text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_SDK_COMPLEX_IMAGINARY_HPP_INCLUDED
#define NT2_SDK_COMPLEX_IMAGINARY_HPP_INCLUDED
#include <nt2/include/constants/zero.hpp>
#include <nt2/sdk/complex/details/imaginary/meta.hpp>
#include <nt2/sdk/complex/complex.hpp>
#include <nt2/sdk/complex/meta/as_complex.hpp>
#include <boost/simd/sdk/details/aliasing.hpp>

namespace nt2
{
  template<class T>
  struct BOOST_SIMD_MAY_ALIAS imaginary
  {
    typedef typename meta::as_complex<T>::type c_type;
    typedef T type;
    T value;

    imaginary() {}
    explicit imaginary(T const& value_) : value(value_){ }
    //    operator c_type () const {return c_type(Zero<type>(), value); }
    bool operator == (const imaginary<T>&a) const{return value == a.value; }
    bool operator != (const imaginary<T>&a) const{return value != a.value; }

    T&       operator()()       { return value; }
    T const& operator()() const { return value; }
  };
  ////////////////////////////////////////////////////////////////////////////
  // Stream insertion for imaginary<T>
  ////////////////////////////////////////////////////////////////////////////
  template<class T>
  BOOST_DISPATCH_FORCE_INLINE
  std::ostream& operator<<(std::ostream& os, imaginary<T> const& v )
  {
     return os << "( _ , " << v() << ")";
  }
}

namespace boost { namespace simd
{
  template<class T, class Ext>
  BOOST_DISPATCH_FORCE_INLINE
  std::ostream& operator<<(std::ostream& os, boost::simd::native<nt2::imaginary<T>,Ext> const& v )
  {
    typedef boost::simd::native<std::complex<T>, Ext> cvtype;
    const std::size_t size = meta::cardinal_of<boost::simd::native<T, Ext> >::value;
    os << "{";
    for(std::size_t i = 0;  i < size; ++i)
      {
        os << v[i] << ((i+1 == size) ? "}" :", ");
      }
    return os;
  }
} }

#endif

ext: hpp


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "isd2csv.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
// To disable autolinking of Boost.Date_Time and Boost.Regex for MSVC
#define BOOST_DATE_TIME_NO_LIB
#define BOOST_REGEX_NO_LIB
// We do not need Boost.Asio's threading support for isd2csv
#define BOOST_ASIO_DISABLE_THREADS
#include <boost/asio.hpp>
#include <boost/uuid/string_generator.hpp>

#include "isdf/reader.h"

namespace flint {
namespace isd2csv {

namespace {

const size_t kPrefixLength = 36u;

bool ValidatePrefix(const std::string &name)
{
	boost::uuids::string_generator gen;
	try {
		gen(name.substr(0, kPrefixLength));
	} catch (const boost::exception &e) {
		return false;
	}
	return true;
}

class Converter {
public:
	Converter(const Option &option,
			  std::ostream *os, std::uint32_t num_objs, size_t length = 0,
			  boost::asio::ip::udp::endpoint *endpoint = nullptr,
			  boost::asio::ip::udp::socket *socket = nullptr)
		: option_(option)
		, length_(length)
		, position_()
		, endpoint_(endpoint)
		, socket_(socket)
		, progress_(-1)
		, os_(os)
		, num_objs_(num_objs)
		, descriptions_(num_objs)
		, units_(num_objs)
	{}

	~Converter()
	{
		if (socket_ && socket_->is_open()) {
			boost::system::error_code ec;
			socket_->shutdown(boost::asio::ip::udp::socket::shutdown_send, ec);
			socket_->close(ec);
		}
	}

	void GetDescription(std::uint32_t i, size_t bytes, const char *desc) {
		descriptions_[i] = std::string(desc, bytes);
	}

	void GetUnit(std::uint32_t i, size_t bytes, const char *unit) {
		units_[i] = std::string(unit, bytes);
	}

	void WriteFirstLine() const {
		size_t p;
		for (std::uint32_t i=0;i<num_objs_;i++) {
			if (i > 0) *os_ << ',';
			const std::string &name = descriptions_[i];
			const size_t s = name.size();
			if ( option_.ignore_prefixes &&
				 ( (p = name.find(':')) != std::string::npos) &&
				 p + 1 < s &&
				 p == kPrefixLength &&
				 ValidatePrefix(name) ) {
				os_->write(name.substr(p+1).c_str(), s-p-1);
			} else {
				os_->write(name.c_str(), s);
			}
			if (!option_.ignore_units && !units_[i].empty()) {
				*os_ << " (";
				os_->write(units_[i].c_str(), units_[i].size());
				*os_ << ")";
			}
		}
		*os_ << "\r\n";
	}

	int GetStep(size_t buf_size, char *buf) {
		char *eob = buf + buf_size;
		char *b = buf;
		while (b < eob) {
			double d;
			std::memcpy(&d, b, sizeof(double));
			if (b != buf) *os_ << ',';
			*os_ << d;
			b += sizeof(double);
		}
		*os_ << "\r\n";
		if (endpoint_ && socket_ && socket_->is_open()) {
			position_ += buf_size;
			char p = static_cast<char>((position_ * 100) / length_);
			if (progress_ < p && 0 <= p && p <= 100) {
				progress_ = p;
				try {
					socket_->send_to(boost::asio::buffer(&progress_, 1), *endpoint_);
				} catch (boost::system::system_error &) {
					boost::system::error_code ec;
					socket_->shutdown(boost::asio::ip::udp::socket::shutdown_send, ec);
					socket_->close(ec);
				}
			}
		}
		return (b == eob) ? 1 : -1;
	}

private:
	const Option &option_;
	size_t length_, position_;
	boost::asio::ip::udp::endpoint *endpoint_;
	boost::asio::ip::udp::socket *socket_;
	char progress_;
	std::ostream *os_;
	std::uint32_t num_objs_;
	std::vector<std::string> descriptions_;
	std::vector<std::string> units_;
};

int Read(isdf::Reader &reader, Converter &converter, std::istream *is)
{
	if (!reader.SkipComment(is)) return EXIT_FAILURE;
	if (!reader.ReadDescriptions(converter, is)) return EXIT_FAILURE;
	if (!reader.ReadUnits(converter, is)) return EXIT_FAILURE;
	converter.WriteFirstLine();
	if (!reader.ReadSteps(converter, is)) return EXIT_FAILURE;
	return EXIT_SUCCESS;
}

}

int Convert(const Option &option, std::istream *is, std::ostream *os)
{
	isdf::Reader reader;
	if (!reader.ReadHeader(is)) return EXIT_FAILURE;
	if (!option.port.empty()) {
		size_t p = is->tellg();
		is->seekg(0, std::ios::end);
		size_t q = is->tellg();
		if (q <= p) return EXIT_FAILURE;
		is->seekg(p, std::ios::beg);
		size_t length = q - p;

		boost::asio::io_service service;
		boost::asio::ip::udp::resolver resolver(service);
		boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), "127.0.0.1", option.port);
		boost::system::error_code ec;
		auto it = resolver.resolve(query, ec);
		if (!ec) {
			boost::asio::ip::udp::endpoint endpoint(*it);
			boost::asio::ip::udp::socket socket(service);
			socket.open(boost::asio::ip::udp::v4(), ec);
			if (!ec) {
				Converter converter(option, os, reader.num_objs(), length, &endpoint, &socket);
				return Read(reader, converter, is);
			}
		}
	}
	Converter converter(option, os, reader.num_objs());
	return Read(reader, converter, is);
}

}
}

ext: cc

max_stars_repo_name: Abhisheknishant/Flint

max_issues_repo_name: Abhisheknishant/Flint

max_forks_repo_name: Abhisheknishant/Flint


text:
// Copyright (c) 2017-2021 The Merit Foundation
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pog2/cgs.h"
#include "addressindex.h"
#include "validation.h"
#include "referrals.h"
#include "ctpl/ctpl.h"
#include "sync.h"

#include <stack>
#include <deque>
#include <stack>
#include <numeric>

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/thread/thread.hpp>

namespace pog2
{
    namespace
    {
        const size_t BATCH_SIZE = 100;
        const int NO_GENESIS = 13500;
    }

    CAmount GetAmbassadorMinumumStake(int height, const Consensus::Params& consensus_params)
    {
        const int halvings = height / consensus_params.nSubsidyHalvingInterval;
        return halvings < 64 ?
            consensus_params.pog2_initial_ambassador_stake >> halvings : 0;
    }

    using UnspentPair = std::pair<CAddressUnspentKey, CAddressUnspentValue>;

    using BigInt = boost::multiprecision::cpp_int;

    double Age(int height, int tip_height, double maturity)
    {
        assert(tip_height >= 0);
        assert(height <= tip_height);
        assert(maturity > 0);

        const double maturity_scale = maturity / 4.0; //matures to about 97% at 4
        const double age = (tip_height - height) / maturity_scale;

        assert(age >= 0);
        return age;
    }

    double AgeScale(int height, int tip_height, double maturity)
    {
        assert(tip_height >= 0);
        assert(height <= tip_height);
        assert(maturity > 0);

        const auto age = Age(height, tip_height, maturity);
        const auto age_scale =  1.0 - (1.0 / (std::pow(age, 2) + 1.0));

        assert(age_scale >= 0);
        assert(age_scale <= 1.001);
        return age_scale;
    }

    double AgeScale(const Coin& c, int tip_height, int maturity) {
        assert(tip_height >= 0);
        assert(c.height <= tip_height);
        assert(maturity > 0);
        return AgeScale(c.height, tip_height, maturity);
    }

    int GetReferralHeight(
            referral::ReferralsViewCache& db,
            const referral::Address& a
            )
    {
        auto height = db.GetReferralHeight(a);
        if (height < 0) {
            const auto beacon = db.GetReferral(a);
            assert(beacon);

            uint256 hashBlock;
            CBlockIndex* pindex = nullptr;

            referral::ReferralRef beacon_out;
            if (GetReferral(beacon->GetHash(), beacon_out, hashBlock, pindex)) {
                assert(pindex);
                height = pindex->nHeight;
                if (height > 0) {
                    db.SetReferralHeight(height, a);
                }
            }
        }
        return height;
    }

    Coins GetCoins(
            int height,
            char address_type,
            const referral::Address& address) {
        Coins cs;
        std::vector<UnspentPair> unspent;
        if (!GetAddressUnspent(address, address_type, false, unspent)) {
            return cs;
        }

        cs.reserve(unspent.size());
        for (const auto& p : unspent) {
            if (p.first.type == 0 || p.first.isInvite) {
                continue;
            }
            assert(p.second.satoshis >= 0);

            cs.push_back({std::min(p.second.blockHeight, height), p.second.satoshis});
        }

        return cs;
    }

    bool GetAllCoins(CGSContext& context, int tip_height) {
        std::vector<UnspentPair> unspent;
        if (!GetAllUnspent(false, [&context, tip_height](const CAddressUnspentKey& key, const CAddressUnspentValue& value) {
                if (key.type == 0 || key.isInvite || value.satoshis == 0 || value.blockHeight > tip_height) {
                    return;
                }

                assert(!key.isInvite);
                assert(value.satoshis > 0);

                auto& entrant = context.GetEntrant(key.hashBytes);
                entrant.coins.emplace_back(value.blockHeight, value.satoshis);
           })) {
            return false;
        }
        return true;
    }

    BalancePair BalanceDecay(int tip_height, const Coin& c, int maturity) {
        assert(tip_height >= 0);
        assert(c.height <= tip_height);
        assert(c.amount >= 0);
        assert(maturity > 0);

        const auto age_scale = AgeScale(c, tip_height, maturity);
        const auto aged_balance = age_scale * c.amount;

        assert(aged_balance <= std::numeric_limits<CAmount>::max());

        CAmount amount = aged_balance;

        assert(amount >= 0);
        assert(amount <= c.amount);
        return BalancePair{amount, c.amount};
    }

