<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/object.hpp"
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( null_object ) {
  flusspferd::object null_object;
  BOOST_CHECK(!null_object.is_valid());
}

<commit_msg>more object test stuff<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/object.hpp"
#include "flusspferd/create.hpp"
#include "test_environment.hpp"

BOOST_FIXTURE_TEST_SUITE( with_context, context_fixture )

BOOST_AUTO_TEST_CASE( null_object ) {
  flusspferd::object null_object;
  BOOST_CHECK(!null_object.is_valid());

  flusspferd::object object_copy(null_object);
  BOOST_CHECK(!null_object.is_valid());
}

BOOST_AUTO_TEST_CASE( plain_object ) {
  flusspferd::object const &plain_object = flusspferd::create_object();
  BOOST_CHECK(plain_object.is_valid());

  flusspferd::object object_copy(plain_object);
  BOOST_CHECK(object_copy.is_valid());
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>//
//  inpal_prime.hpp
//  InversePalindrome
//
//  Created by Bryan Triana on 7/13/16.
//  Copyright © 2016 Inverse Palindrome. All rights reserved.
//

#ifndef inpal_prime_hpp
#define inpal_prime_hpp

#include <vector>
#include <string>

namespace inpal
{
    class prime
    {
    public:
        //general purpose functions
        static std::vector<std::size_t> prime_list(std::size_t range);
        static std::vector<std::size_t> factor_list(std::size_t num);
        //special purpose functions
        static std::size_t max_prime(std::size_t range);
        static std::size_t prime_count(std::size_t range);
        static double prime_density(double range);
        static bool prime_test(std::size_t num);
        static bool twin_test(std::size_t num);
        static bool cousin_test(std::size_t num);
        static bool sexy_test(std::size_t num);
        static std::size_t max_palprime(std::size_t range);
        static std::size_t max_factor(std::size_t num);
        static std::size_t factor_count(std::size_t num);
    private:
        //utility algorithms
        static std::vector<bool> prime_sieve(std::size_t range);
        static bool pal_test(std::size_t num);
    };
}

#endif /* inpal_prime_hpp */
<commit_msg>Update inpal_prime.hpp<commit_after>//
//  inpal_prime.hpp
//  InversePalindrome
//
//  Created by Bryan Triana on 7/13/16.
//  Copyright © 2016 Inverse Palindrome. All rights reserved.
//

#ifndef inpal_prime_hpp
#define inpal_prime_hpp

#include <vector>
#include <string>

namespace inpal
{
    class prime
    {
    public:
        //general purpose functions
        static std::vector<std::size_t> prime_list(std::size_t range);
        static std::vector<std::size_t> factor_list(std::size_t num);
        //special purpose functions
        static std::size_t prime_locate(std::size_t pos);
        static std::size_t max_prime(std::size_t range);
        static std::size_t prime_count(std::size_t range);
        static double prime_density(double range);
        static bool prime_test(std::size_t num);
        static bool twin_test(std::size_t num);
        static bool cousin_test(std::size_t num);
        static bool sexy_test(std::size_t num);
        static std::size_t max_palprime(std::size_t range);
        static std::size_t max_factor(std::size_t num);
        static std::size_t factor_count(std::size_t num);
    private:
        //utility algorithms
        static std::vector<bool> prime_sieve(std::size_t range);
        static bool pal_test(std::size_t num);
    };
}

#endif /* inpal_prime_hpp */
<|endoftext|>


<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("stop_tracker_timeout", &session_settings::stop_tracker_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_timeout", &session_settings::request_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("urlseed_wait_retry", &session_settings::urlseed_wait_retry)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("optimistic_unchoke_interval", &session_settings::optimistic_unchoke_interval)
        .def_readwrite("num_want", &session_settings::num_want)
        .def_readwrite("initial_picker_threshold", &session_settings::initial_picker_threshold)
        .def_readwrite("allowed_fast_set_size", &session_settings::allowed_fast_set_size)
        .def_readwrite("max_outstanding_disk_bytes_per_connection", &session_settings::max_outstanding_disk_bytes_per_connection)
        .def_readwrite("handshake_timeout", &session_settings::handshake_timeout)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
        .def_readwrite("free_torrent_hashes", &session_settings::free_torrent_hashes)
        .def_readwrite("upnp_ignore_nonrouters", &session_settings::upnp_ignore_nonrouters)
        .def_readwrite("send_buffer_watermark", &session_settings::send_buffer_watermark)
        .def_readwrite("auto_upload_slots", &session_settings::auto_upload_slots)
        .def_readwrite("auto_upload_slots_rate_based", &session_settings::auto_upload_slots_rate_based)
        .def_readwrite("use_parole_mode", &session_settings::use_parole_mode)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_buffer_chunk_size", &session_settings::cache_buffer_chunk_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
        .def_readwrite("use_read_cache", &session_settings::use_read_cache)
        .def_readwrite("disk_io_write_mode", &session_settings::disk_io_write_mode)
        .def_readwrite("disk_io_read_mode", &session_settings::disk_io_read_mode)
        .def_readwrite("coalesce_reads", &session_settings::coalesce_reads)
        .def_readwrite("coalesce_writes", &session_settings::coalesce_writes)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("peer_turnover", &session_settings::peer_turnover)
        .def_readwrite("peer_turnover_cutoff", &session_settings::peer_turnover_cutoff)
        .def_readwrite("close_redundant_connections", &session_settings::close_redundant_connections)
        .def_readwrite("auto_scrape_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("auto_scrape_min_interval", &session_settings::auto_scrape_min_interval)
        .def_readwrite("max_peerlist_size", &session_settings::max_peerlist_size)
        .def_readwrite("max_paused_peerlist_size", &session_settings::max_paused_peerlist_size)
        .def_readwrite("min_announce_interval", &session_settings::min_announce_interval)
        .def_readwrite("prioritize_partial_pieces", &session_settings::prioritize_partial_pieces)
        .def_readwrite("auto_manage_startup", &session_settings::auto_manage_startup)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("announce_to_all_trackers", &session_settings::announce_to_all_trackers)
        .def_readwrite("prefer_udp_trackers", &session_settings::prefer_udp_trackers)
        .def_readwrite("strict_super_seeding", &session_settings::strict_super_seeding)
        .def_readwrite("seeding_piece_quota", &session_settings::seeding_piece_quota)
        .def_readwrite("max_sparse_regions", &session_settings::max_sparse_regions)
#ifndef TORRENT_DISABLE_MLOCK
        .def_readwrite("lock_disk_cache", &session_settings::lock_disk_cache)
#endif
        .def_readwrite("max_rejects", &session_settings::max_rejects)
        .def_readwrite("recv_socket_buffer_size", &session_settings::recv_socket_buffer_size)
        .def_readwrite("send_socket_buffer_size", &session_settings::send_socket_buffer_size)
        .def_readwrite("optimize_hashing_for_speed", &session_settings::optimize_hashing_for_speed)
        .def_readwrite("file_checks_delay_per_block", &session_settings::file_checks_delay_per_block)
        .def_readwrite("disk_cache_algorithm", &session_settings::disk_cache_algorithm)
        .def_readwrite("read_cache_line_size", &session_settings::read_cache_line_size)
        .def_readwrite("write_cache_line_size", &session_settings::write_cache_line_size)
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;

    enum_<session_settings::disk_cache_algo_t>("disk_cache_algo_t")
        .value("lru", session_settings::lru)
        .value("largest_contiguous", session_settings::largest_contiguous)
    ;

    enum_<session_settings::io_buffer_mode_t>("io_buffer_mode_t")
        .value("enable_os_cache", session_settings::enable_os_cache)
        .value("disable_os_cache_for_aligned_files", session_settings::disable_os_cache_for_aligned_files)
        .value("disable_os_cache", session_settings::disable_os_cache)
    ;

    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_DHT
    class_<dht_settings>("dht_settings")
        .def_readwrite("max_peers_reply", &dht_settings::max_peers_reply)
        .def_readwrite("search_branching", &dht_settings::search_branching)
        .def_readwrite("service_port", &dht_settings::service_port)
        .def_readwrite("max_fail_count", &dht_settings::max_fail_count)
    ;
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<commit_msg>Remove 'max_outstanding_disk_bytes_per_connection' from the session_settings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("stop_tracker_timeout", &session_settings::stop_tracker_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_timeout", &session_settings::request_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("urlseed_wait_retry", &session_settings::urlseed_wait_retry)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("optimistic_unchoke_interval", &session_settings::optimistic_unchoke_interval)
        .def_readwrite("num_want", &session_settings::num_want)
        .def_readwrite("initial_picker_threshold", &session_settings::initial_picker_threshold)
        .def_readwrite("allowed_fast_set_size", &session_settings::allowed_fast_set_size)
        .def_readwrite("handshake_timeout", &session_settings::handshake_timeout)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
        .def_readwrite("free_torrent_hashes", &session_settings::free_torrent_hashes)
        .def_readwrite("upnp_ignore_nonrouters", &session_settings::upnp_ignore_nonrouters)
        .def_readwrite("send_buffer_watermark", &session_settings::send_buffer_watermark)
        .def_readwrite("auto_upload_slots", &session_settings::auto_upload_slots)
        .def_readwrite("auto_upload_slots_rate_based", &session_settings::auto_upload_slots_rate_based)
        .def_readwrite("use_parole_mode", &session_settings::use_parole_mode)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_buffer_chunk_size", &session_settings::cache_buffer_chunk_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
        .def_readwrite("use_read_cache", &session_settings::use_read_cache)
        .def_readwrite("disk_io_write_mode", &session_settings::disk_io_write_mode)
        .def_readwrite("disk_io_read_mode", &session_settings::disk_io_read_mode)
        .def_readwrite("coalesce_reads", &session_settings::coalesce_reads)
        .def_readwrite("coalesce_writes", &session_settings::coalesce_writes)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("peer_turnover", &session_settings::peer_turnover)
        .def_readwrite("peer_turnover_cutoff", &session_settings::peer_turnover_cutoff)
        .def_readwrite("close_redundant_connections", &session_settings::close_redundant_connections)
        .def_readwrite("auto_scrape_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("auto_scrape_min_interval", &session_settings::auto_scrape_min_interval)
        .def_readwrite("max_peerlist_size", &session_settings::max_peerlist_size)
        .def_readwrite("max_paused_peerlist_size", &session_settings::max_paused_peerlist_size)
        .def_readwrite("min_announce_interval", &session_settings::min_announce_interval)
        .def_readwrite("prioritize_partial_pieces", &session_settings::prioritize_partial_pieces)
        .def_readwrite("auto_manage_startup", &session_settings::auto_manage_startup)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("announce_to_all_trackers", &session_settings::announce_to_all_trackers)
        .def_readwrite("prefer_udp_trackers", &session_settings::prefer_udp_trackers)
        .def_readwrite("strict_super_seeding", &session_settings::strict_super_seeding)
        .def_readwrite("seeding_piece_quota", &session_settings::seeding_piece_quota)
        .def_readwrite("max_sparse_regions", &session_settings::max_sparse_regions)
#ifndef TORRENT_DISABLE_MLOCK
        .def_readwrite("lock_disk_cache", &session_settings::lock_disk_cache)
#endif
        .def_readwrite("max_rejects", &session_settings::max_rejects)
        .def_readwrite("recv_socket_buffer_size", &session_settings::recv_socket_buffer_size)
        .def_readwrite("send_socket_buffer_size", &session_settings::send_socket_buffer_size)
        .def_readwrite("optimize_hashing_for_speed", &session_settings::optimize_hashing_for_speed)
        .def_readwrite("file_checks_delay_per_block", &session_settings::file_checks_delay_per_block)
        .def_readwrite("disk_cache_algorithm", &session_settings::disk_cache_algorithm)
        .def_readwrite("read_cache_line_size", &session_settings::read_cache_line_size)
        .def_readwrite("write_cache_line_size", &session_settings::write_cache_line_size)
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;

    enum_<session_settings::disk_cache_algo_t>("disk_cache_algo_t")
        .value("lru", session_settings::lru)
        .value("largest_contiguous", session_settings::largest_contiguous)
    ;

    enum_<session_settings::io_buffer_mode_t>("io_buffer_mode_t")
        .value("enable_os_cache", session_settings::enable_os_cache)
        .value("disable_os_cache_for_aligned_files", session_settings::disable_os_cache_for_aligned_files)
        .value("disable_os_cache", session_settings::disable_os_cache)
    ;

    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_DHT
    class_<dht_settings>("dht_settings")
        .def_readwrite("max_peers_reply", &dht_settings::max_peers_reply)
        .def_readwrite("search_branching", &dht_settings::search_branching)
        .def_readwrite("service_port", &dht_settings::service_port)
        .def_readwrite("max_fail_count", &dht_settings::max_fail_count)
    ;
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<|endoftext|>


<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("auto_scraped_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;
    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<commit_msg>Update python bindings session_settings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("stop_tracker_timeout", &session_settings::stop_tracker_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_timeout", &session_settings::request_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("urlseed_wait_retry", &session_settings::urlseed_wait_retry)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("optimistic_unchoke_multiplier", &session_settings::optimistic_unchoke_multiplier)
        .def_readwrite("num_want", &session_settings::num_want)
        .def_readwrite("initial_picker_threshold", &session_settings::initial_picker_threshold)
        .def_readwrite("allowed_fast_set_size", &session_settings::allowed_fast_set_size)
        .def_readwrite("max_outstanding_disk_bytes_per_connection", &session_settings::max_outstanding_disk_bytes_per_connection)
        .def_readwrite("handshake_timeout", &session_settings::handshake_timeout)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
        .def_readwrite("free_torrent_hashes", &session_settings::free_torrent_hashes)
        .def_readwrite("upnp_ignore_nonrouters", &session_settings::upnp_ignore_nonrouters)
        .def_readwrite("send_buffer_watermark", &session_settings::send_buffer_watermark)
        .def_readwrite("auto_upload_slots", &session_settings::auto_upload_slots)
        .def_readwrite("auto_upload_slots_rate_based", &session_settings::auto_upload_slots_rate_based)
        .def_readwrite("use_parole_mode", &session_settings::use_parole_mode)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_buffer_chunk_size", &session_settings::cache_buffer_chunk_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
        .def_readwrite("use_read_cache", &session_settings::use_read_cache)
        .def_readwrite("disk_io_write_mode", &session_settings::disk_io_write_mode)
        .def_readwrite("disk_io_read_mode", &session_settings::disk_io_read_mode)
        .def_readwrite("coalesce_reads", &session_settings::coalesce_reads)
        .def_readwrite("coalesce_writes", &session_settings:coalesce_writes)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::automanaged_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("peer_turnover", &session_settings::peer_turnover)
        .def_readwrite("peer_turnover_cutoff", &session_settings::peer_turnover_cutoff)
        .def_readwrite("close_redundant_connections", &session_settings::close_redundant_connections)
        .def_readwrite("auto_scrape_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("auto_scrape_min_interval", &session_settings::auto_scrape_min_interval)
        .def_readwrite("max_peerlist_size", &session_settings::max_peerlist_size)
        .def_readwrite("max_paused_peerlist_size", &session_settings::max_paused_peerlist_size)
        .def_readwrite("min_announce_interval", &session_settings::min_announce_interval)
        .def_readwrite("prioritize_partial_pieces", &session_settings::prioritize_partial_pieces)
        .def_readwrite("auto_manage_startup", &session_settings::auto_manage_startup)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("announce_to_all_trackers", &session_settings::announce_to_all_trackers)
        .def_readwrite("prefer_udp_trackers", &session_settings::prefer_udp_trackers)
        .def_readwrite("strict_super_seeding", &session_settings::strict_super_seeding)
        .def_readwrite("seeding_piece_quota", &session_settings::seeding_piece_quota)
        .def_readwrite("max_sparse_regions", &session_settings::max_sparse_regions)
#ifndef TORRENT_DISABLE_MLOCK
        .def_readwrite("lock_disk_cache", &session_settings::lock_disk_cache)
#endif
        .def_readwrite("max_rejects", &session_settings::max_rejects)
        .def_readwrite("recv_socket_buffer_size", &session_settings::recv_socket_buffer_size)
        .def_readwrite("send_socket_buffer_size", &session_settings::send_socket_buffer_size)
        .def_readwrite("optimize_hashing_for_speed", &session_settings::optimize_hashing_for_speed)
        .def_readwrite("file_checks_delay_per_block", &session_settings::file_checks_delay_per_block)
        .def_readwrite("disk_cache_algorithm", &session_settings::disk_cache_algorithm)
        .def_readwrite("read_cache_line_size", &session_settings::read_cache_line_size)
        .def_readwrite("write_cache_line_size", &session_settings::write_cache_line_size)
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;

    enum_<session_settings::disk_cache_algo_t("disk_cache_algo_t")
        .value("lru", session_settings::disk_cache_algo_t::lru)
        .value("largest_contiguous", session_settings::disk_cache_algo_t::largest_contiguous)
    ;

    enum_<session_settings::io_buffer_mode_t("io_buffer_mode_t")
        .value("enable_os_cache", session_settings::io_buffer_mode_t::enable_os_cache)
        .value("disable_os_cache_for_aligned_files", session_settings::io_buffer_mode_t:disable_os_cache_for_aligned_files)
        .value("disable_os_cache", session_settings::io_buffer_mode_t::disable_os_cache)
    ;

    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_DHT
    class_<dht_settings>("dht_settings")
        .def_readwrite("max_peers_reply", dht_settings::max_peers_reply)
        .def_readwrite("search_branching", dht_settings::search_branching)
        .def_readwrite("service_port", dht_settings::service_port)
        .def_readwrite("max_fail_count", dht_settings::max_fail_count)
    ;
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<|endoftext|>


<commit_before>/******************************************************************************
 *
 * fci.cpp
 *
 * This program loads basis functions and nuclear field information to
 * form a Hamiltonian and compute its eigenvalues.
 *
 * JDWhitfield
 * Dartmouth, 2016-2017
 *
 *
 *      This program is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 *****************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<fstream>
#include<assert.h>
#include<iomanip>
#include<random>
#include<chrono>
#include<algorithm>
#include"parser.h"
#include"ci_matrix.h"
#include"libint_interface.h"

int
main(int argc, char *argv[])
{
    using std::chrono::high_resolution_clock;

    std::cout.precision(10);
    std::cout << std::scientific;

    int debug=2;

    //timing variables
    //std::chrono::system_clock::time_point start_time;
    std::chrono::duration<double> time_elapsed;

    // ****************************
    // * Parse commandline inputs *
    // ****************************
    if (argc > 1)
    {
	    if(!strcmp(argv[1],"-h"))
	    {
            std::cout << "fci [basis_func] [nuc_field]";
            std::cout << "\n\tDefault files are used when called with no parameters.\n\n";
		    return 0;
	    }
    }

    const auto basis_fname=(argc>1) ? argv[1] : "basis_funcs";
    const auto nuc_fname  =(argc>2) ? argv[2] : "nuc_field";

    // ****************************
    // * Output files             *
    // ****************************
    std::fstream fonebody;
    system("touch ham_ov.dat");
    system("rm ham_ov.dat");
    system("touch ham_ov.dat");
    fonebody.open("ham_ov.dat");

   /*
     Format ham_ov.dat-
     number of basis
     Ov matrix
     Core Hamiltonian matrix
     Nuclear Repulsion
    */

    std::fstream ftwobody;
    system("touch 2_ele.dat");
    system("rm 2_ele.dat");
    system("touch 2_ele.dat");
    ftwobody.open("2_ele.dat");
    /*
     Format 2_ele.dat-
     number of reduced integral
     i,j,k,l, ee(i,j,k,l)
    */

    //increase the printout precision
    fonebody.precision(10);
    ftwobody.precision(10);
    fonebody << std::scientific << std::showpos;
    ftwobody << std::scientific;

    // ****************************
    // * Parse data files         *
    // ****************************
    libint2::BasisSet shells = parse_basisfile(basis_fname);

    if(debug)
    {
        printf("Basis set\n");
        for( auto s : shells)
            std::cout << s << "\n";
    }

    //number of spin orbitals in the basis set
    int M=2*shells.nbf();

    fonebody << M << "\n";

    //number of electrons
    int N=-99;

    /*
    //number of 2e- integrals
    int m=(M/2) - 1;
    int nints=term4(m,m,m,m)+1;
    */

    auto atoms = parse_nucfile(nuc_fname,N);

    if(N==-99)
    {
        std::cout << "Nelec not set\n";
        throw;
    }

    Matrix S, h;
    std::vector<double> AOInts;

    //FCI matrix dimension
    int D=nchoosek(M,N);

    //libints
    auto start_time = high_resolution_clock::now();
    Matrix hT,hV;
    get_libints(shells,atoms,S,hV,hT,AOInts);
    h=hT+hV;
    time_elapsed=(high_resolution_clock::now()-start_time);
    std::cout << "Took " << time_elapsed.count() << " seconds to get AO Ints\n";

    if(debug)
    {
        std::cout << "S\n" << S << "\n\n";
        fonebody  << S << "\n";
        std::cout << "h\n" << h << "\n\n";
        fonebody  << h << "\n";
        std::cout << "AO 2body integrals (chemist's notation)\n";

	//temporary header to be overwritten by the number of integrals
        ftwobody  << "AO       \n";
	int nints=0;
        for(auto p=0; p!=M/2; p++) //unique integral labels, looping scheme from libint
            for(auto q=0; q<=p; q++)
                for(auto r=0; r<=p; r++)
                    for(auto s=0; s<= (p==r ? q : r) ; s++)
                        if(std::abs(AOInts[term4(p,q,r,s)]) > 1e-5)
			{
				std::cout << term4(p,q,r,s) << ": ["
					  << p << q << "|" << r << s << "] = " << AOInts[term4(p,q,r,s)] << std::endl;

 			        ftwobody << p << " " << q << " " << r << " " << s << " " << AOInts[term4(p,q,r,s)] << std::endl;
				nints++;
			}
	//go back to write the number of integrals at the top
        ftwobody.seekp(0);
	//header
	ftwobody  << nints;
    }

    Matrix h2;
    std::vector<double> MOInts;
    if(Matrix(S).isIdentity(1e-9))
    {
        //nothing changes if S is the identity matrix
        h2=h;
        MOInts=AOInts;
        std::cout<<"We don't need to orthogonalize\n";
    }
    else
    {// *     ORTHOGONALIZATION    *

        /***********************************************************/
        // Transformation matricies
        //
        //Basis transform to an orthogonal space
        //C = C(W) = XW for any WW^\dag =\id
        //

        Eigen::SelfAdjointEigenSolver<Matrix> Eigensystem(S);
        Matrix s=Matrix(Eigensystem.eigenvalues());
        //check which eigenvalues are non-trivial to avoid linear dependence
        //then compute s^{-1/2}
        Matrix shalf;
        shalf.resize(M/2,M/2);    // set size
        shalf.fill(0);            // make sure all elements are zero
        //make sure its a column vector
        if(s.rows()<s.cols())
            s.transposeInPlace();

        for(int j=0; j<s.rows(); j++)
        {
            if(std::abs(s(j,0))>1e-6)
                shalf(j,j)=1/sqrt(s(j,0));
            else
                shalf(j,j)=0;
        }

        //orthogonalization transform
        //Here we're just using W=\id
        Matrix C;
        bool CANONICAL=true;
        if(CANONICAL)
            C=Matrix(Eigensystem.eigenvectors()*shalf);
        else
            C=Matrix(Eigensystem.eigenvectors()*shalf*Eigensystem.eigenvectors().adjoint());

        //time the transformations
        start_time = high_resolution_clock::now();

        h2       =Matrix(C.adjoint())*h*C;   //One-body transform
        MOInts   = transform4(M,C,AOInts);//two-body transform

        time_elapsed = high_resolution_clock::now() - start_time;
        std::cout << "Transformation to (canonical) orthogonal basis took " << time_elapsed.count() << "ms \n";

    }

    if(debug)
    {
        std::cout << "h\n";
        std::cout << h2 << "\n\n";
        std::cout << "Orthogonalized Integrals\n";
        for(auto m : MOInts)
            std::cout << m << "\n";
    }

    //LAPACK
    start_time=high_resolution_clock::now();

    double* w=ci_eigenvals(M,N,MOInts,h2,debug);

    time_elapsed = std::chrono::high_resolution_clock::now() - start_time;
    std::cout << "Making matrix and getting eigenvalues took " << time_elapsed.count()
              << "s to get eigenvalues.\n";

    std::cout << "\nEigenvalues( "<< D << " ) :\n --------- \n";

    std::cout.precision(10);
    std::cout << std::scientific;
    for(int i=0; i<D; i++)
        std::cout << w[i]  << "\n";

    // ****************************
    // * Close output files       *
    // ****************************

    fonebody.close();

    return 0;
}
<commit_msg>Refactored fci.cpp, next we eval UG generators<commit_after>/******************************************************************************
 *
 * fci.cpp
 *
 * This program loads basis functions and nuclear field information to
 * form a Hamiltonian and compute its eigenvalues.
 *
 * JDWhitfield
 * Dartmouth, 2016-2017
 *
 *
 *      This program is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 *****************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<fstream>
#include<assert.h>
#include<iomanip>
#include<random>
#include<chrono>
#include<algorithm>
#define EIGEN_USE_LAPACKE
#include"parser.h"
#include"ci_matrix.h"
#include"weyl.h"
#include"libint_interface.h"

int
get_integrals(const char* basis_fname, const char* nuc_fname, int& M, int& N, Matrix& h2, std::vector<double>& h4)
{

    bool debug=true;
    bool CANONICAL=true;// if false use symmetric orthogonalization

    //parse files
    auto atoms = parse_nucfile(nuc_fname,N);
    libint2::BasisSet shells = parse_basisfile(basis_fname);

    //set M
    M=2*shells.nbf();

    //internal matricies
    Matrix hT,hV;
    Matrix S, h;
    std::vector<double> AOInts;

    //return variables
    //    Matrix h2;
    //    std::vector<double> MOInts;

    auto start_time = std::chrono::high_resolution_clock::now();

    //libints
    get_libints(shells,atoms,S,hV,hT,AOInts);
    h=hT+hV;

    auto end_time=std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> time_elapsed= end_time-start_time;

    if(debug)
	    std::cout << "Took " << time_elapsed.count() << " seconds to get AO Ints\n";

    if(Matrix(S).isIdentity(1e-9))
    {
        //nothing changes if S is the identity matrix
        h2=h;
        h4=AOInts;
	return 0;
        //std::cout<<"We don't need to orthogonalize\n";
    }
    else
    {// *     ORTHOGONALIZATION    *

        /***********************************************************/
        // Transformation matricies
        //
        //Basis transform to an orthogonal space
	//X=Us^{-1/2} when S=U^+ s U
        //C = C(W) = XW for any WW^\dag =\id
        //

	if(debug)
		std::cout << S << std::endl;

	if(debug)
		std::cout << S.eigenvalues() << std::endl;

        Eigen::SelfAdjointEigenSolver<Matrix> Eigensystem(S);

	if(debug)
		std::cout << "here\n";

        Matrix s=Matrix(Eigensystem.eigenvalues());
        //check which eigenvalues are non-trivial to avoid linear dependence
        //then compute s^{-1/2}
        Matrix shalf;
        shalf.resize(M/2,M/2);    // set size
        shalf.fill(0);            // make sure all elements are zero
        //make sure its a column vector
        if(s.rows()<s.cols())
            s.transposeInPlace();

        for(int j=0; j<s.rows(); j++)
        {
            if(std::abs(s(j,0))>1e-6)
                shalf(j,j)=1/sqrt(s(j,0));
            else
                shalf(j,j)=0;
        }

        Matrix C;
        if(CANONICAL)  //if canonical W=\id
            C=Matrix(Eigensystem.eigenvectors()*shalf);
        else  	       //if symmetric W=U^+
            C=Matrix(Eigensystem.eigenvectors()*shalf*Eigensystem.eigenvectors().adjoint());

	if(debug) //time the transformations
		start_time = std::chrono::high_resolution_clock::now();

        h2       =Matrix(C.adjoint())*h*C;   //One-body transform
        h4       =transform4(M,C,AOInts);//two-body transform

	if(debug)
	{
		time_elapsed = std::chrono::high_resolution_clock::now() - start_time;
		std::cout << "Transformation to (canonical) orthogonal basis took " << time_elapsed.count() << "ms \n";
	}

    }

    return 0;

}

int
main(int argc, char *argv[])
{
    using std::chrono::high_resolution_clock;

    std::cout.precision(10);
    std::cout << std::scientific;

    int debug=2;

    //timing variables
    //std::chrono::system_clock::time_point start_time;
    std::chrono::duration<double> time_elapsed;

    // ****************************
    // * Parse commandline inputs *
    // ****************************
    if (argc > 1)
    {
	    if(!strcmp(argv[1],"-h"))
	    {
		    std::cout << "fci [basis_func] [nuc_field]";
		    std::cout << "\n\tDefault files are used when called with no parameters.\n\n";
		    return 0;
	    }
    }

    const char* basis_fname=(argc>1) ? argv[1] : "basis_funcs";
    const char* nuc_fname  =(argc>2) ? argv[2] : "nuc_field";

    int M,N;
    Matrix h2;
    std::vector<double>  h4;

    if(get_integrals(basis_fname, nuc_fname, M, N,  h2, h4)!=0)
    {
	    std::cout << "Problem getting integrals\n";
    }

    // ****************************
    // * Output files             *
    // ****************************
    /*
    std::fstream fonebody;
    system("touch ham_ov.dat");
    system("rm ham_ov.dat");
    system("touch ham_ov.dat");
    fonebody.open("ham_ov.dat");

    // Format ham_ov.dat-
    // number of basis
    // Ov matrix
    // Core Hamiltonian matrix
    // Nuclear Repulsion

    std::fstream ftwobody;
    system("touch 2_ele.dat");
    system("rm 2_ele.dat");
    system("touch 2_ele.dat");
    ftwobody.open("2_ele.dat");
    // Format 2_ele.dat-
    // number of reduced integral
    //  i,j,k,l, ee(i,j,k,l)

    //increase the printout precision
    fonebody.precision(10);
    ftwobody.precision(10);
    fonebody << std::scientific << std::showpos;
    ftwobody << std::scientific;

    fonebody << M << "\n";
    fonebody << h2 << "\n";

    //temporary header to be overwritten by the number of integrals
    ftwobody  << "h4       \n";
    int nints=0;
    for(auto p=0; p!=M/2; p++) //unique integral labels, looping scheme from libint
            for(auto q=0; q<=p; q++)
                for(auto r=0; r<=p; r++)
                    for(auto s=0; s<= (p==r ? q : r) ; s++)
                        if(std::abs(h4[term4(p,q,r,s)]) > 1e-5)
			{
				//std::cout << term4(p,q,r,s) << ": ["
				//	  << p << q << "|" << r << s << "] = "
				//	  << h4[term4(p,q,r,s)] << std::endl;

 			        ftwobody << p << " " << q << " " << r << " " << s << " "
				         << h4[term4(p,q,r,s)] << std::endl;
				nints++;
			}
    //go back to write the number of integrals at the top
    ftwobody.seekp(0);
    //header
    ftwobody  << nints;

    //number of 2e- integrals
    int m=(M/2) - 1;
    int nints=term4(m,m,m,m)+1;

    fonebody.close();
    ftwobody.close();
    */

    //FCI matrix dimension
    int D=nchoosek(M,N);

    //LAPACK
    auto start_time=std::chrono::high_resolution_clock::now();

    //here is the basic CI algorithm
    double* w=ci_eigenvals(M,N,h4,h2,debug);

    time_elapsed = std::chrono::high_resolution_clock::now() - start_time;
    std::cout << "Making matrix and getting eigenvalues took " << time_elapsed.count()
              << "s to get eigenvalues.\n";

    std::cout << "\nEigenvalues( "<< D << " ) :\n --------- \n";

    std::cout.precision(10);
    std::cout << std::scientific;
    for(int i=0; i<D; i++)
        std::cout << w[i]  << "\n";

    return 0;
}
<|endoftext|>


<commit_before>/*
Description:
This is a example code for Sandbox Electronics' I2C/SPI to UART bridge module.
You can get one of those products on
http://sandboxelectronics.com
Version:
V0.1
Release Date:
2014-02-16
Author:
Tiequan Shao          info@sandboxelectronics.com
Lisence:
CC BY-NC-SA 3.0
Please keep the above information when you use this code in your project.
*/

#ifndef _SC16IS750_H_
#define _SC16IS750_H_

#include "application.h"

#ifdef ARDUINO
  #if (ARDUINO >= 100)
   #include <Arduino.h>
  #else
   #include <WProgram.h>
   #include <pins_arduino.h>
  #endif
#elif USE_SPARK_CORE_V02
  #include <spark_related_stuff_v2.h>
#elif USE_SPARK_CORE_V01
  #include <spark_related_stuff_v1.h>
#endif

/*
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif
*/

//Device Address

//A:VDD
//B:GND
//C:SCL
//D:SDA
#define     SC16IS750_ADDRESS_AA     (0X90)
#define     SC16IS750_ADDRESS_AB     (0X92)
#define     SC16IS750_ADDRESS_AC     (0X94)
#define     SC16IS750_ADDRESS_AD     (0X96)
#define     SC16IS750_ADDRESS_BA     (0X98)
#define     SC16IS750_ADDRESS_BB     (0X9A)
#define     SC16IS750_ADDRESS_BC     (0X9C)
#define     SC16IS750_ADDRESS_BD     (0X9E)
#define     SC16IS750_ADDRESS_CA     (0XA0)
#define     SC16IS750_ADDRESS_CB     (0XA2)
#define     SC16IS750_ADDRESS_CC     (0XA4)
#define     SC16IS750_ADDRESS_CD     (0XA6)
#define     SC16IS750_ADDRESS_DA     (0XA8)
#define     SC16IS750_ADDRESS_DB     (0XAA)
#define     SC16IS750_ADDRESS_DC     (0XAC)
#define     SC16IS750_ADDRESS_DD     (0XAE)

//General Registers
#define     SC16IS750_REG_RHR        (0x00)
#define     SC16IS750_REG_THR        (0X00)
#define     SC16IS750_REG_IER        (0X01)
#define     SC16IS750_REG_FCR        (0X02)
#define     SC16IS750_REG_IIR        (0X02)
#define     SC16IS750_REG_LCR        (0X03)
#define     SC16IS750_REG_MCR        (0X04)
#define     SC16IS750_REG_LSR        (0X05)
#define     SC16IS750_REG_MSR        (0X06)
#define     SC16IS750_REG_SPR        (0X07)
#define     SC16IS750_REG_TCR        (0X06)
#define     SC16IS750_REG_TLR        (0X07)
#define     SC16IS750_REG_TXLVL      (0X08)
#define     SC16IS750_REG_RXLVL      (0X09)
#define     SC16IS750_REG_IODIR      (0X0A)
#define     SC16IS750_REG_IOSTATE    (0X0B)
#define     SC16IS750_REG_IOINTENA   (0X0C)
#define     SC16IS750_REG_IOCONTROL  (0X0E)
#define     SC16IS750_REG_EFCR       (0X0F)

//Special Registers
#define     SC16IS750_REG_DLL        (0x00)
#define     SC16IS750_REG_DLH        (0X01)

//Enhanced Registers
#define     SC16IS750_REG_EFR        (0X02)
#define     SC16IS750_REG_XON1       (0X04)
#define     SC16IS750_REG_XON2       (0X05)
#define     SC16IS750_REG_XOFF1      (0X06)
#define     SC16IS750_REG_XOFF2      (0X07)

//
#define     SC16IS750_INT_CTS        (0X80)
#define     SC16IS750_INT_RTS        (0X40)
#define     SC16IS750_INT_XOFF       (0X20)
#define     SC16IS750_INT_SLEEP      (0X10)
#define     SC16IS750_INT_MODEM      (0X08)
#define     SC16IS750_INT_LINE       (0X04)
#define     SC16IS750_INT_THR        (0X02)
#define     SC16IS750_INT_RHR        (0X01)

//Application Related

#define     SC16IS750_CRYSTCAL_FREQ (14745600UL)
//#define 	SC16IS750_CRYSTCAL_FREQ (1843200UL)
//#define     SC16IS750_CRYSTCAL_FREQ (16000000UL)
//#define     SC16IS750_DEBUG_PRINT   (0)
#define     SC16IS750_PROTOCOL_I2C  (0)
#define     SC16IS750_PROTOCOL_SPI  (1)

class SC16IS750 // : public Stream
{
    public:
        SC16IS750(uint8_t prtcl = SC16IS750_PROTOCOL_I2C, uint8_t addr = SC16IS750_ADDRESS_AD);
        void begin(uint32_t baud);
        int read();
        size_t write(uint8_t val);
        int available();
        void pinMode(uint8_t pin, uint8_t io);
        void digitalWrite(uint8_t pin, uint8_t value);
        uint8_t digitalRead(uint8_t pin);
		uint8_t ping();
	//	void setTimeout(uint32_t);
	//	size_t readBytes(char *buffer, size_t length);
		int peek();
		void flush();
		uint8_t GPIOGetPortState(void);
		uint8_t InterruptPendingTest(void);
		void    SetPinInterrupt(uint8_t io_int_ena);
		void    InterruptControl(uint8_t int_ena);
		void    ModemPin(uint8_t gpio); //gpio == 0, gpio[7:4] are modem pins, gpio == 1 gpio[7:4] are gpios
		void    GPIOLatch(uint8_t latch);

    private:
        uint8_t device_address_sspin;
        uint8_t protocol;
	//	uint32_t timeout;
        int16_t SetBaudrate(uint32_t baudrate);
        uint8_t ReadRegister(uint8_t reg_addr);
        void    WriteRegister(uint8_t reg_addr, uint8_t val);
        void    SetLine(uint8_t data_length, uint8_t parity_select, uint8_t stop_length );
        void    GPIOSetPinMode(uint8_t pin_number, uint8_t i_o);
        void    GPIOSetPinState(uint8_t pin_number, uint8_t pin_state);

        uint8_t GPIOGetPinState(uint8_t pin_number);
        void    GPIOSetPortMode(uint8_t port_io);
        void    GPIOSetPortState(uint8_t port_state);
        void    ResetDevice(void);

        void    __isr(void);
        void    FIFOEnable(uint8_t fifo_enable);
        void    FIFOReset(uint8_t rx_fifo);
        void    FIFOSetTriggerLevel(uint8_t rx_fifo, uint8_t length);
        uint8_t FIFOAvailableData(void);
        uint8_t FIFOAvailableSpace(void);
        void    WriteByte(uint8_t val);
        int     ReadByte(void);
        void    EnableTransmit(uint8_t tx_enable);
	//	int16_t readwithtimeout();
		int 	peek_buf;
		uint8_t peek_flag;

};

#endif
<commit_msg>Delete SC16IS750-library.cpp<commit_after><|endoftext|>


<commit_before>#include "mavlink_commands.h"
#include "system_impl.h"
#include <future>
#include <memory>

namespace dronecode_sdk {

// TODO: Currently the mavlink command handling is made in a way to only
//       process one command at any time. Therefore, the work state is global
//       for this whole class.
//       The limitation is made because:
//       - We are not sure what exactly will happen if the commands are sent in parallel
//         and what kind of edge cases we might run into.
//       - The queue used does not support going through and checking each and every
//         item yet.

MAVLinkCommands::MAVLinkCommands(SystemImpl &parent) : _parent(parent)
{
    _parent.register_mavlink_message_handler(
        MAVLINK_MSG_ID_COMMAND_ACK,
        std::bind(&MAVLinkCommands::receive_command_ack, this, std::placeholders::_1),
        this);
}

MAVLinkCommands::~MAVLinkCommands()
{
    _parent.unregister_all_mavlink_message_handlers(this);
}

MAVLinkCommands::Result MAVLinkCommands::send_command(const MAVLinkCommands::CommandInt &command)
{
    // We wrap the async call with a promise and future.
    auto prom = std::make_shared<std::promise<Result>>();
    auto res = prom->get_future();

    queue_command_async(command, [&prom](Result result, float progress) {
        UNUSED(progress);
        // We can only fulfill the promise once in C++11.
        // Therefore we have to ignore the IN_PROGRESS state and wait
        // for the final result.
        if (result != Result::IN_PROGRESS) {
            prom->set_value(result);
        }
    });

    // Block now to wait for result.
    return res.get();
}

MAVLinkCommands::Result MAVLinkCommands::send_command(const MAVLinkCommands::CommandLong &command)
{
    // We wrap the async call with a promise and future.
    auto prom = std::make_shared<std::promise<Result>>();
    auto res = prom->get_future();

    queue_command_async(command, [&prom](Result result, float progress) {
        UNUSED(progress);
        // We can only fulfill the promise once in C++11.
        // Therefore we have to ignore the IN_PROGRESS state and wait
        // for the final result.
        if (result != Result::IN_PROGRESS) {
            prom->set_value(result);
        }
    });

    return res.get();
}

void MAVLinkCommands::queue_command_async(const CommandInt &command,
                                          command_result_callback_t callback)
{
    // LogDebug() << "Command " << (int)(command.command) << " to send to "
    //  << (int)(command.target_system_id)<< ", " << (int)(command.target_component_id;

    Work new_work{};
    mavlink_msg_command_int_pack(GCSClient::system_id,
                                 GCSClient::component_id,
                                 &new_work.mavlink_message,
                                 command.target_system_id,
                                 command.target_component_id,
                                 command.frame,
                                 command.command,
                                 command.current,
                                 command.autocontinue,
                                 command.params.param1,
                                 command.params.param2,
                                 command.params.param3,
                                 command.params.param4,
                                 command.params.x,
                                 command.params.y,
                                 command.params.z);

    new_work.callback = callback;
    new_work.mavlink_command = command.command;
    _work_queue.push_back(new_work);
}

void MAVLinkCommands::queue_command_async(const CommandLong &command,
                                          command_result_callback_t callback)
{
    // LogDebug() << "Command " << (int)(command.command) << " to send to "
    //  << (int)(command.target_system_id)<< ", " << (int)(command.target_component_id;

    Work new_work{};
    mavlink_msg_command_long_pack(GCSClient::system_id,
                                  GCSClient::component_id,
                                  &new_work.mavlink_message,
                                  command.target_system_id,
                                  command.target_component_id,
                                  command.command,
                                  command.confirmation,
                                  command.params.param1,
                                  command.params.param2,
                                  command.params.param3,
                                  command.params.param4,
                                  command.params.param5,
                                  command.params.param6,
                                  command.params.param7);

    new_work.callback = callback;
    new_work.mavlink_command = command.command;
    _work_queue.push_back(new_work);
}

void MAVLinkCommands::receive_command_ack(mavlink_message_t message)
{
    mavlink_command_ack_t command_ack;
    mavlink_msg_command_ack_decode(&message, &command_ack);

    // LogDebug() << "We got an ack: " << command_ack.command;

    auto work = _work_queue.borrow_front();
    if (!work) {
        return;
    }

    if (work->mavlink_command != command_ack.command) {
        // If the command does not match with our current command, ignore it.
        LogWarn() << "Command ack " << int(command_ack.command)
                  << " not matching our current command: " << work->mavlink_command;
        _work_queue.return_front();
        return;
    }

    switch (command_ack.result) {
        case MAV_RESULT_ACCEPTED:
            _parent.unregister_timeout_handler(_timeout_cookie);
            _work_queue.pop_front();
            call_callback(work->callback, Result::SUCCESS, 1.0f);
            break;

        case MAV_RESULT_DENIED:
            LogWarn() << "command denied (" << work->mavlink_command << ").";
            _parent.unregister_timeout_handler(_timeout_cookie);
            _work_queue.pop_front();
            call_callback(work->callback, Result::COMMAND_DENIED, NAN);
            break;

        case MAV_RESULT_UNSUPPORTED:
            LogWarn() << "command unsupported (" << work->mavlink_command << ").";
            _parent.unregister_timeout_handler(_timeout_cookie);
            _work_queue.pop_front();
            call_callback(work->callback, Result::COMMAND_DENIED, NAN);
            break;

        case MAV_RESULT_TEMPORARILY_REJECTED:
            LogWarn() << "command temporarily rejected (" << work->mavlink_command << ").";
            _parent.unregister_timeout_handler(_timeout_cookie);
            _work_queue.pop_front();
            call_callback(work->callback, Result::COMMAND_DENIED, NAN);
            break;

        case MAV_RESULT_FAILED:
            _parent.unregister_timeout_handler(_timeout_cookie);
            _work_queue.pop_front();
            call_callback(work->callback, Result::COMMAND_DENIED, NAN);
            break;

        case MAV_RESULT_IN_PROGRESS:
            if (static_cast<int>(command_ack.progress) != 255) {
                LogInfo() << "progress: " << static_cast<int>(command_ack.progress) << " % ("
                          << work->mavlink_command << ").";
            }
            // If we get a progress update, we can raise the timeout
            // to something higher because we know the initial command
            // has arrived. A possible timeout for this case is the initial
            // timeout * the possible retries because this should match the
            // case where there is no progress update and we keep trying.
            _parent.unregister_timeout_handler(_timeout_cookie);
            _parent.register_timeout_handler(std::bind(&MAVLinkCommands::receive_timeout, this),
                                             work->retries_to_do * work->timeout_s,
                                             &_timeout_cookie);
            _work_queue.return_front();
            // FIXME: We can only call callbacks with promises once, so let's not do it
            //        on IN_PROGRESS.
            // call_callback(work->callback, Result::IN_PROGRESS, command_ack.progress /
            //               100.0f);
            break;

        default:
            LogWarn() << "Received unknown ack.";
            _work_queue.return_front();
            break;
    }
}

void MAVLinkCommands::receive_timeout()
{
    // If we're not waiting, we ignore this.
    auto work = _work_queue.borrow_front();

    if (!work) {
        LogErr() << "Received timeout without item in queue.";
        return;
    }

    if (work->retries_to_do > 0) {
        // We're not sure the command arrived, let's retransmit.
        LogWarn() << "sending again, retries to do: " << work->retries_to_do << "  ("
                  << work->mavlink_command << ").";
        if (!_parent.send_message(work->mavlink_message)) {
            LogErr() << "connection send error in retransmit (" << work->mavlink_command << ").";
            _work_queue.pop_front();
            call_callback(work->callback, Result::CONNECTION_ERROR, NAN);

        } else {
            --work->retries_to_do;
            _parent.register_timeout_handler(std::bind(&MAVLinkCommands::receive_timeout, this),
                                             work->timeout_s,
                                             &_timeout_cookie);
            _work_queue.return_front();
        }

    } else {
        // We have tried retransmitting, giving up now.
        LogErr() << "Retrying failed (" << work->mavlink_command << ")";

        _work_queue.pop_front();

        call_callback(work->callback, Result::TIMEOUT, NAN);
    }
}

void MAVLinkCommands::do_work()
{
    auto work = _work_queue.borrow_front();
    if (!work) {
        // Nothing to do.
        return;
    }

    if (!work->already_sent) {
        // LogDebug() << "sending it the first time (" << work->mavlink_command << ")";
        if (!_parent.send_message(work->mavlink_message)) {
            LogErr() << "connection send error (" << work->mavlink_command << ")";
            _work_queue.pop_front();
            call_callback(work->callback, Result::CONNECTION_ERROR, NAN);
        } else {
            work->already_sent = true;
            _parent.register_timeout_handler(std::bind(&MAVLinkCommands::receive_timeout, this),
                                             work->timeout_s,
                                             &_timeout_cookie);
            _work_queue.return_front();
        }
    } else {
        _work_queue.return_front();
    }
}

void MAVLinkCommands::call_callback(const command_result_callback_t &callback,
                                    Result result,
                                    float progress)
{
    if (!callback) {
        return;
    }

    // It seems that we need to queue the callback on the thread pool otherwise
    // we lock ourselves out when we send a command in the callback receiving a command result.
    _parent.call_user_callback([callback, result, progress]() { callback(result, progress); });
}

} // namespace dronecode_sdk
<commit_msg>mavlink_commands: switch to LockedQueue::Guard<commit_after>#include "mavlink_commands.h"
#include "system_impl.h"
#include <future>
#include <memory>

namespace dronecode_sdk {

// TODO: Currently the mavlink command handling is made in a way to only
//       process one command at any time. Therefore, the work state is global
//       for this whole class.
//       The limitation is made because:
//       - We are not sure what exactly will happen if the commands are sent in parallel
//         and what kind of edge cases we might run into.
//       - The queue used does not support going through and checking each and every
//         item yet.

MAVLinkCommands::MAVLinkCommands(SystemImpl &parent) : _parent(parent)
{
    _parent.register_mavlink_message_handler(
        MAVLINK_MSG_ID_COMMAND_ACK,
        std::bind(&MAVLinkCommands::receive_command_ack, this, std::placeholders::_1),
        this);
}

MAVLinkCommands::~MAVLinkCommands()
{
    _parent.unregister_all_mavlink_message_handlers(this);
}

MAVLinkCommands::Result MAVLinkCommands::send_command(const MAVLinkCommands::CommandInt &command)
{
    // We wrap the async call with a promise and future.
    auto prom = std::make_shared<std::promise<Result>>();
    auto res = prom->get_future();

    queue_command_async(command, [&prom](Result result, float progress) {
        UNUSED(progress);
        // We can only fulfill the promise once in C++11.
        // Therefore we have to ignore the IN_PROGRESS state and wait
        // for the final result.
        if (result != Result::IN_PROGRESS) {
            prom->set_value(result);
        }
    });

    // Block now to wait for result.
    return res.get();
}

MAVLinkCommands::Result MAVLinkCommands::send_command(const MAVLinkCommands::CommandLong &command)
{
    // We wrap the async call with a promise and future.
    auto prom = std::make_shared<std::promise<Result>>();
    auto res = prom->get_future();

    queue_command_async(command, [&prom](Result result, float progress) {
        UNUSED(progress);
        // We can only fulfill the promise once in C++11.
        // Therefore we have to ignore the IN_PROGRESS state and wait
        // for the final result.
        if (result != Result::IN_PROGRESS) {
            prom->set_value(result);
        }
    });

    return res.get();
}

void MAVLinkCommands::queue_command_async(const CommandInt &command,
                                          command_result_callback_t callback)
{
    // LogDebug() << "Command " << (int)(command.command) << " to send to "
    //  << (int)(command.target_system_id)<< ", " << (int)(command.target_component_id;

    Work new_work{};
    mavlink_msg_command_int_pack(GCSClient::system_id,
                                 GCSClient::component_id,
                                 &new_work.mavlink_message,
                                 command.target_system_id,
                                 command.target_component_id,
                                 command.frame,
                                 command.command,
                                 command.current,
                                 command.autocontinue,
                                 command.params.param1,
                                 command.params.param2,
                                 command.params.param3,
                                 command.params.param4,
                                 command.params.x,
                                 command.params.y,
                                 command.params.z);

    new_work.callback = callback;
    new_work.mavlink_command = command.command;
    _work_queue.push_back(new_work);
}

void MAVLinkCommands::queue_command_async(const CommandLong &command,
                                          command_result_callback_t callback)
{
    // LogDebug() << "Command " << (int)(command.command) << " to send to "
    //  << (int)(command.target_system_id)<< ", " << (int)(command.target_component_id;

    Work new_work{};
    mavlink_msg_command_long_pack(GCSClient::system_id,
                                  GCSClient::component_id,
                                  &new_work.mavlink_message,
                                  command.target_system_id,
                                  command.target_component_id,
                                  command.command,
                                  command.confirmation,
                                  command.params.param1,
                                  command.params.param2,
                                  command.params.param3,
                                  command.params.param4,
                                  command.params.param5,
                                  command.params.param6,
                                  command.params.param7);

    new_work.callback = callback;
    new_work.mavlink_command = command.command;
    _work_queue.push_back(new_work);
}

void MAVLinkCommands::receive_command_ack(mavlink_message_t message)
{
    mavlink_command_ack_t command_ack;
    mavlink_msg_command_ack_decode(&message, &command_ack);

    // LogDebug() << "We got an ack: " << command_ack.command;

    auto work_queue_guard = _work_queue.guard();
    auto work = work_queue_guard.get_front();

    if (!work) {
        return;
    }

    if (work->mavlink_command != command_ack.command) {
        // If the command does not match with our current command, ignore it.
        LogWarn() << "Command ack " << int(command_ack.command)
                  << " not matching our current command: " << work->mavlink_command;
        return;
    }

    switch (command_ack.result) {
        case MAV_RESULT_ACCEPTED:
            _parent.unregister_timeout_handler(_timeout_cookie);
            work_queue_guard.pop_front();
            call_callback(work->callback, Result::SUCCESS, 1.0f);
            break;

        case MAV_RESULT_DENIED:
            LogWarn() << "command denied (" << work->mavlink_command << ").";
            _parent.unregister_timeout_handler(_timeout_cookie);
            work_queue_guard.pop_front();
            call_callback(work->callback, Result::COMMAND_DENIED, NAN);
            break;

        case MAV_RESULT_UNSUPPORTED:
            LogWarn() << "command unsupported (" << work->mavlink_command << ").";
            _parent.unregister_timeout_handler(_timeout_cookie);
            work_queue_guard.pop_front();
            call_callback(work->callback, Result::COMMAND_DENIED, NAN);
            break;

        case MAV_RESULT_TEMPORARILY_REJECTED:
            LogWarn() << "command temporarily rejected (" << work->mavlink_command << ").";
            _parent.unregister_timeout_handler(_timeout_cookie);
            work_queue_guard.pop_front();
            call_callback(work->callback, Result::COMMAND_DENIED, NAN);
            break;

        case MAV_RESULT_FAILED:
            _parent.unregister_timeout_handler(_timeout_cookie);
            work_queue_guard.pop_front();
            call_callback(work->callback, Result::COMMAND_DENIED, NAN);
            break;

        case MAV_RESULT_IN_PROGRESS:
            if (static_cast<int>(command_ack.progress) != 255) {
                LogInfo() << "progress: " << static_cast<int>(command_ack.progress) << " % ("
                          << work->mavlink_command << ").";
            }
            // If we get a progress update, we can raise the timeout
            // to something higher because we know the initial command
            // has arrived. A possible timeout for this case is the initial
            // timeout * the possible retries because this should match the
            // case where there is no progress update and we keep trying.
            _parent.unregister_timeout_handler(_timeout_cookie);
            _parent.register_timeout_handler(std::bind(&MAVLinkCommands::receive_timeout, this),
                                             work->retries_to_do * work->timeout_s,
                                             &_timeout_cookie);
            // FIXME: We can only call callbacks with promises once, so let's not do it
            //        on IN_PROGRESS.
            // call_callback(work->callback, Result::IN_PROGRESS, command_ack.progress /
            //               100.0f);
            break;

        default:
            LogWarn() << "Received unknown ack.";
            break;
    }
}

void MAVLinkCommands::receive_timeout()
{
    // If we're not waiting, we ignore this.
    auto work_queue_guard = _work_queue.guard();
    auto work = work_queue_guard.get_front();

    if (!work) {
        LogErr() << "Received timeout without item in queue.";
        return;
    }

    if (work->retries_to_do > 0) {
        // We're not sure the command arrived, let's retransmit.
        LogWarn() << "sending again, retries to do: " << work->retries_to_do << "  ("
                  << work->mavlink_command << ").";
        if (!_parent.send_message(work->mavlink_message)) {
            LogErr() << "connection send error in retransmit (" << work->mavlink_command << ").";
            work_queue_guard.pop_front();
            call_callback(work->callback, Result::CONNECTION_ERROR, NAN);

        } else {
            --work->retries_to_do;
            _parent.register_timeout_handler(std::bind(&MAVLinkCommands::receive_timeout, this),
                                             work->timeout_s,
                                             &_timeout_cookie);
        }

    } else {
        // We have tried retransmitting, giving up now.
        LogErr() << "Retrying failed (" << work->mavlink_command << ")";

        work_queue_guard.pop_front();

        call_callback(work->callback, Result::TIMEOUT, NAN);
    }
}

void MAVLinkCommands::do_work()
{
    auto work_queue_guard = _work_queue.guard();
    auto work = work_queue_guard.get_front();

    if (!work) {
        // Nothing to do.
        return;
    }

    if (!work->already_sent) {
        // LogDebug() << "sending it the first time (" << work->mavlink_command << ")";
        if (!_parent.send_message(work->mavlink_message)) {
            LogErr() << "connection send error (" << work->mavlink_command << ")";
            work_queue_guard.pop_front();
            call_callback(work->callback, Result::CONNECTION_ERROR, NAN);
        } else {
            work->already_sent = true;
            _parent.register_timeout_handler(std::bind(&MAVLinkCommands::receive_timeout, this),
                                             work->timeout_s,
                                             &_timeout_cookie);
        }
    }
}

void MAVLinkCommands::call_callback(const command_result_callback_t &callback,
                                    Result result,
                                    float progress)
{
    if (!callback) {
        return;
    }

    // It seems that we need to queue the callback on the thread pool otherwise
    // we lock ourselves out when we send a command in the callback receiving a command result.
    _parent.call_user_callback([callback, result, progress]() { callback(result, progress); });
}

} // namespace dronecode_sdk
<|endoftext|>


<commit_before>/**
 * @file nca_main.cpp
 * @author Ryan Curtin
 *
 * Executable for Neighborhood Components Analysis.
 */
#include <mlpack/core.hpp>
#include <mlpack/core/metrics/lmetric.hpp>

#include "nca.hpp"

// Define parameters.
PROGRAM_INFO("Neighborhood Components Analysis (NCA)",
    "This program implements Neighborhood Components Analysis, both a linear "
    "dimensionality reduction technique and a distance learning technique.  The"
    " method seeks to improve k-nearest-neighbor classification on a dataset "
    "by scaling the dimensions.  The method is nonparametric, and does not "
    "require a value of k.  It works by using stochastic (\"soft\") neighbor "
    "assignments and using optimization techniques over the gradient of the "
    "accuracy of the neighbor assignments.\n"
    "\n"
    "To work, this algorithm needs labeled data.  It can be given as the last "
    "row of the input dataset (--input_file), or alternatively in a separate "
    "file (--labels_file).");

PARAM_STRING_REQ("input_file", "Input dataset to run NCA on.", "i");
PARAM_STRING_REQ("output_file", "Output file for learned distance matrix.",
    "o");
PARAM_STRING("labels_file", "File of labels for input dataset.", "l", "");
PARAM_DOUBLE("step_size", "Step size for stochastic gradient descent.", "s",
    0.01);
PARAM_INT("max_iterations", "Maximum number of iterations for stochastic "
    "gradient descent (0 indicates no limit).", "n", 500000);
PARAM_DOUBLE("tolerance", "Maximum tolerance for termination of stochastic "
    "gradient descent.", "t", 1e-7);
PARAM_FLAG("normalize", "Normalize data; useful for datasets where points are "
    "far apart, or when SGD is converging to an objective of NaN.", "N");

using namespace mlpack;
using namespace mlpack::nca;
using namespace mlpack::metric;
using namespace std;
using namespace arma;

int main(int argc, char* argv[])
{
  // Parse command line.
  CLI::ParseCommandLine(argc, argv);

  const string inputFile = CLI::GetParam<string>("input_file");
  const string labelsFile = CLI::GetParam<string>("labels_file");
  const string outputFile = CLI::GetParam<string>("output_file");

  const double stepSize = CLI::GetParam<double>("step_size");
  const size_t maxIterations = CLI::GetParam<int>("max_iterations");
  const double tolerance = CLI::GetParam<double>("tolerance");
  const bool normalize = CLI::HasParam("normalize");

  // Load data.
  mat data;
  data::Load(inputFile.c_str(), data, true);

  // Do we want to load labels separately?
  umat labels(data.n_cols, 1);
  if (labelsFile != "")
  {
    data::Load(labelsFile.c_str(), labels, true);

    if (labels.n_rows == 1)
      labels = trans(labels);

    if (labels.n_cols > 1)
      Log::Fatal << "Labels must have only one column or row!" << endl;
  }
  else
  {
    for (size_t i = 0; i < data.n_cols; i++)
      labels[i] = (int) data(data.n_rows - 1, i);

    data.shed_row(data.n_rows - 1);
  }

  // Normalize the data, if necessary.
  if (normalize)
  {
    // Find the minimum and maximum values for each dimension.
    arma::vec range = arma::max(data, 1) - arma::min(data, 1);

    // Now find the maximum range.
    double maxRange = arma::max(range);

    // We can place a (lazy) upper bound on the distance with range^2 * d.
    // Since we want no distance greater than 700 (because std::exp(-750)
    // underflows), we can normalize with (range^2 * d) / 700).
    double normalization = (std::pow(maxRange, 2.0) * data.n_rows) / 700.0;
    data /= normalization; // Element-wise division.

    Log::Info << "Data normalized (normalization constant " << normalization
        << ")." << std::endl;
  }

  // Now create the NCA object and run the optimization.
  NCA<LMetric<2> > nca(data, labels.unsafe_col(0), stepSize, maxIterations,
      tolerance);

  mat distance;
  nca.LearnDistance(distance);

  // Save the output.
  data::Save(CLI::GetParam<string>("output_file").c_str(), distance, true);
}
<commit_msg>Also support a random seed.<commit_after>/**
 * @file nca_main.cpp
 * @author Ryan Curtin
 *
 * Executable for Neighborhood Components Analysis.
 */
#include <mlpack/core.hpp>
#include <mlpack/core/metrics/lmetric.hpp>

#include "nca.hpp"

// Define parameters.
PROGRAM_INFO("Neighborhood Components Analysis (NCA)",
    "This program implements Neighborhood Components Analysis, both a linear "
    "dimensionality reduction technique and a distance learning technique.  The"
    " method seeks to improve k-nearest-neighbor classification on a dataset "
    "by scaling the dimensions.  The method is nonparametric, and does not "
    "require a value of k.  It works by using stochastic (\"soft\") neighbor "
    "assignments and using optimization techniques over the gradient of the "
    "accuracy of the neighbor assignments.\n"
    "\n"
    "To work, this algorithm needs labeled data.  It can be given as the last "
    "row of the input dataset (--input_file), or alternatively in a separate "
    "file (--labels_file).");

PARAM_STRING_REQ("input_file", "Input dataset to run NCA on.", "i");
PARAM_STRING_REQ("output_file", "Output file for learned distance matrix.",
    "o");
PARAM_STRING("labels_file", "File of labels for input dataset.", "l", "");
PARAM_DOUBLE("step_size", "Step size for stochastic gradient descent (alpha).",
    "a", 0.01);
PARAM_INT("max_iterations", "Maximum number of iterations for stochastic "
    "gradient descent (0 indicates no limit).", "n", 500000);
PARAM_DOUBLE("tolerance", "Maximum tolerance for termination of stochastic "
    "gradient descent.", "t", 1e-7);
PARAM_FLAG("normalize", "Normalize data; useful for datasets where points are "
    "far apart, or when SGD is converging to an objective of NaN.", "N");
PARAM_INT("seed", "Random seed.  If 0, 'std::time(NULL)' is used.", "s", 0);

using namespace mlpack;
using namespace mlpack::nca;
using namespace mlpack::metric;
using namespace std;
using namespace arma;

int main(int argc, char* argv[])
{
  // Parse command line.
  CLI::ParseCommandLine(argc, argv);

  if (CLI::GetParam<int>("seed") != 0)
    math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
  else
    math::RandomSeed((size_t) std::time(NULL));

  const string inputFile = CLI::GetParam<string>("input_file");
  const string labelsFile = CLI::GetParam<string>("labels_file");
  const string outputFile = CLI::GetParam<string>("output_file");

  const double stepSize = CLI::GetParam<double>("step_size");
  const size_t maxIterations = CLI::GetParam<int>("max_iterations");
  const double tolerance = CLI::GetParam<double>("tolerance");
  const bool normalize = CLI::HasParam("normalize");

  // Load data.
  mat data;
  data::Load(inputFile.c_str(), data, true);

  // Do we want to load labels separately?
  umat labels(data.n_cols, 1);
  if (labelsFile != "")
  {
    data::Load(labelsFile.c_str(), labels, true);

    if (labels.n_rows == 1)
      labels = trans(labels);

    if (labels.n_cols > 1)
      Log::Fatal << "Labels must have only one column or row!" << endl;
  }
  else
  {
    for (size_t i = 0; i < data.n_cols; i++)
      labels[i] = (int) data(data.n_rows - 1, i);

    data.shed_row(data.n_rows - 1);
  }

  // Normalize the data, if necessary.
  if (normalize)
  {
    // Find the minimum and maximum values for each dimension.
    arma::vec range = arma::max(data, 1) - arma::min(data, 1);

    // Now find the maximum range.
    double maxRange = arma::max(range);

    // We can place a (lazy) upper bound on the distance with range^2 * d.
    // Since we want no distance greater than 700 (because std::exp(-750)
    // underflows), we can normalize with (range^2 * d) / 700).
    double normalization = (std::pow(maxRange, 2.0) * data.n_rows) / 700.0;
    data /= normalization; // Element-wise division.

    Log::Info << "Data normalized (normalization constant " << normalization
        << ")." << std::endl;
  }

  // Now create the NCA object and run the optimization.
  NCA<LMetric<2> > nca(data, labels.unsafe_col(0), stepSize, maxIterations,
      tolerance);

  mat distance;
  nca.LearnDistance(distance);

  // Save the output.
  data::Save(CLI::GetParam<string>("output_file").c_str(), distance, true);
}
<|endoftext|>