    template <class AgeFunc>
    BalancePair AgedBalance(int tip_height, const Coins& cs, int maturity, AgeFunc AgedBalanceFunc) {
        assert(tip_height >= 0);

        BalancePairs balances(cs.size());
        std::transform(cs.begin(), cs.end(), balances.begin(),
                [tip_height, maturity, &AgedBalanceFunc](const Coin& c) {
                    return AgedBalanceFunc(tip_height, c, maturity);
                });

        const auto aged_balance =
            std::accumulate(balances.begin(), balances.end(), CAmount{0},
                [](CAmount amount, const BalancePair& b) {
                    return amount + b.first;
               });

        const auto balance =
            std::accumulate(balances.begin(), balances.end(), CAmount{0},
                [](CAmount amount, const BalancePair& b) {
                    return amount + b.second;
                });

        assert(aged_balance <= balance);
        return BalancePair{aged_balance, balance};
    }

    //Convex function with property that if C0 > C1 and you have A within [0, 1] then
    //ConvexF(C0 + A) - ConvexF(C0) > ConvexF(C1 + A) - ConvexF(C1);
    //See: Lottery Trees: Motivational Deployment of Networked Systems
    //These properties are important to allow for some kind of growth incentive
    //without compromising the system's integrity against sybil attacks.
    template <class V>
    V ConvexF(V c, V B, V S) {
        assert(c >= V{0});
        assert(c <= V{1.01});
        assert(B >= V{0});
        assert(B <= V{1.01});
        assert(S >= V{0});
        assert(S <= V{1.01});

        const V v = (B*c) + ((V{1} - B)*boost::multiprecision::pow(c, V{1} + S));
        assert(v >= 0);
        return v;
    }

    Contribution ContributionNode(
            CGSContext& context,
            CachedEntrant& entrant,
            referral::ReferralsViewCache& db)
    {
        assert(context.tip_height > 0);
        assert(context.new_coin_maturity > 0);

        const auto aged_balance = entrant.balances;

        const auto beacon_height =
            std::min(entrant.height, context.tip_height);

        if (beacon_height < 0 ) {
            return Contribution{};
        }

        assert(beacon_height <= context.tip_height);

        const auto beacon_age_scale =
            1.0 - AgeScale(beacon_height, context.tip_height, context.new_coin_maturity);

        assert(beacon_age_scale >= 0);
        assert(beacon_age_scale <= 1.01);

        Contribution c;

        //We compute both the linear and sublinear versions of the contribution.
        //This is done because there are two pools of selections evenly split
        //between stake oriented and growth oriented engagements.
        c.value = (beacon_age_scale * aged_balance.second) + aged_balance.first;
        c.sub = boost::multiprecision::log(ContributionAmount{1.0} + c.value);

        assert(c.value >= 0);
        assert(c.value <= aged_balance.second);
        assert(c.sub >= 0);

        return c;
    }

    struct Node
    {
        char address_type;
        referral::Address address;
        Children children;
        SubtreeContribution contribution;
    };

    using NodeStack = std::stack<Node>;

    using AddressQueue = std::deque<AddressPair>;

    /**
     * Computes the subtree contribution rooted at the address specified.
     * This algorithm computes the subtree contribution by doing a post order
     * traversal of the ambassador tree.
     *
     * TODO: Implement parallel version, maybe Coffman–Graham algorithm.
     */
    SubtreeContribution ContributionSubtreeIter(
            CGSContext& context,
            char address_type,
            const referral::Address& address,
            referral::ReferralsViewCache& db)
    {
        const auto c = context.subtree_contribution.find(address);

        if (c != context.subtree_contribution.end()) {
            return c->second;
        }

        const auto& root_entrant = context.GetEntrant(address);

        SubtreeContribution contribution;

        NodeStack ns;
        ns.push({
                root_entrant.address_type,
                address,
                root_entrant.children,
                {}});

        while (!ns.empty()) {
            auto& n = ns.top();
            n.contribution.value += contribution.value;
            n.contribution.sub += contribution.sub;
            n.contribution.tree_size += contribution.tree_size;

            if (n.children.empty()) {
                const auto& c = context.GetEntrant(n.address).contribution;
                n.contribution.value += c.value;
                n.contribution.sub += c.sub;
                n.contribution.tree_size++;

                assert(n.contribution.value >= 0);
                assert(n.contribution.sub >= 0);

                contribution = n.contribution;
                context.subtree_contribution[n.address] = n.contribution;

                ns.pop();

            } else {
                const auto child_address = n.children.back();
                n.children.pop_back();

                contribution.value = 0;
                contribution.sub = 0;
                contribution.tree_size = 0;

                const auto& child_entrant = context.GetEntrant(child_address);

                ns.push({
                        child_entrant.address_type,
                        child_address,
                        child_entrant.children,
                        {}});
            }
        }

        return context.subtree_contribution[address];
    }

    ContributionAmount GetValue(const SubtreeContribution& t)
    {
        return t.value;
    }

    ContributionAmount GetSubValue(const SubtreeContribution& t)
    {
        return t.sub;
    }

    struct WeightedScores
    {
        ContributionAmount value;
        ContributionAmount sub;
        size_t tree_size;
    };

    WeightedScores WeightedScore(
            CGSContext& context,
            const char address_type,
            const referral::Address& address,
            referral::ReferralsViewCache& db)
    {
        assert(context.tree_contribution.value > 0);
        assert(context.tree_contribution.sub > 0);

        const auto subtree_contribution =
                ContributionSubtreeIter(
                    context,
                    address_type,
                    address,
                    db);
        assert(subtree_contribution.value >= 0);
        assert(subtree_contribution.value <= context.tree_contribution.value);
        assert(subtree_contribution.sub <= context.tree_contribution.sub);

        WeightedScores score;
        score.value = ConvexF<ContributionAmount>(
                subtree_contribution.value / context.tree_contribution.value,
                context.B,
                context.S);

        score.sub = ConvexF<ContributionAmount>(
                subtree_contribution.sub / context.tree_contribution.sub,
                context.B,
                context.S);

        score.tree_size = subtree_contribution.tree_size;

        assert(score.value >= 0);
        assert(score.sub >= 0);
        assert(score.tree_size > 0);
        return score;
    }

    struct ExpectedValues
    {
        ContributionAmount value;
        ContributionAmount sub;
        size_t tree_size;
    };

    ExpectedValues ExpectedValue(
            CGSContext& context,
            const CachedEntrant& entrant,
            referral::ReferralsViewCache& db)
    {
        //this case can occur on regtest if there is not enough data.
        if (context.tree_contribution.value == 0) {
            return {0, 0, 0};
        }

        assert(context.tree_contribution.value > 0);
        assert(context.tree_contribution.sub > 0);

        auto expected_value = WeightedScore(
                context,
                entrant.address_type,
                entrant.address,
                db);

        assert(expected_value.value >= 0);
        assert(expected_value.sub >= 0);

        for (const auto& c:  entrant.children) {
            const auto& child_entrant = context.GetEntrant(c);
            auto child_score = WeightedScore(
                    context,
                    child_entrant.address_type,
                    c,
                    db);

            assert(child_score.value >= 0);
            assert(child_score.sub >= 0);
            expected_value.value -= child_score.value;
            expected_value.sub -= child_score.sub;
        }

        assert(expected_value.value >= 0);
        assert(expected_value.sub >= 0);
        return {
            expected_value.value,
                expected_value.sub,
                expected_value.tree_size
        };
    }

    Entrant ComputeCGS(
            CGSContext& context,
            const CachedEntrant& entrant,
            referral::ReferralsViewCache& db)
    {
        auto expected_value = ExpectedValue(
                context,
                entrant,
                db);

        const ContributionAmount cgs = context.tree_contribution.value * expected_value.value;
        const ContributionAmount sub_cgs = context.tree_contribution.sub * expected_value.sub;

        assert(cgs >= 0);
        assert(sub_cgs >= 0);

        auto floored_cgs = cgs.convert_to<CAmount>();
        auto floored_sub_cgs = sub_cgs.convert_to<CAmount>();

        const auto& balance = entrant.balances;

        return Entrant{
                entrant.address_type,
                entrant.address,
                balance.second,
                balance.first,
                floored_cgs,
                floored_sub_cgs,
                entrant.height,
                entrant.children.size(),
                expected_value.tree_size
        };
    }

    void ComputeAges(CGSContext& context) {
        assert(context.cgs_pool != nullptr);

        std::vector<std::future<void>> jobs;
        jobs.reserve(context.entrants.size() / BATCH_SIZE);
        for(size_t b = 0; b < context.entrants.size(); b+=BATCH_SIZE) {
            jobs.push_back(
                    context.cgs_pool->push([b, &context](int id) {
                        const auto end = std::min(context.entrants.size(), b + BATCH_SIZE);
                        for(size_t i = b; i < end; i++) {
                            auto& e = context.entrants[i];
                            e.balances = AgedBalance(
                                    context.tip_height,
                                    e.coins,
                                    context.coin_maturity,
                                    BalanceDecay);
                        }
                    }));
        }
        for(auto& j : jobs) {
            j.wait();
        }
    }

    void PrefillContributionsAndHeights(
            CGSContext& context,
            const char address_type,
            const referral::Address& address,
            referral::ReferralsViewCache& db) {

        AddressQueue q;
        q.push_back(std::make_pair(address_type, address));
        while(!q.empty()) {
            const auto p = q.front();
            q.pop_front();

            const auto height = GetReferralHeight(db, p.second);

            const auto& entrant = context.AddEntrant(
                    p.first,
                    p.second,
                    height,
                    db.GetChildren(p.second));

            for(const auto& c : entrant.children) {
                const auto maybe_ref = db.GetReferral(c);
                if (!maybe_ref) {
                    continue;
                }

                q.push_back(std::make_pair(maybe_ref->addressType, maybe_ref->GetAddress()));
            }

        }
    }

    void ComputeAllContributions(
            CGSContext& context,
            referral::ReferralsViewCache& db) {
        assert(context.cgs_pool != nullptr);

        std::vector<std::future<void>> jobs;
        jobs.reserve(context.entrants.size() / BATCH_SIZE);
        for(size_t b = 0; b < context.entrants.size(); b+=BATCH_SIZE) {
            jobs.push_back(
                    context.cgs_pool->push([b, &context, &db](int id) {
                        const auto end = std::min(context.entrants.size(), b + BATCH_SIZE);
                        for(size_t i = b; i < end; i++) {
                            auto& e = context.entrants[i];
                            e.contribution = ContributionNode(context, e, db);
                        }
                    }));
        }
        for(auto& j : jobs) {
            j.wait();
        }
    }

    void ComputeAllScores(
            CGSContext& context,
            referral::ReferralsViewCache& db,
            const Consensus::Params& params,
            Entrants& entrants)
    {
        assert(context.cgs_pool != nullptr);
        const auto minimum_stake = GetAmbassadorMinumumStake(context.tip_height, params);

        std::vector<std::future<Entrants>> jobs;
        jobs.reserve(context.entrants.size() / BATCH_SIZE);

        assert(!context.entrants.empty());
        assert(context.entrants[0].address == params.genesis_address);

        //Important, 1 here to skip the genesis address
        for(size_t b = 1; b < context.entrants.size(); b+=BATCH_SIZE) {
            jobs.push_back(
                    context.cgs_pool->push([b, minimum_stake , &context, &db](int id) {
                        const auto end = std::min(context.entrants.size(), b + BATCH_SIZE);
                        Entrants es;
                        es.reserve(end - b);
                        for(size_t i = b; i < end; i++) {
                            const auto& e = context.entrants[i];
                            if(e.balances.second >= minimum_stake) {
                                es.emplace_back(ComputeCGS(context, e, db));
                            }
                        }
                        return es;
                    }));
        }

        entrants.reserve(context.entrants.size()*BATCH_SIZE);

        for(auto& j : jobs) {
            auto es = j.get();
            entrants.insert(entrants.end(), es.begin(), es.end());
        }
    }

    void GetAllRewardableEntrants(
            CGSContext& context,
            referral::ReferralsViewCache& db,
            const Consensus::Params& params,
            int height,
            Entrants& entrants)
    {
        assert(height >= 0);

        context.tip_height = height;
        context.coin_maturity = params.pog2_coin_maturity;
        context.new_coin_maturity = params.pog2_new_coin_maturity;
        context.B = params.pog2_convex_b;
        context.S = params.pog2_convex_s;
        PrefillContributionsAndHeights(
                context,
                2,
                params.genesis_address,
                db);
        GetAllCoins(context, height);
        ComputeAges(context);

        ComputeAllContributions(context, db);
        context.tree_contribution = ContributionSubtreeIter(context, 2, params.genesis_address, db);

        ComputeAllScores(context, db, params, entrants);
    }

    CachedEntrant& CGSContext::AddEntrant(
            char address_type,
            const referral::Address& address,
            int height,
            const Children& children)
    {

        CachedEntrant e;
        e.address = address;
        e.address_type = address_type;
        e.height = height;
        e.children = children;

        entrants.emplace_back(e);
        auto ei = entrant_idx.insert(std::make_pair(address, entrants.size() - 1));
        assert(ei.second);
        return entrants.back();
    }

    CachedEntrant& CGSContext::GetEntrant(const referral::Address& a)
    {
        auto p = entrant_idx.find(a);
        assert(p != entrant_idx.end());
        return entrants[p->second];
    }

    const CachedEntrant& CGSContext::GetEntrant(const referral::Address& a) const
    {
        const auto p = entrant_idx.find(a);
        assert(p != entrant_idx.end());
        return entrants[p->second];
    }

} // namespace pog2

ext: cpp

max_stars_repo_name: meritlabs/merit

max_issues_repo_name: meritlabs/merit

max_forks_repo_name: meritlabs/merit


text:
#include <iostream>
#include <Eigen/Dense>
#include <vector>
#include "Solver.hpp"

#include <chrono>
#include <iostream>
using namespace std;
using namespace Eigen;

Solver::Solver(){
    prob_id = 1;
}

VectorXd Solver::iterative_refinement(const Ref<const MatrixXd> &A, const VectorXd &b, const double mu_ir = 1e-7, const double mu_rel = 1e-5, const double epsilon = 1e-10, const int max_iter = 10)
{   //solves the system Ax=b using iterative refinement
    VectorXd Ab(A.cols()), delta(A.cols()), x(A.cols()), x_best(A.cols());
    MatrixXd AA_tild(A.cols(), A.cols()), AA_tild_reg(A.cols(), A.cols());

    Ab = A.transpose() * b;
    AA_tild = A.transpose() * A;
    AA_tild_reg = AA_tild;
    double reg = mu_ir + mu_rel * Solver::power_iteration(AA_tild, epsilon, 100);
    AA_tild_reg += reg * MatrixXd::Identity(AA_tild.rows(), AA_tild.cols());
    LLT<MatrixXd> llt = AA_tild_reg.llt();

    int not_improved = 0;
    double res;
    double res_pred = std::numeric_limits<double>::max();
    x = VectorXd::Zero(A.cols());
    x_best = x;
    delta = Ab;

    for (int i = 0; i < max_iter; i++)
    {
        llt.solveInPlace(delta);
        x += delta;
        delta.noalias() = AA_tild * x - Ab;
        res = delta.norm();
        if (res_pred - res < epsilon)
        {
            not_improved++;
        }
        else
        {
            x_best = x;
            res_pred = res;
            not_improved = 0;
        }
        if (res < epsilon || not_improved == 2)
        {
            break;
        }
    }
    return x_best;
}

double Solver::power_iteration(const MatrixXd &A,const  double epsilon = 1e-10, const int max_iter = 100){//computes the biggest eigenvalue of A
    VectorXd v(A.cols()), Av(A.cols());
    v = VectorXd::Random(A.cols());
    v.normalize();
    for (int i =0; i< max_iter; i++){
        Av.noalias() = A*v;
        v = Av;
        v.normalize();
    };
    double l_max;
    Av.noalias() = A*v;
    l_max = v.dot(Av);
    return l_max;
}

VectorXd Solver::solveQP( MatrixXd P, const VectorXd &q, const VectorXd &warm_start, const double epsilon =1e-10, const double mu_prox = 1e-7, const int max_iter=1000,const bool adaptative_rho=true){
    //solving a QP using ADMM algorithm
    double L, rho, res_dual, res_prim, mu_thresh, tau_inc, tau_dec, alpha_relax;
    mu_thresh = 10.; alpha_relax = 1.5;
    MatrixXd Pinv(P.rows(), P.cols());
    VectorXd q_prox(q.size()),l(q.size()),Plqu(q.size());
    VectorXd u = VectorXd::Zero(q.size());
    VectorXd l_2 = VectorXd::Zero(q.size());
    VectorXd l_2_pred = l_2;
    l = warm_start;
    L = Solver::power_iteration(P,epsilon, 10);
    rho = std::sqrt(mu_prox*L)*std::pow(L/mu_prox,.4);
    tau_inc = std::pow(L/mu_prox,.15); tau_dec = tau_inc;
    q_prox = q;
    P += (rho + mu_prox) * MatrixXd::Identity(P.rows(), P.cols());
    LLT<MatrixXd> chol = P.llt();
    Pinv.setIdentity(); chol.solveInPlace(Pinv);
    int rho_up = 0, cpt = 0;
    for(int i = 0; i< max_iter; i++){
        l.noalias() = Pinv*(rho*l_2-u-q_prox);
        q_prox.noalias() = q - mu_prox*l;
        l_2.noalias() = (alpha_relax*l + (1-alpha_relax)*l_2+u/rho).cwiseMax(0);
        u.noalias() += rho*(alpha_relax*l + (1-alpha_relax)*l_2_pred-l_2);
        Plqu.noalias() = rho*(l_2-l_2_pred);
        res_dual = Plqu.lpNorm<Infinity>();
        res_prim = (l_2-(alpha_relax*l + (1-alpha_relax)*l_2_pred)).lpNorm<Infinity>();
        l_2_pred = l_2;
        if(res_dual < epsilon){
            break;
        }
        if(adaptative_rho){
            if(res_prim > mu_thresh*res_dual){ //rho needs to be increased
                if( cpt% 5 == 0){ //limits the frequency of rho update to 1 every 5 iterations
                    if (rho_up ==-1){
                        tau_inc = 1+.8*(tau_inc-1);
                        tau_dec = 1+.8*(tau_dec-1);
                    }
                    P += rho*(tau_inc-1)*MatrixXd::Identity(P.rows(), P.cols());
                    rho *= tau_inc;
                    chol = P.llt();
                    Pinv.setIdentity(); chol.solveInPlace(Pinv);
                    rho_up= 1;
                }
                cpt++;
            }
            else if (res_dual > mu_thresh*res_prim){//rho needs to be decreased
                if( cpt% 5 == 0){
                    if (rho_up ==1){
                        tau_inc = 1+.8*(tau_inc-1);
                        tau_dec = 1+.8*(tau_dec-1);
                    }
                    P += rho*(1./tau_dec-1)*MatrixXd::Identity(P.rows(), P.cols());
                    rho /= tau_dec;
                    chol = P.llt();
                    Pinv.setIdentity(); chol.solveInPlace(Pinv);
                    rho_up=-1;
                }
                cpt++;
            }
        }
    };
    return l_2;
}

VectorXd Solver::dualFromPrimalQP(const MatrixXd &P, const VectorXd &q, const VectorXd &l, const double &epsilon=1e-10){//computes dual solutions from primal solution
    VectorXd gamma(l.size());
    gamma = -(P*l + q);
    for (int i = 0; i<gamma.size();i++){
        if(l(i)>epsilon){
            gamma(i) = 0;
        }
    }
    return gamma;
}

VectorXd Solver::solveDerivativesQP(const MatrixXd &P, const VectorXd &q, const VectorXd &l, const VectorXd &gamma, const VectorXd &grad_l, const double &epsilon){ //solves the system obtained from differentiating the KKT optimality conditions
    std::vector<int> not_null;
    for (int i = 0; i<gamma.size(); i++){
        if(gamma(i)>1e-10){
            not_null.push_back(i);
        }
    }
    MatrixXd B = gamma.asDiagonal();
    MatrixXd C = MatrixXd::Identity(l.size(), l.size());
    MatrixXd A_tild(not_null.size(), not_null.size()), B_tild(not_null.size(),l.size()), C_tild(l.size(),not_null.size()), D_tild(l.size(),l.size());
    A_tild = MatrixXd::Zero(not_null.size(), not_null.size());
    for(int i = 0; i< not_null.size();i++){
        A_tild(i,i) = l(not_null[i]);
        B_tild.row(i) = B.row(not_null[i]);
        C_tild.col(i) = C.col(not_null[i]);
    }
    D_tild = P;
    MatrixXd A(l.size()+not_null.size(),l.size()+not_null.size());
    A.topLeftCorner(not_null.size(),not_null.size()) = A_tild;
    A.topRightCorner(not_null.size(),l.size()) = B_tild;
    A.bottomLeftCorner(l.size(),not_null.size()) = C_tild;
    A.bottomRightCorner(l.size(),l.size()) = D_tild;
    A.transposeInPlace();
    VectorXd dd(A.cols());
    for(int i = 0 ; i< dd.size(); i++){
        if(i<not_null.size()){
            dd(i) = 0.;
        }
        else{
            dd(i) = grad_l(i-not_null.size());
        }
    }
    VectorXd b(A.cols());
    b = Solver::iterative_refinement(A,dd);
    VectorXd bl(l.size());
    for(int i = 0; i <l.size();i++){
        bl(i) = b(not_null.size()+i);
    }
    return bl;
}

void Solver::prox_circle(VectorXd &l, const VectorXd &l_n){//projection of l on the disk of radius l_n
    int nb_contacts;
    double norm_l2d;
    VectorXd l_2d(2);
    nb_contacts = l_n.size();
    for(int i = 0; i<nb_contacts; i++){
        l_2d(0) = l(2*i);
        l_2d(1) = l(2*i+1);
        norm_l2d = l_2d.norm();
        if(norm_l2d> l_n(i)){
            l(2*i) = l_2d(0)*l_n(i)/norm_l2d;
            l(2*i+1) = l_2d(1)*l_n(i)/norm_l2d;
        }
    }
}

VectorXd Solver::solveQCQP( MatrixXd P, const VectorXd &q, const VectorXd &l_n, const VectorXd &warm_start, const double epsilon=1e-10, const double mu_prox = 1e-7, const int max_iter = 1000, const bool adaptative_rho=true){
    double L, rho, res_dual, res_prim, eps_rel, tau_dec, tau_inc, mu_thresh, alpha_relax;
    mu_thresh = 10.; alpha_relax = 1.5;
    eps_rel = 1e-4;
    MatrixXd Pinv(P.rows(), P.cols());
    VectorXd q_prox(q.size()), l(q.size()), Plqu(q.size());
    VectorXd u = VectorXd::Zero(q.size());
    VectorXd l_2 = VectorXd::Zero(q.size());VectorXd l_2_pred = VectorXd::Zero(q.size());
    l = warm_start;
    L = Solver::power_iteration(P, epsilon, 100);
    rho = std::sqrt(mu_prox * L) * std::pow(L / mu_prox, .4);
    tau_dec = std::pow(L / mu_prox, .15);
    tau_inc = tau_dec;
    q_prox = q;
    P += (rho + mu_prox) * MatrixXd::Identity(P.rows(), P.cols());
    LLT<MatrixXd> chol = P.llt();
    Pinv.setIdentity();
    chol.solveInPlace(Pinv);

    int rho_up = 0, cpt=0;
    for(int i = 0; i< max_iter; i++){
        l = Pinv * (rho * l_2 - u - q_prox);
        q_prox = q - mu_prox * l;
        l_2 = alpha_relax * l + (1 - alpha_relax) * l_2 + u / rho;
        Solver::prox_circle(l_2,l_n);
        u += rho*(alpha_relax*l + (1-alpha_relax)*l_2_pred-l_2);
        Plqu = l_2-l_2_pred;
        res_dual = rho*Plqu.lpNorm<Infinity>();
        res_prim = (l_2-(alpha_relax*l + (1-alpha_relax)*l_2_pred)).lpNorm<Infinity>();
        l_2_pred = l_2;
        if( res_prim < epsilon + eps_rel*l.norm() && res_dual < epsilon ){
            break;
        }
        if (adaptative_rho){
            if( res_prim > mu_thresh*res_dual){//rho needs to be increased
                if(cpt%5 ==0){// limits the frequency of rho update to every 5 iterations
                    if (rho_up ==-1){
                        tau_inc = 1+.8*(tau_inc-1);
                    }
                    P += rho*(tau_inc-1)*MatrixXd::Identity(P.rows(), P.cols());
                    rho *= tau_inc;
                    chol = P.llt();
                    Pinv.setIdentity();chol.solveInPlace(Pinv);
                    rho_up= 1;
                }
                cpt++;

            }
            else if ( res_dual > mu_thresh*res_prim){
                if(cpt%5 ==0){
                    if (rho_up ==1){
                        tau_dec = 1+.8*(tau_dec-1);
                    }
                    P +=rho*(1./tau_dec-1)*MatrixXd::Identity(P.rows(), P.cols());
                    rho /= tau_dec;
                    chol = P.llt();
                    Pinv.setIdentity(); chol.solveInPlace(Pinv);
                    rho_up=-1;
                }
                cpt++;
            }
        }
    };
    return l_2;
}

VectorXd Solver::dualFromPrimalQCQP(const MatrixXd &P, const VectorXd &q, const VectorXd &l_n, const VectorXd &l, const double &epsilon=1e-10){
    VectorXd gamma(l_n.size()),slack(l_n.size()),l_2d(2) ;
    MatrixXd  A = MatrixXd::Zero(l.size(), l_n.size());
    std::vector<int> not_null;
    slack = l_n;
    for(int i = 0; i<l_n.size(); i++){
        A(2*i,i) = 2*l(2*i);
        A(2*i+1,i) = 2*l(2*i+1);
    }
    for (int i = 0; i<gamma.size();i++){
        l_2d(0) = l(2*i);
        l_2d(1) = l(2*i+1);
        slack(i) += -l_2d.norm();
        if(slack(i)>epsilon){
            gamma(i) = 0;
        }
        else
        {
            not_null.push_back(i);
        }
    }
    MatrixXd A_tild(A.rows(), not_null.size());
    for (int i = 0; i < not_null.size(); ++i) {
        A_tild.col(i) = A.col(not_null[i]);
    }
    VectorXd gamma_not_null(not_null.size());
    gamma_not_null = -(A_tild.transpose()*A_tild).llt().solve(A_tild.transpose()*(P*l+q));
    int idx;
    for(int i=0; i<not_null.size();i++){
        idx =not_null[i];
        gamma(idx) = gamma_not_null(i);
    }
    return gamma;
}

VectorXd Solver::solveDerivativesQCQP(const MatrixXd &P, const VectorXd &q, const VectorXd &l_n, const VectorXd &l, const VectorXd &gamma, const VectorXd &grad_l, const double &epsilon){
    int nb_contacts = l_n.size();
    VectorXd slack(nb_contacts);
    slack = -l_n.cwiseProduct(l_n);
    double norm_l2d;
    VectorXd l_2d(2);
    MatrixXd C(2*nb_contacts,nb_contacts);
    MatrixXd D_tild = MatrixXd::Zero(2*nb_contacts, 2*nb_contacts);
    for(int i = 0; i<nb_contacts; i++){
        l_2d(0) = l(2*i);
        l_2d(1) = l(2*i+1);
        norm_l2d = l_2d.squaredNorm();
        slack(i) = slack(i) + norm_l2d;
        C(2*i,i) = 2*l(2*i);
        C(2*i+1,i) = 2*l(2*i+1);
        D_tild(2*i,2*i) = 2*gamma(i);
        D_tild(2*i+1,2*i+1) = 2*gamma(i);
    }
    std::vector<int> not_null;
    for (int i = 0; i<nb_contacts; i++){
        if(slack(i)>-1e-10){
            not_null.push_back(i);
        }
    }
    MatrixXd A_tild = MatrixXd::Zero(not_null.size(),not_null.size());
    MatrixXd B = gamma.asDiagonal()*(C.transpose());
    MatrixXd B_tild(not_null.size(),B.cols()), C_tild(C.rows(), not_null.size());
    for(int i = 0; i< not_null.size(); i++){
        A_tild(i,i) = slack(not_null[i]);
        B_tild.row(i) = B.row(not_null[i]);
        C_tild.col(i) = C.col(not_null[i]);
    }
    D_tild = D_tild+P;
    MatrixXd A(l.size()+not_null.size(),l.size()+not_null.size());
    A.topLeftCorner(not_null.size(),not_null.size()) = A_tild;
    A.topRightCorner(not_null.size(),l.size()) = B_tild;
    A.bottomLeftCorner(l.size(),not_null.size()) = C_tild;
    A.bottomRightCorner(l.size(),l.size()) = D_tild;
    A.transposeInPlace();

    VectorXd dd(A.cols());
    for(int i = 0 ; i< dd.size(); i++){
        if(i<not_null.size()){
            dd(i) = 0.;
        }
        else{
            dd(i) = grad_l(i-not_null.size());
        }
    }
    VectorXd b(A.cols());
    b = Solver::iterative_refinement(A,dd);
    VectorXd blgamma = VectorXd::Zero(gamma.size()+l.size());
    for(int i = 0; i<b.size();i++){
        if(i<not_null.size()){
            blgamma(not_null[i]) = b(i);
        }
        else{
            blgamma(nb_contacts-not_null.size()+i) = b(i);
        }
    }
    return blgamma;
}

std::tuple<MatrixXd,MatrixXd> Solver::getE12QCQP(const VectorXd &l_n, const VectorXd &mu, const VectorXd &gamma){
    MatrixXd E1 = MatrixXd::Zero(l_n.size(),l_n.size());
    MatrixXd E2 = MatrixXd::Zero(l_n.size(),l_n.size());
    for (int i = 0;i<l_n.size();i++){
        E1(i,i) = 2*gamma(i)*l_n(i)*l_n(i)*mu(i);
        E2(i,i) = 2*gamma(i)*l_n(i)*mu(i)*mu(i);
    }
    return std::make_tuple(E1,E2);
}

void Solver::prox_lorentz(VectorXd &l)
{//projection of l onto Lorentz cone |l_ti| <= l_ni
    int nb_contacts;
    double norm_lfi;
    double mag;
    double mag_normed;
    VectorXd l_fi(2);
    nb_contacts = l.size() / 3;
    for (int i = 0; i<nb_contacts; i++)
    {
        l_fi(0) = l(nb_contacts + 2 * i);
        l_fi(1) = l(nb_contacts + 2 * i + 1);
        norm_lfi = l_fi.norm();
        if (norm_lfi > l(i))
        {
            if (norm_lfi > -l(i))
            {
                mag = (l(i) + norm_lfi) / 2.0;
                l(i) = mag;
                mag_normed = mag / norm_lfi;
                l(nb_contacts + 2 * i) *= mag_normed;
                l(nb_contacts + 2 * i + 1) *= mag_normed;
            }
            else
            {
                l(i) = 0.0;
                l(nb_contacts + 2 * i) = 0.0;
                l(nb_contacts + 2 * i + 1) = 0.0;
            }
        }
    }
}

VectorXd Solver::solveLCQP( MatrixXd P, const VectorXd &q, const VectorXd &warm_start, const double epsilon=1e-10, const double mu_prox = 1e-7, const int max_iter = 1000, const bool adaptative_rho=true){
    double L, rho, res_dual, res_prim, eps_rel, tau_dec, tau_inc, mu_thresh, alpha_relax;
    mu_thresh = 10.; alpha_relax = 1.5;
    eps_rel = 1e-4;
    MatrixXd Pinv(P.rows(), P.cols());
    VectorXd q_prox(q.size()), l(q.size()), Plqu(q.size());
    VectorXd u = VectorXd::Zero(q.size());
    VectorXd l_2 = VectorXd::Zero(q.size());VectorXd l_2_pred = VectorXd::Zero(q.size());
    l = warm_start;
    L = Solver::power_iteration(P, epsilon, 100);
    rho = std::sqrt(mu_prox * L) * std::pow(L / mu_prox, .4);
    tau_dec = std::pow(L / mu_prox, .15);
    tau_inc = tau_dec;
    q_prox = q;
    P += (rho + mu_prox) * MatrixXd::Identity(P.rows(), P.cols());
    LLT<MatrixXd> chol = P.llt();
    Pinv.setIdentity();
    chol.solveInPlace(Pinv);

    int rho_up = 0, cpt=0;
    for(int i = 0; i< max_iter; i++){
        l = Pinv * (rho * l_2 - u - q_prox);
        q_prox = q - mu_prox * l;
        l_2 = alpha_relax * l + (1 - alpha_relax) * l_2 + u / rho;
        Solver::prox_lorentz(l_2);
        u += rho*(alpha_relax*l + (1-alpha_relax)*l_2_pred-l_2);
        Plqu = l_2-l_2_pred;
        res_dual = rho*Plqu.lpNorm<Infinity>();
        res_prim = (l_2-(alpha_relax*l + (1-alpha_relax)*l_2_pred)).lpNorm<Infinity>();
        l_2_pred = l_2;
        if( res_prim < epsilon + eps_rel*l.norm() && res_dual < epsilon ){
            break;
        }
        if (adaptative_rho){
            if( res_prim > mu_thresh*res_dual){//rho needs to be increased
                if(cpt%5 ==0){// limits the frequency of rho update to every 5 iterations
                    if (rho_up ==-1){
                        tau_inc = 1+.8*(tau_inc-1);
                    }
                    P += rho*(tau_inc-1)*MatrixXd::Identity(P.rows(), P.cols());
                    rho *= tau_inc;
                    chol = P.llt();
                    Pinv.setIdentity();chol.solveInPlace(Pinv);
                    rho_up= 1;
                }
                cpt++;

            }
            else if ( res_dual > mu_thresh*res_prim){
                if(cpt%5 ==0){
                    if (rho_up ==1){
                        tau_dec = 1+.8*(tau_dec-1);
                    }
                    P +=rho*(1./tau_dec-1)*MatrixXd::Identity(P.rows(), P.cols());
                    rho /= tau_dec;
                    chol = P.llt();
                    Pinv.setIdentity(); chol.solveInPlace(Pinv);
                    rho_up=-1;
                }
                cpt++;
            }
        }
    };
    return l_2;
}

VectorXd Solver::solveDerivativesLCQP(const MatrixXd &P, const VectorXd &q, const VectorXd &l, const VectorXd &grad_l, const double &epsilon){
    int nb_contacts = l.size() / 3;
    VectorXd slack(nb_contacts);
    double norm_lfi;
    VectorXd l_fi(2);
    VectorXd bl = VectorXd::Zero(l.size());
    double constraint_eps = epsilon;
    std::vector<int> base_inactive;

    for(int i = 0; i < nb_contacts; i++){
        if(l(i) > constraint_eps)
        {
                base_inactive.push_back(i);
        }
    }

    int n_lvars = base_inactive.size();
    if (n_lvars == 0)
    {
        return bl;
    }

    // nonzero grad_l; procede to generating it
    // first, remove inactive cones
    int ni, fxi, fyi;
    VectorXd q_not_null = VectorXd::Zero(3 * n_lvars);
    VectorXd grad_l_not_null = VectorXd::Zero(3 * n_lvars);
    VectorXd l_not_null = VectorXd::Zero(3 * n_lvars);
    MatrixXd P_pretild = MatrixXd::Zero(l.size(), 3 * n_lvars);
    MatrixXd P_tild = MatrixXd::Zero(3 * n_lvars, 3 * n_lvars);
    std::vector<int> edge_active;
    for (int i = 0; i<n_lvars; i++){
        ni = base_inactive[i];
        fxi = base_inactive[i] * 2 + nb_contacts;
        fyi = fxi + 1;

        grad_l_not_null(i) = grad_l(ni);
        grad_l_not_null(n_lvars + 2 * i) = grad_l(fxi);
        grad_l_not_null(n_lvars + 2 * i + 1) = grad_l(fyi);

        q_not_null(i) = q(ni);
        q_not_null(n_lvars + 2 * i) = q(fxi);
        q_not_null(n_lvars + 2 * i + 1) = q(fyi);

        l_not_null(i) = l(ni);
        l_not_null(n_lvars + 2 * i) = l(fxi);
        l_not_null(n_lvars + 2 * i + 1) = l(fyi);

        P_pretild.col(i) = P.col(ni);
        P_pretild.col(n_lvars + 2 * i) = P.col(fxi);
        P_pretild.col(n_lvars + 2 * i) = P.col(fyi);

        l_fi(0) = l(fxi);
        l_fi(1) = l(fyi);
        if ((l(ni) - l_fi.norm()) < constraint_eps)
        {
            edge_active.push_back(i);
        }

    }
    for (int i = 0; i<n_lvars; i++){
        ni = base_inactive[i];
        fxi = base_inactive[i] * 2 + nb_contacts;
        fyi = fxi + 1;
        P_tild.row(i) = P_pretild.row(ni);
        P_tild.row(n_lvars + 2 * i) = P_pretild.row(fxi);
        P_tild.row(n_lvars + 2 * i) = P_pretild.row(fyi);
    }

    // terminate early if no active constraints
    int n_constraints = edge_active.size();
    MatrixXd A(n_constraints + 3 * n_lvars, n_constraints + 3 * n_lvars);
    double gamma_max = 0;
    if (n_constraints == 0)
    {
        A = P_tild;
    }
    else
    {
        // constraint matrix

        MatrixXd B = MatrixXd::Zero(n_constraints, 3 * n_lvars);
        for (int i = 0; i < n_constraints; i++){
            ni = edge_active[i];
            fxi = edge_active[i] * 2 + n_lvars;
            fyi = fxi + 1;
            B(i, ni) = - 2. * l_not_null(ni);
            B(i, fxi) = 2. * l_not_null(fxi);
            B(i, fyi) = 2. * l_not_null(fyi);
        }
        VectorXd obj_grad_not_null(3 * n_lvars);
        obj_grad_not_null = P_tild * l_not_null + q_not_null;
        VectorXd gamma_not_null(n_constraints);

        gamma_not_null = iterative_refinement(B.transpose(), -obj_grad_not_null);
        gamma_max = gamma_not_null.maxCoeff();

        VectorXd D_diag = VectorXd::Zero(3 * n_lvars);
        for (int i = 0; i<edge_active.size(); i++){
            ni = edge_active[i];
            fxi = edge_active[i] * 2 + n_lvars;
            fyi = fxi + 1;
            D_diag(ni) = -2 * gamma_not_null(i);
            D_diag(fxi) = 2 * gamma_not_null(i);
            D_diag(fyi) = 2 * gamma_not_null(i);
        }

        A.topRightCorner(n_constraints, 3 * n_lvars) = B;
        A.bottomLeftCorner(3 * n_lvars, n_constraints) = B.transpose();
        A.bottomRightCorner(3 * n_lvars, 3 * n_lvars) = P_tild + MatrixXd(D_diag.asDiagonal());
    }

    VectorXd dd(A.rows());
    for(int i = 0 ; i< dd.size(); i++){
        if(i<n_constraints){
            dd(i) = 0.;
        }
        else{
            dd(i) = grad_l_not_null(i-n_constraints);
        }
    }

    VectorXd b = iterative_refinement(A, dd);
    for (int i = 0; i < n_lvars ; i++)
    {
        ni = base_inactive[i];
        fxi = base_inactive[i] * 2 + nb_contacts;
        fyi = fxi + 1;
        //bl(base_inactive[i]) = b(i+edge_active.size());
        bl(ni) = b(n_constraints + i);
        bl(fxi) = b(n_constraints + n_lvars + 2 * i);
        bl(fyi) = b(n_constraints + n_lvars + 2 * i + 1);
    }
    return bl;

}

int Solver::test(){
    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::duration<float> fsec;
    MatrixXd m2(4,4);
    m2 << 4.45434,  1.11359, -2.22717,  1.11359,
         1.11359,  4.45434,  1.11359, -2.22717,
        -2.22717,  1.11359,  4.45434,  1.11359,
         1.11359, -2.22717,  1.11359,  4.45434;
    VectorXd sol(4),sol2(4),q2(4),l_n(2), warm_start2(4);
    l_n(0) = 1;
    l_n(1) = 1;
    l_n = l_n*10000;
    q2 << -0.0112815,-0.0083385,-0.0083385,-0.0112815;
    //q2 << -0.00981,-0.00981,-0.00981,-0.00981;
    warm_start2 << 0.00220234,0.00220234,0.00220234,0.00220234;
    m2.setZero();m2(0,0) = .0005;m2(1,1) = 3.;
    q2.setZero(); q2(0) = -8000; q2(1) = 0.;
    warm_start2.setZero();
    //sol = Solver::solveQCQP(m2,q2,l_n,warm_start2, 1e-10,1e-7,1000);
    sol = Solver::solveQP(m2,q2,warm_start2, 1e-10,1e-7,1000);
    std::cout << " solution  : " << sol << std::endl;
    VectorXd gamma(sol.size());
    gamma = Solver::dualFromPrimalQCQP(m2,q2,l_n,sol);
    MatrixXd  A(sol.size(), l_n.size());
    for(int i = 0; i<l_n.size(); i++){
        A(2*i,i) = 2*sol(2*i);
        A(2*i+1,i) = 2*sol(2*i+1);
    }
    //std::cout<< "KKT : " << m2*sol + q2 + A*gamma << std::endl;
    //std::cout << "solution : " << sol << std::endl;
    //std::cout << "solution dual : " << gamma << std::endl;
    VectorXd grad_l(sol.size());
    VectorXd bl(sol.size());
    bl = Solver::solveDerivativesQCQP(m2,q2,l_n,sol,gamma,grad_l,1e-8);
    //std::cout << " bl : " << bl << std::endl;

    sol2 = Solver::solveQP(m2,q2,warm_start2,1e-10,1e-7,1);
    VectorXd gamma2(sol2.size());
    gamma2 = Solver::dualFromPrimalQP(m2,q2,sol2);
    //std::cout<< "KKT 2: " << m2*sol2 + q2 + gamma2 << std::endl;
    //std::cout << "solution 2: " << sol2 << std::endl;
    //std::cout << "solution dual 2 : " << gamma2 << std::endl;
    VectorXd grad_l2(sol2.size());
    VectorXd bl2(sol2.size());
    bl2 = Solver::solveDerivativesQP(m2,q2,sol2,gamma2,grad_l2,1e-8);
    //std::cout << " bl2 : " << bl2 << std::endl;

    MatrixXd G2(12,12);
    G2 <<  6.6174e-24,  0.0000e+00,  0.0000e+00,  0.0000e+00, -4.8452e-04, 0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00, 0.0000e+00,  0.0000e+00,
         0.0000e+00, -6.6174e-24,  0.0000e+00,  0.0000e+00,  0.0000e+00, 0.0000e+00, -3.9642e-04,  0.0000e+00,  0.0000e+00,  0.0000e+00, 0.0000e+00,  0.0000e+00,
         0.0000e+00,  0.0000e+00, -6.6174e-24,  0.0000e+00,  0.0000e+00, 0.0000e+00,  0.0000e+00,  0.0000e+00, -3.9642e-04, -7.1925e-20, 0.0000e+00,  0.0000e+00,
         0.0000e+00,  0.0000e+00,  0.0000e+00,  6.6174e-24,  0.0000e+00, 0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00, -4.8452e-04,  4.4048e-20,
        -1.0544e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00,  4.3570e+03, -1.6704e+00,  4.4543e+00,  1.6704e+00,  1.1136e+00,  1.6704e+00, 1.1136e+00, -1.6704e+00,
         0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00, -1.6704e+00, 4.3570e+03, -1.6704e+00,  1.1136e+00,  1.6704e+00,  1.1136e+00, 1.6704e+00,  4.4543e+00,
         0.0000e+00, -1.0544e+00,  0.0000e+00,  0.0000e+00,  4.4543e+00, -1.6704e+00,  5.3243e+03,  1.6704e+00,  1.1136e+00,  1.6704e+00, 1.1136e+00, -1.6704e+00,
         0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00,  1.6704e+00, 1.1136e+00,  1.6704e+00,  5.3243e+03, -1.6704e+00,  4.4543e+00, -1.6704e+00,  1.1136e+00,
        0.0000e+00,  0.0000e+00, -1.0544e+00,  0.0000e+00,  1.1136e+00, 1.6704e+00,  1.1136e+00, -1.6704e+00,  5.3243e+03, -1.6704e+00,4.4543e+00,  1.6704e+00,
        0.0000e+00,  0.0000e+00, -1.9131e-16,  0.0000e+00,  1.6704e+00,1.1136e+00,  1.6704e+00,  4.4543e+00, -1.6704e+00,  5.3243e+03,-1.6704e+00,  1.1136e+00,
        0.0000e+00,  0.0000e+00,  0.0000e+00, -1.0544e+00,  1.1136e+00,1.6704e+00,  1.1136e+00, -1.6704e+00,  4.4543e+00, -1.6704e+00,4.3570e+03,  1.6704e+00,
        0.0000e+00,  0.0000e+00,  0.0000e+00,  9.5861e-17, -1.6704e+00,4.4543e+00, -1.6704e+00,  1.1136e+00,  1.6704e+00,  1.1136e+00,1.6704e+00,  4.3570e+03;
    G2(0,0) = 0; G2(1,1) = 4e1;
    G2 = G2*G2.transpose();
    VectorXd g2(12), l_ng(6), l_ng2(6);
    g2 << 0.0000e+00,0.0000e+00,0.0000e+00,0.0000e+00,7.2829e-04,2.2609e-14,7.2829e-04,2.2609e-14,7.2829e-04,2.2609e-14,7.2829e-04,2.2609e-14;
    VectorXd sol3(12);
    //VectorXd warm_start3  = VectorXd::Zero(12);
    VectorXd warm_start3  = VectorXd::Random(12);

    double mean,mean2, mean3;
    mean = 0;mean2 = 0.; mean3 = 0.;
    int ntest = 1000;
    std::srand((unsigned int) time(0));
    int test_dimension = 6;
    MatrixXd G(2*test_dimension,2*test_dimension);
    VectorXd g(test_dimension);
    VectorXd grad_l3 = VectorXd::Ones(2*test_dimension);
    VectorXd gamma3(2*test_dimension);
    for (int i = 0; i< ntest; i++){
        //std::cout<< "prob id : " << i << std::endl;
        g = VectorXd::Random(2*test_dimension)*10;
        g = g.array().exp();
        G = g.asDiagonal();
        //G = MatrixXd::Random(2*test_dimension,2*test_dimension);
        //G = G*G.transpose();
        g = VectorXd::Random(2*test_dimension);
        SelfAdjointEigenSolver<MatrixXd> eigensolver(G);
        if (eigensolver.info() != Success) abort();
        //cout << "The eigenvalues of G are:\n" << eigensolver.eigenvalues() << endl;
        l_ng = VectorXd::Random(test_dimension)+VectorXd::Ones(test_dimension);
        l_ng = l_ng*.1;
        l_ng2 = l_ng*100000;
        //std::cout<< "lng: " << l_ng << "\n";
        auto t0 = Time::now();
        //sol3 = Solver::solveQP(G,g,warm_start3,1e-10,1e-7,10000);
        auto t1 = Time::now();
        //sol3 = Solver::solveQCQP(G,g,l_ng,warm_start3,1e-10,1e-7,100000);
        sol3 = Solver::solveQP(G,g,warm_start3,1e-10,1e-7,100000, true );
        auto t2 = Time::now();
        gamma3 = Solver::dualFromPrimalQP(G,g,sol3,1e-10);
        Solver::solveDerivativesQP(G,g,sol3,gamma,grad_l3,1e-10);
        auto t3 = Time::now();
        sol3 = Solver::solveQCQP(G,g,l_ng2,warm_start3,1e-10,1e-7,100000);
        auto t33 = Time::now();
        gamma3 = Solver::dualFromPrimalQCQP(G,g,l_ng2,sol3,1e-10);
        Solver::solveDerivativesQCQP(G,g,l_ng2,sol3,gamma3,grad_l3,1e-10);
        auto t4 = Time::now();
        fsec fs = t1 - t0;
        fsec fs2 = t3 - t2;
        fsec fs3 = t4 - t33;
        mean += fs.count();
        mean2 += fs2.count();
        mean3 += fs3.count();
        //std::cout << "grad to sol: " << (G*sol3 +g ) << "\n";

    }

    //fsec fs = t1 - t0;
    //std::cout<< "solving QP: " << mean/ntest << "s\n";
    std::cout<< "diff QP1: " << mean2/ntest << "s\n";
    std::cout<< "diff QCQP2: " << mean3/ntest << "s\n";

    //std::cout << " IR : " << Solver::iterative_refinement(G,g,1e-14) << std::endl;
    return 0;
}

max_stars_repo_name: mshalm/diffqcqp

max_issues_repo_name: mshalm/diffqcqp

max_forks_repo_name: mshalm/diffqcqp


text:
#define BOOST_TEST_DYN_LINK
#ifdef STAND_ALONE
#   define BOOST_TEST_MODULE Main
#endif
#include <boost/test/unit_test.hpp>

#include "corm/BeanCreator.h"

#include "DummyClass.h"

BOOST_AUTO_TEST_SUITE(BeanCreator_Test_Suite)

BOOST_AUTO_TEST_CASE(Singleton_Scalar_Creator) {
	corm::SingletonBeanCreator<DummyClass&> creator;

	corm::ValueWrapper<DummyClass&>* wrapper = creator.create();
	DummyClass& dummy1 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, dummy1.getValue());

	wrapper = creator.create();
	DummyClass& dummy2 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, dummy2.getValue());

	// Verify that it is the same instance
	dummy1.setValue(5);
	BOOST_CHECK_EQUAL(5, dummy1.getValue());
	BOOST_CHECK_EQUAL(5, dummy2.getValue());
	BOOST_CHECK_EQUAL(&dummy1, &dummy2);
}

BOOST_AUTO_TEST_CASE(Singleton_Pointer_Creator) {
	corm::SingletonBeanCreator<DummyClass*> creator;

	corm::ValueWrapper<DummyClass*>* wrapper = creator.create();
	DummyClass* dummy1 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, dummy1->getValue());

	wrapper = creator.create();
	DummyClass* dummy2 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, dummy2->getValue());

	// Verify that it is the same instance
	BOOST_CHECK_EQUAL(dummy1, dummy2);
	dummy1->setValue(5);
	BOOST_CHECK_EQUAL(5, dummy1->getValue());
	BOOST_CHECK_EQUAL(5, dummy2->getValue());
}

BOOST_AUTO_TEST_CASE(Factory_Scalar_Creator) {
	corm::FactoryBeanCreator<DummyClass> creator;

	corm::ValueWrapper<DummyClass>* wrapper = creator.create();
	DummyClass dummy1 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, dummy1.getValue());

	wrapper = creator.create();
	DummyClass dummy2 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, dummy2.getValue());

	// Verify that it is the same instance
	dummy1.setValue(5);
	BOOST_CHECK_EQUAL(5, dummy1.getValue());
	BOOST_CHECK_EQUAL(0, dummy2.getValue());
}

BOOST_AUTO_TEST_CASE(Factory_Pointer_Creator) {
	corm::FactoryBeanCreator<DummyClass*> creator;

	corm::ValueWrapper<DummyClass*>* wrapper = creator.create();
	DummyClass* dummy1 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, dummy1->getValue());

	wrapper = creator.create();
	DummyClass* dummy2 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, dummy2->getValue());

	// Verify that it is the same instance
	BOOST_CHECK(dummy1 != dummy2);
	dummy1->setValue(5);
	BOOST_CHECK_EQUAL(5, dummy1->getValue());
	BOOST_CHECK_EQUAL(0, dummy2->getValue());
	delete(dummy1);
	delete(dummy2);
}

BOOST_AUTO_TEST_CASE(Smart_Singleton_Creator) {
	corm::SmartSingletonBeanCreator<DummyClass> creator;

	// Get one instance
	corm::ValueWrapper<std::shared_ptr<DummyClass>>* wrapper = creator.create();
	std::shared_ptr<DummyClass> bean1 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, bean1->getValue());

	// Get a second instance
	wrapper = creator.create();
	std::shared_ptr<DummyClass> bean2 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, bean2->getValue());

	// Make sure that the two instances are the same
	BOOST_CHECK_EQUAL(bean1, bean2);
}

BOOST_AUTO_TEST_CASE(Smart_Factory_Creator) {
	corm::SmartFactoryBeanCreator<DummyClass> creator;

	// Get one instance
	corm::ValueWrapper<std::shared_ptr<DummyClass>>* wrapper = creator.create();
	std::shared_ptr<DummyClass> bean1 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, bean1->getValue());

	// Get a second instance
	wrapper = creator.create();
	std::shared_ptr<DummyClass> bean2 = wrapper->m_value;
	delete(wrapper);
	BOOST_CHECK_EQUAL(0, bean2->getValue());

	// Make sure that the two instances are the same
	BOOST_CHECK(bean1 != bean2);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: cancech/CORM

max_issues_repo_name: cancech/CORM

max_forks_repo_name: cancech/CORM


text:
//
//  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
//  Distributed under 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)
//
#ifndef BOOST_LOCALE_FORMATTING_HPP_INCLUDED
#define BOOST_LOCALE_FORMATTING_HPP_INCLUDED

#include <boost/locale/config.hpp>
#ifdef BOOST_MSVC
#  pragma warning(push)
#  pragma warning(disable : 4275 4251 4231 4660)
#endif
#include <boost/cstdint.hpp>
#include <boost/locale/time_zone.hpp>
#include <ostream>
#include <istream>
#include <string>
#include <string.h>
#include <typeinfo>

namespace boost {
    namespace locale {
        ///
        /// \brief This namespace holds additional formatting
        /// flags that can be set using ios_info.
        ///
        namespace flags {
            ///
            /// Formatting flags, each one of them has corresponding manipulation
            /// in namespace \a as
            ///
            typedef enum {
                posix               = 0,
                number              = 1,
                currency            = 2,
                percent             = 3,
                date                = 4,
                time                = 5,
                datetime            = 6,
                strftime            = 7,
                spellout            = 8,
                ordinal             = 9,

                display_flags_mask  = 31,

                currency_default    = 0 << 5,
                currency_iso        = 1 << 5,
                currency_national   = 2 << 5,

                currency_flags_mask = 3 << 5,

                time_default        = 0 << 7,
                time_short          = 1 << 7,
                time_medium         = 2 << 7,
                time_long           = 3 << 7,
                time_full           = 4 << 7,
                time_flags_mask     = 7 << 7,

                date_default        = 0 << 10,
                date_short          = 1 << 10,
                date_medium         = 2 << 10,
                date_long           = 3 << 10,
                date_full           = 4 << 10,
                date_flags_mask     = 7 << 10,

                datetime_flags_mask = date_flags_mask | time_flags_mask

            } display_flags_type;

            ///
            /// Special string patters that can be used
            /// for text formatting
            ///
            typedef enum {
                datetime_pattern,   ///< strftime like formatting
                time_zone_id        ///< time zone name
            } pattern_type;

            ///
            /// Special integer values that can be used for formatting
            ///
            typedef enum {
                domain_id           ///< Domain code - for message formatting
            } value_type;

        } // flags

        ///
        /// \brief This class holds an external data - beyond existing fmtflags that std::ios_base holds
        ///
        /// You should almost never create this object directly. Instead, you should access it via ios_info::get(stream_object)
        /// static member function. It automatically creates default formatting data for that stream
        ///
        class BOOST_LOCALE_DECL ios_info {
        public:

            /// \cond INTERNAL

            ios_info();
            ios_info(ios_info const &);
            ios_info const &operator=(ios_info const &);
            ~ios_info();

            /// \endcond

            ///
            /// Get ios_info instance for specific stream object
            ///
            static ios_info &get(std::ios_base &ios);

            ///
            /// Set a flags that define a way for format data like number, spell, currency etc.
            ///
            void display_flags(uint64_t flags);

            ///
            /// Set a flags that define how to format currency
            ///
            void currency_flags(uint64_t flags);

            ///
            /// Set a flags that define how to format date
            ///
            void date_flags(uint64_t flags);

            ///
            /// Set a flags that define how to format time
            ///
            void time_flags(uint64_t flags);

            ///
            /// Set a flags that define how to format both date and time
            ///
            void datetime_flags(uint64_t flags);

            ///
            /// Set special message domain identification
            ///
            void domain_id(int);

            ///
            /// Set time zone for formatting dates and time
            ///
            void time_zone(std::string const &);

            ///
            /// Set date/time pattern (strftime like)
            ///
            template<typename CharType>
            void date_time_pattern(std::basic_string<CharType> const &str)
            {
                string_set &s = date_time_pattern_set();
                s.set<CharType>(str.c_str());
            }

            ///
            /// Get a flags that define a way for format data like number, spell, currency etc.
            ///
            uint64_t display_flags() const;

            ///
            /// Get a flags that define how to format currency
            ///
            uint64_t currency_flags() const;

            ///
            /// Get a flags that define how to format date
            ///
            uint64_t date_flags() const;

            ///
            /// Get a flags that define how to format time
            ///
            uint64_t time_flags() const;

            ///
            /// Get a flags that define how to format both date and time
            ///
            uint64_t datetime_flags() const;

            ///
            /// Get special message domain identification
            ///
            int domain_id() const;

            ///
            /// Get time zone for formatting dates and time
            ///
            std::string time_zone() const;

            ///
            /// Get date/time pattern (strftime like)
            ///
            template<typename CharType>
            std::basic_string<CharType> date_time_pattern() const
            {
                string_set const &s = date_time_pattern_set();
                return s.get<CharType>();
            }

            /// \cond INTERNAL
            void on_imbue();
            /// \endcond

        private:

            class string_set;

            string_set const &date_time_pattern_set() const;
            string_set &date_time_pattern_set();

            class BOOST_LOCALE_DECL string_set {
            public:
                string_set();
                ~string_set();
                string_set(string_set const &other);
                string_set const &operator=(string_set const &other);
                void swap(string_set &other);

                template<typename Char>
                void set(Char const *s)
                {
                    delete [] ptr;
                    ptr = 0;
                    type=&typeid(Char);
                    Char const *end = s;
                    while(*end!=0) end++;
                    // if ptr = 0 it does not matter what is value of size
                    size = sizeof(Char)*(end - s+1);
                    ptr = new char[size];
                    memcpy(ptr,s,size);
                }

                template<typename Char>
                std::basic_string<Char> get() const
                {
                    if(type==0 || *type!=typeid(Char))
                        throw std::bad_cast();
                    std::basic_string<Char> result = reinterpret_cast<Char const *>(ptr);
                    return result;
                }

            private:
                std::type_info const *type;
                size_t size;
                char *ptr;
            };

            uint64_t flags_;
            int domain_id_;
            std::string time_zone_;
            string_set datetime_;

            struct data;
            data *d;

        };

        ///
        /// \brief This namespace includes all manipulators that can be used on IO streams
        ///
        namespace as {
            ///
            /// \defgroup manipulators I/O Stream manipulators
            ///
            /// @{
            ///

            ///
            /// Format values with "POSIX" or "C"  locale. Note, if locale was created with additional non-classic locale then
            /// These numbers may be localized
            ///

            inline std::ios_base & posix(std::ios_base & ios)
            {
                ios_info::get(ios).display_flags(flags::posix);
                return ios;
            }

            ///
            /// Format a number. Note, unlike standard number formatting, integers would be treated like real numbers when std::fixed or
            /// std::scientific manipulators were applied
            ///
            inline std::ios_base & number(std::ios_base & ios)
            {
                ios_info::get(ios).display_flags(flags::number);
                return ios;
            }

            ///
            /// Format currency, number is treated like amount of money
            ///
            inline std::ios_base & currency(std::ios_base & ios)
            {
                ios_info::get(ios).display_flags(flags::currency);
                return ios;
            }

            ///
            /// Format percent, value 0.3 is treated as 30%.
            ///
            inline std::ios_base & percent(std::ios_base & ios)
            {
                ios_info::get(ios).display_flags(flags::percent);
                return ios;
            }

            ///
            /// Format a date, number is treated as POSIX time
            ///
            inline std::ios_base & date(std::ios_base & ios)
            {
                ios_info::get(ios).display_flags(flags::date);
                return ios;
            }

            ///
            /// Format a time, number is treated as POSIX time
            ///
            inline std::ios_base & time(std::ios_base & ios)
            {
                ios_info::get(ios).display_flags(flags::time);
                return ios;
            }

            ///
            /// Format a date and time, number is treated as POSIX time
            ///
            inline std::ios_base & datetime(std::ios_base & ios)
            {
                ios_info::get(ios).display_flags(flags::datetime);
                return ios;
            }

            ///
            /// Create formatted date time, Please note, this manipulator only changes formatting mode,
            /// and not format itself, so you are probably looking for ftime manipulator
            ///
            inline std::ios_base & strftime(std::ios_base & ios)
            {
                ios_info::get(ios).display_flags(flags::strftime);
                return ios;
            }

            ///
            /// Spell the number, like "one hundred and ten"
            ///
            inline std::ios_base & spellout(std::ios_base & ios)
            {
                ios_info::get(ios).display_flags(flags::spellout);
                return ios;
            }

            ///
            /// Write an order of the number like 4th.
            ///
            inline std::ios_base & ordinal(std::ios_base & ios)
            {
                ios_info::get(ios).display_flags(flags::ordinal);
                return ios;
            }

            ///
            /// Set default currency formatting style -- national, like "$"
            ///
            inline std::ios_base & currency_default(std::ios_base & ios)
            {
                ios_info::get(ios).currency_flags(flags::currency_default);
                return ios;
            }

            ///
            /// Set ISO currency formatting style, like "USD", (requires ICU >= 4.2)
            ///
            inline std::ios_base & currency_iso(std::ios_base & ios)
            {
                ios_info::get(ios).currency_flags(flags::currency_iso);
                return ios;
            }

            ///
            /// Set national currency formatting style, like "$"
            ///
            inline std::ios_base & currency_national(std::ios_base & ios)
            {
                ios_info::get(ios).currency_flags(flags::currency_national);
                return ios;
            }

            ///
            /// set default (medium) time formatting style
            ///
            inline std::ios_base & time_default(std::ios_base & ios)
            {
                ios_info::get(ios).time_flags(flags::time_default);
                return ios;
            }

            ///
            /// set short time formatting style
            ///
            inline std::ios_base & time_short(std::ios_base & ios)
            {
                ios_info::get(ios).time_flags(flags::time_short);
                return ios;
            }

            ///
            /// set medium time formatting style
            ///
            inline std::ios_base & time_medium(std::ios_base & ios)
            {
                ios_info::get(ios).time_flags(flags::time_medium);
                return ios;
            }

            ///
            /// set long time formatting style
            ///
            inline std::ios_base & time_long(std::ios_base & ios)
            {
                ios_info::get(ios).time_flags(flags::time_long);
                return ios;
            }

            ///
            /// set full time formatting style
            ///
            inline std::ios_base & time_full(std::ios_base & ios)
            {
                ios_info::get(ios).time_flags(flags::time_full);
                return ios;
            }

            ///
            /// set default (medium) date formatting style
            ///
            inline std::ios_base & date_default(std::ios_base & ios)
            {
                ios_info::get(ios).date_flags(flags::date_default);
                return ios;
            }

            ///
            /// set short date formatting style
            ///
            inline std::ios_base & date_short(std::ios_base & ios)
            {
                ios_info::get(ios).date_flags(flags::date_short);
                return ios;
            }

            ///
            /// set medium date formatting style
            ///
            inline std::ios_base & date_medium(std::ios_base & ios)
            {
                ios_info::get(ios).date_flags(flags::date_medium);
                return ios;
            }

            ///
            /// set long date formatting style
            ///
            inline std::ios_base & date_long(std::ios_base & ios)
            {
                ios_info::get(ios).date_flags(flags::date_long);
                return ios;
            }

            ///
            /// set full date formatting style
            ///
            inline std::ios_base & date_full(std::ios_base & ios)
            {
                ios_info::get(ios).date_flags(flags::date_full);
                return ios;
            }

            /// \cond INTERNAL
            namespace details {
                template<typename CharType>
                struct add_ftime {

                    std::basic_string<CharType> ftime;

                    void apply(std::basic_ios<CharType> &ios) const
                    {
                        ios_info::get(ios).date_time_pattern(ftime);
                        as::strftime(ios);
                    }

                };

                template<typename CharType>
                std::basic_ostream<CharType> &operator<<(std::basic_ostream<CharType> &out,add_ftime<CharType> const &fmt)
                {
                    fmt.apply(out);
                    return out;
                }

                template<typename CharType>
                std::basic_istream<CharType> &operator>>(std::basic_istream<CharType> &in,add_ftime<CharType> const &fmt)
                {
                    fmt.apply(in);
                    return in;
                }

            }
            /// \endcond

            ///
            /// Set strftime like formatting string
            ///
            /// Please note, formatting flags are very similar but not exactly the same as flags for C function strftime.
            /// Differences: some flags as "%e" do not add blanks to fill text up to two spaces, not all flags supported.
            ///
            /// Flags:
            /// -   "%a" -- Abbreviated  weekday (Sun.)
            /// -   "%A" -- Full weekday (Sunday)
            /// -   "%b" -- Abbreviated month (Jan.)
            /// -   "%B" -- Full month (January)
            /// -   "%c" -- Locale date-time format. **Note:** prefer using "as::datetime"
            /// -   "%d" -- Day of Month [01,31]
            /// -   "%e" -- Day of Month [1,31]
            /// -   "%h" -- Same as "%b"
            /// -   "%H" -- 24 clock hour [00,23]
            /// -   "%I" -- 12 clock hour [01,12]
            /// -   "%j" -- Day of year [1,366]
            /// -   "%m" -- Month [01,12]
            /// -   "%M" -- Minute [00,59]
            /// -   "%n" -- New Line
            /// -   "%p" -- AM/PM in locale representation
            /// -   "%r" -- Time with AM/PM, same as "%I:%M:%S %p"
            /// -   "%R" -- Same as "%H:%M"
            /// -   "%S" -- Second [00,61]
            /// -   "%t" -- Tab character
            /// -   "%T" -- Same as "%H:%M:%S"
            /// -   "%x" -- Local date representation. **Note:** prefer using "as::date"
            /// -   "%X" -- Local time representation. **Note:** prefer using "as::time"
            /// -   "%y" -- Year [00,99]
            /// -   "%Y" -- 4 digits year. (2009)
            /// -   "%Z" -- Time Zone
            /// -   "%%" -- Percent symbol
            ///

            template<typename CharType>
            #ifdef BOOST_LOCALE_DOXYGEN
            unspecified_type
            #else
            details::add_ftime<CharType>
            #endif
            ftime(std::basic_string<CharType> const &format)
            {
                details::add_ftime<CharType> fmt;
                fmt.ftime=format;
                return fmt;
            }

            ///
            /// See ftime(std::basic_string<CharType> const &format)
            ///
            template<typename CharType>
            #ifdef BOOST_LOCALE_DOXYGEN
            unspecified_type
            #else
            details::add_ftime<CharType>
            #endif
            ftime(CharType const *format)
            {
                details::add_ftime<CharType> fmt;
                fmt.ftime=format;
                return fmt;
            }

            /// \cond INTERNAL
            namespace details {
                struct set_timezone {
                    std::string id;
                };
                template<typename CharType>
                std::basic_ostream<CharType> &operator<<(std::basic_ostream<CharType> &out,set_timezone const &fmt)
                {
                    ios_info::get(out).time_zone(fmt.id);
                    return out;
                }

                template<typename CharType>
                std::basic_istream<CharType> &operator>>(std::basic_istream<CharType> &in,set_timezone const &fmt)
                {
                    ios_info::get(in).time_zone(fmt.id);
                    return in;
                }
            }
            /// \endcond

            ///
            /// Set GMT time zone to stream
            ///
            inline std::ios_base &gmt(std::ios_base &ios)
            {
                ios_info::get(ios).time_zone("GMT");
                return ios;
            }

            ///
            /// Set local time zone to stream
            ///
            inline std::ios_base &local_time(std::ios_base &ios)
            {
                ios_info::get(ios).time_zone(time_zone::global());
                return ios;
            }

            ///
            /// Set time zone using \a id
            ///
            inline
            #ifdef BOOST_LOCALE_DOXYGEN
            unspecified_type
            #else
            details::set_timezone
            #endif
            time_zone(char const *id)
            {
                details::set_timezone tz;
                tz.id=id;
                return tz;
            }

            ///
            /// Set time zone using \a id
            ///
            inline
            #ifdef BOOST_LOCALE_DOXYGEN
            unspecified_type
            #else
            details::set_timezone
            #endif
            time_zone(std::string const &id)
            {
                details::set_timezone tz;
                tz.id=id;
                return tz;
            }

        ///
        /// @}
        ///

        } // as manipulators

    } // locale
} // boost

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

#endif
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
// Author: Jean-Gabriel Young <info@jgyoung.ca>
// Simplicial Configuration Model sampler (rejection method)
// Reference: https://doi.org/10.1103/PhysRevE.96.032312
// arXiv link:  https://arxiv.org/abs/1705.10298
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// STL
#include <cstdlib>   // EXIT_FAILURE, EXIT_SUCCESS

#include <iostream>
#include <fstream>
#include <sstream>

#include <chrono>
#include <vector>
#include <utility>
#include <random>
#include <string>
// Boost
#include <boost/program_options.hpp>
// Program headers
#include "types.h"
#include "scm/scm.h"
#include "io_functions.h"

namespace po = boost::program_options;

int main(int argc, char const *argv[])
{
  /* ~~~~~ Program options ~~~~~~~*/
  std::string facet_list_path;
  std::string degree_seq_file;
  std::string size_seq_file;
  unsigned int num_samples;
  unsigned int seed;

  po::options_description description("Options");
  description.add_options()
  ("seed,d", po::value<unsigned int>(&seed),
      "Seed of the pseudo random number generator (Mersenne-twister 19937). Seed with time if not specified.")
  ("cleansed_input,c", "In facet list mode, assume that the input is already cleansed, i.e., that nodes are labeled with 0 indexed contiguous integers and that no facet is included in another.")
  ("degree_seq_file,k", po::value<std::string>(&degree_seq_file),
    "Path to degree sequence file.")
  ("size_seq_file,s", po::value<std::string>(&size_seq_file),
    "Path to size sequence file.")
  ("verbose,v", "Output log messages.")
  ("help,h", "Produce help message.")
  ;
  po::options_description hidden;
  hidden.add_options()
  ("facet_list_path", po::value<std::string>(&facet_list_path),
      "Path to facet list.")
  ;
  po::positional_options_description p;
  p.add("facet_list_path", -1);
  po::options_description all_options;
  all_options.add(description);
  all_options.add(hidden);
  po::variables_map var_map;
  po::store(po::command_line_parser(argc, argv).
          options(all_options).
          positional(p).
          run(),
          var_map);
  po::notify(var_map);
  if (var_map.count("help") || argc == 1)
  {
      std::cout << "Usage:\n"
                << " [Facet list mode] "+std::string(argv[0])+" [--option_1=VAL] ... [--option_n=VAL] path-to-facet-list\n"
                << " [Seq. mode] "+std::string(argv[0])+" [--option_1=VAL] ... -k path-to-degrees.txt -s path-to-sizes.txt\n";
      std::cout << description;
      return EXIT_SUCCESS;
  }
  if (!var_map.count("facet_list_path") && (!var_map.count("degree_seq_file") && !var_map.count("size_seq_file")))
  {
      std::cerr << "Missing facet list or sequences files.\n";
      return EXIT_FAILURE;
  }
  if (!var_map.count("seed")) {
      // seeding based on the clock
      seed = (unsigned int) std::chrono::high_resolution_clock::now().time_since_epoch().count();
  }

  if (var_map.count("facet_list_path"))
  {
    // facet  list mode
    /* ~~~~~ Load max. facets ~~~~~~~*/
    if (var_map.count("verbose")) std::clog << "Loading facet file.\n";
    adj_list_t maximal_facets;
    vmap_t id_to_vertex;
    std::ifstream file(facet_list_path.c_str());
    if (!file.is_open()) return EXIT_FAILURE;
    unsigned int largest_facet = read_facet_list(maximal_facets, file, var_map.count("cleansed_input") != 0, id_to_vertex);
    file.close();
    /* ~~~~~ Sampling ~~~~~~~*/
    scm_t K(maximal_facets);
    std::mt19937 engine(seed);
    if (var_map.count("verbose"))
    {
      unsigned int tries = 1;
      do
      {
        K.shuffle(engine);
        std::clog << "\rnum_tries: " << tries;
        ++tries;
      } while(!K.is_simplicial_complex());
      std::clog << "\n";
    }
    else
    {
      do
      {
        K.shuffle(engine);
      } while(!K.is_simplicial_complex());
    }
    output_K(K, std::cout, id_to_vertex);
  }
  else
  {
    // seq mode
    /* ~~~~~ Load max. facets ~~~~~~~*/
    if (var_map.count("verbose")) std::clog << "Loading sequence files.\n";
    uint_vec_t d;
    uint_vec_t s;
    {
      std::ifstream file(degree_seq_file.c_str());
      read_sequence_file(file, d);
      file.close();
    }
    {
      std::ifstream file(size_seq_file.c_str());
      read_sequence_file(file, s);
      file.close();
    }
    /* ~~~~~ Sampling ~~~~~~~*/
    scm_t K(s, d);
    std::mt19937 engine(seed);
    if (var_map.count("verbose"))
    {
      unsigned int tries = 1;
      do
      {
        K.shuffle(engine);
        std::clog << "\rnum_tries: " << tries;
        ++tries;
      } while(!K.is_simplicial_complex());
      std::clog << "\n";
    }
    else
    {
      do
      {
        K.shuffle(engine);
      } while(!K.is_simplicial_complex());
    }
    output_K(K, std::cout);
  }
  return EXIT_SUCCESS;
}

max_stars_repo_name: arbenson/scm

max_issues_repo_name: arbenson/scm

max_forks_repo_name: arbenson/scm


text:
#include <ipmid/api.h>
#include <fcntl.h>
#include <boost/container/flat_map.hpp>
#include <iostream>
#include <phosphor-logging/log.hpp>
#include <sdbusplus/message/types.hpp>
#include <sdbusplus/timer.hpp>
#include <psucommands.hpp>
// #include <main.hpp>

namespace inspur
{

void registerPSUFunctions() __attribute__((constructor));

int getPSUNum()
{
    return sizeof(psuConf)/sizeof(psuConf[0]);
}

int getGPIOValue(const int gpio)
{
    char path[64];
    char value_str[3];
    int fd;

    std::snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", gpio);
    fd = open(path, O_RDONLY);
    if (fd < 0)
    {
        std::fprintf(stderr, "Failed to open gpio value for reading!\n");
        return -1;
    }

    if (read(fd, value_str, 3) < 0)
    {
        std::fprintf(stderr, "Failed to read value!\n");
        return -1;
    }

    close(fd);
    return (atoi(value_str));
}

int initGpio(int gpio)
{
    char buffer[64];
    int len;
    int fp;
    fp = open("/sys/class/gpio/export", O_WRONLY);
    if (fp == -1)
    {
        std::fprintf(stderr, "Failed to open gpio export!");
        close(fp);
        return -1;
    }
    len = snprintf(buffer, sizeof(buffer), "%d", gpio);
    if (write(fp, buffer, len) < 0)
    {
        std::fprintf(stderr, "Failed to export gpio!");
    }
    close(fp);
    return 0;
}

int gpioUnexport(int gpio)
{
    char buffer[64];
    int len;
    int fp;
    fp = open("/sys/class/gpio/unexport", O_WRONLY);
    if (fp == -1)
    {
        std::fprintf(stderr, "Failed to open gpio export!");
        close(fp);
        return -1;
    }
    len = snprintf(buffer, sizeof(buffer), "%d", gpio);
    if (write(fp, buffer, len) < 0)
    {
        std::fprintf(stderr, "Failed to unexport gpio!");
        close(fp);
        return -1;
    }
    close(fp);
    return 0;
}

int setDirection(int gpio, int dir)
{
    // 0-->IN, 1-->OUT
    static const char dir_str[] = "in\0out";
    char path[64];
    int fp;

    snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/direction", gpio);
    fp = open(path, O_WRONLY);
    if (fp < 0)
    {
        std::fprintf(stderr, "Failed to open gpio direction!");
        close(fp);
        return -1;
    }

    if (write(fp, &dir_str[dir == 0 ? 0 : 3], dir == 0 ? 2 : 3) < 0)
    {
        std::fprintf(stderr, "Failed to set gpio direction!");
        return -1;
    }

    close(fp);
    return 0;
}

ipmi_ret_t ipmiGetPSUCount(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                                        ipmi_request_t request,
                                        ipmi_response_t response,
                                        ipmi_data_len_t dataLen,
                                        ipmi_context_t context)
{
    // if (*dataLen != 1)
    // {
    //     *dataLen = 0;
    //     return IPMI_CC_REQ_DATA_LEN_INVALID;
    // }
    *dataLen = 0; // default to 0 in case of an error

    // auto req = static_cast<GetPSUNumReq*>(request);
    GetPSUNumRes psuNumRes{};

    // if (req->psuCmd != psuSubCmd)
    // {
    //     return IPMI_CC_INVALID_FIELD_REQUEST;
    // }

    *dataLen = sizeof(GetPSUNumRes);

    psuNumRes.completeCode = 0x00;
    psuNumRes.psuNum = getPSUNum();
    std::memcpy(response, &psuNumRes, *dataLen);

    return IPMI_CC_OK;
}

ipmi_ret_t ipmiGetPSUStatus(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
                                        ipmi_request_t request,
                                        ipmi_response_t response,
                                        ipmi_data_len_t dataLen,
                                        ipmi_context_t context)
{
    if (*dataLen != 1)
    {
        *dataLen = 0;
        return IPMI_CC_REQ_DATA_LEN_INVALID;
    }

    auto req = static_cast<GetPSUStatusReq*>(request);
    GetPSUStatusRes psuInfoRes{};
    int psuIndex = req->psuIndex;
    //  判断index是否超出PSU 总数
    int psuNum = getPSUNum();
    if (psuIndex >= psuNum)
    {
        return IPMI_CC_PARM_OUT_OF_RANGE;
    }

    int initFlag = initGpio(psuConf[psuIndex]);
    if (initFlag == -1)
    {
        return IPMI_CC_PARM_OUT_OF_RANGE;
    }

    int dirFlag = setDirection(psuConf[psuIndex], 0);
    if (dirFlag == -1)
    {
        return IPMI_CC_PARM_OUT_OF_RANGE;
    }

    int psuPresent = getGPIOValue(psuConf[psuIndex]);
    if (psuPresent == -1)
    {
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    int unexport = gpioUnexport(psuConf[psuIndex]);
    if (unexport == -1)
    {
        return IPMI_CC_INVALID_FIELD_REQUEST;
    }

    *dataLen = sizeof(GetPSUStatusRes);
    psuInfoRes.completeCode = 0x00;
    psuInfoRes.PSUInfo.Index = psuIndex;
    psuInfoRes.PSUInfo.Present = psuPresent == 1 ? 0 : 1;

    std::memcpy(response, &psuInfoRes, *dataLen);

    return IPMI_CC_OK;
}

void registerPSUFunctions()
{
    // <Get PSU number>
    ipmi_register_callback(
        netfunInspurAppOEM,
        static_cast<ipmi_cmd_t>(IPMINetfnInspurOEMCmd::cmdGetPSUNumber),
        NULL, ipmiGetPSUCount, PRIVILEGE_USER);
    std::printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n", netfunInspurAppOEM, IPMINetfnInspurOEMCmd::cmdGetPSUNumber);

    // <Get PSU info>
    ipmi_register_callback(
        netfunInspurAppOEM,
        static_cast<ipmi_cmd_t>(IPMINetfnInspurOEMCmd::cmdGetPSUStatus),
        NULL, ipmiGetPSUStatus, PRIVILEGE_USER);
    std::printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n", netfunInspurAppOEM, IPMINetfnInspurOEMCmd::cmdGetPSUStatus);

    return;
}
} // namespace ipmi


text:
#pragma once
#include "MetaObject/python/DataConverter.hpp"
#include <MetaObject/params/IParam.hpp>

#include <boost/python.hpp>

#include <memory>

namespace mo
{
    namespace python
    {

        void setupParameters(const std::string& module_name);

        struct ParamCallbackContainer
        {
            using Ptr_t = std::unique_ptr<ParamCallbackContainer>;
            using Registry_t = std::map<IParam*, std::vector<Ptr_t>>;

            static std::shared_ptr<Registry_t> registry();
            ParamCallbackContainer(mo::IControlParam* ptr, const boost::python::object& obj);

            void onParamUpdate(const IParam&, Header, UpdateFlags, IAsyncStream&);

            void onParamDelete(const IParam&);

          private:
            mo::IControlParam* m_ptr = nullptr;
            boost::python::object m_callback;
            mo::python::DataConverterRegistry::Get_t m_getter;
            UpdateSlot_t m_slot;
            DeleteSlot_t m_delete_slot;
            std::shared_ptr<Connection> del_connection;
            std::shared_ptr<Connection> update_connection;
        };
    } // namespace python
} // namespace mo

max_stars_repo_name: dtmoodie/MetaObject

max_issues_repo_name: dtmoodie/MetaObject

max_forks_repo_name: dtmoodie/MetaObject