text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

#include "equitycrossassetmodel.hpp"

#include <qle/methods/multipathgeneratorbase.hpp>
#include <qle/models/all.hpp>
#include <qle/processes/all.hpp>
#include <qle/pricingengines/all.hpp>

#include <ql/currencies/europe.hpp>
#include <ql/currencies/america.hpp>
#include <ql/indexes/ibor/euribor.hpp>
#include <ql/indexes/ibor/gbplibor.hpp>
#include <ql/indexes/ibor/usdlibor.hpp>
#include <ql/instruments/vanillaoption.hpp>
#include <ql/math/statistics/incrementalstatistics.hpp>
#include <ql/math/optimization/levenbergmarquardt.hpp>
#include <ql/math/randomnumbers/rngtraits.hpp>
#include <ql/methods/montecarlo/multipathgenerator.hpp>
#include <ql/methods/montecarlo/pathgenerator.hpp>
#include <ql/models/shortrate/onefactormodels/gsr.hpp>
#include <ql/models/shortrate/calibrationhelpers/swaptionhelper.hpp>
#include <ql/pricingengines/swaption/gaussian1dswaptionengine.hpp>
#include <ql/termstructures/yield/flatforward.hpp>
#include <ql/time/calendars/target.hpp>
#include <ql/time/daycounters/actual360.hpp>
#include <ql/time/daycounters/thirty360.hpp>
#include <ql/quotes/simplequote.hpp>

#include <test-suite/utilities.hpp>

#include <boost/make_shared.hpp>
// fix for boost 1.64, see https://lists.boost.org/Archives/boost/2016/11/231756.php
#if BOOST_VERSION >= 106400
#include <boost/serialization/array_wrapper.hpp>
#endif
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/covariance.hpp>
#include <boost/accumulators/statistics/error_of_mean.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/variates/covariate.hpp>

using namespace QuantLib;
using namespace QuantExt;

using boost::unit_test_framework::test_suite;
using namespace boost::accumulators;

namespace {

struct CrossAssetData {
    CrossAssetData()
        : referenceDate(30, July, 2015), eurYts(boost::make_shared<FlatForward>(referenceDate, 0.02, Actual365Fixed())),
          usdYts(boost::make_shared<FlatForward>(referenceDate, 0.05, Actual365Fixed())),
          eqDivSp(boost::make_shared<FlatForward>(referenceDate, 0.01, Actual365Fixed())),
          eqDivLh(boost::make_shared<FlatForward>(referenceDate, 0.0075, Actual365Fixed())),
          usdEurSpotToday(boost::make_shared<SimpleQuote>(0.90)), eurEurSpotToday(boost::make_shared<SimpleQuote>(1.0)),
          spSpotToday(boost::make_shared<SimpleQuote>(2100)), lhSpotToday(boost::make_shared<SimpleQuote>(12.50)) {

        SavedSettings backup;

        Settings::instance().evaluationDate() = referenceDate;

        // use different grids for each of the individual processes
        // to test the piecewise numerical integration ...

        std::vector<Date> volstepdatesEur, volstepdatesUsd, volstepdatesFx;
        volstepdatesEqSp.resize(0);
        volstepdatesEqLh.resize(0);

        volstepdatesEur.push_back(Date(15, July, 2016));
        volstepdatesEur.push_back(Date(15, July, 2017));
        volstepdatesEur.push_back(Date(15, July, 2018));
        volstepdatesEur.push_back(Date(15, July, 2019));
        volstepdatesEur.push_back(Date(15, July, 2020));

        volstepdatesUsd.push_back(Date(13, April, 2016));
        volstepdatesUsd.push_back(Date(13, September, 2016));
        volstepdatesUsd.push_back(Date(13, April, 2017));
        volstepdatesUsd.push_back(Date(13, September, 2017));
        volstepdatesUsd.push_back(Date(13, April, 2018));
        volstepdatesUsd.push_back(Date(15, July, 2018)); // shared with EUR
        volstepdatesUsd.push_back(Date(13, April, 2019));
        volstepdatesUsd.push_back(Date(13, September, 2019));

        volstepdatesFx.push_back(Date(15, July, 2016)); // shared with EUR
        volstepdatesFx.push_back(Date(15, October, 2016));
        volstepdatesFx.push_back(Date(15, May, 2017));
        volstepdatesFx.push_back(Date(13, September, 2017)); // shared with USD
        volstepdatesFx.push_back(Date(15, July, 2018));      //  shared with EUR and USD

        volstepdatesEqSp.push_back(Date(13, April, 2016));   // shared with USD
        volstepdatesEqSp.push_back(Date(15, October, 2016)); // shared with FX
        volstepdatesEqSp.push_back(Date(15, March, 2017));
        volstepdatesEqSp.push_back(Date(13, October, 2017));
        volstepdatesEqSp.push_back(Date(15, July, 2018)); //  shared with EUR and USD
        volstepdatesEqSp.push_back(Date(13, October, 2018));

        volstepdatesEqLh.push_back(Date(13, June, 2016));
        volstepdatesEqLh.push_back(Date(15, September, 2016));
        volstepdatesEqLh.push_back(Date(15, April, 2017));
        volstepdatesEqLh.push_back(Date(13, October, 2017));
        volstepdatesEqLh.push_back(Date(15, July, 2018)); //  shared with EUR and USD
        volstepdatesEqLh.push_back(Date(13, December, 2018));

        std::vector<Real> eurVols, usdVols, fxVols, eqSpVols, eqLhVols;

        for (Size i = 0; i < volstepdatesEur.size() + 1; ++i) {
            eurVols.push_back(0.0050 + (0.0080 - 0.0050) * std::exp(-0.3 * static_cast<double>(i)));
        }
        for (Size i = 0; i < volstepdatesUsd.size() + 1; ++i) {
            usdVols.push_back(0.0030 + (0.0110 - 0.0030) * std::exp(-0.3 * static_cast<double>(i)));
        }
        for (Size i = 0; i < volstepdatesFx.size() + 1; ++i) {
            fxVols.push_back(0.15 + (0.20 - 0.15) * std::exp(-0.3 * static_cast<double>(i)));
        }
        for (Size i = 0; i < volstepdatesEqSp.size() + 1; ++i) {
            eqSpVols.push_back(0.20 + (0.35 - 0.20) * std::exp(-0.3 * static_cast<double>(i)));
        }
        for (Size i = 0; i < volstepdatesEqLh.size() + 1; ++i) {
            eqLhVols.push_back(0.25 + (0.45 - 0.25) * std::exp(-0.3 * static_cast<double>(i)));
        }

        Array alphaTimesEur(volstepdatesEur.size()), alphaEur(eurVols.begin(), eurVols.end()), kappaTimesEur(0),
            kappaEur(1, 0.02);
        Array alphaTimesUsd(volstepdatesUsd.size()), alphaUsd(usdVols.begin(), usdVols.end()), kappaTimesUsd(0),
            kappaUsd(1, 0.04);
        Array fxTimes(volstepdatesFx.size()), fxSigmas(fxVols.begin(), fxVols.end());
        Array eqSpTimes(volstepdatesEqSp.size()), spSigmas(eqSpVols.begin(), eqSpVols.end());
        Array eqLhTimes(volstepdatesEqLh.size()), lhSigmas(eqLhVols.begin(), eqLhVols.end());

        for (Size i = 0; i < alphaTimesEur.size(); ++i) {
            alphaTimesEur[i] = eurYts->timeFromReference(volstepdatesEur[i]);
        }
        for (Size i = 0; i < alphaTimesUsd.size(); ++i) {
            alphaTimesUsd[i] = eurYts->timeFromReference(volstepdatesUsd[i]);
        }
        for (Size i = 0; i < fxTimes.size(); ++i) {
            fxTimes[i] = eurYts->timeFromReference(volstepdatesFx[i]);
        }
        for (Size i = 0; i < eqSpTimes.size(); ++i) {
            eqSpTimes[i] = eurYts->timeFromReference(volstepdatesEqSp[i]);
        }
        for (Size i = 0; i < eqLhTimes.size(); ++i) {
            eqLhTimes[i] = eurYts->timeFromReference(volstepdatesEqLh[i]);
        }

        boost::shared_ptr<IrLgm1fParametrization> eurLgmParam =
            boost::make_shared<IrLgm1fPiecewiseConstantParametrization>(EURCurrency(), eurYts, alphaTimesEur, alphaEur,
                                                                        kappaTimesEur, kappaEur);

        boost::shared_ptr<IrLgm1fParametrization> usdLgmParam =
            boost::make_shared<IrLgm1fPiecewiseConstantParametrization>(USDCurrency(), usdYts, alphaTimesUsd, alphaUsd,
                                                                        kappaTimesUsd, kappaUsd);

        boost::shared_ptr<FxBsParametrization> fxUsdEurBsParam =
            boost::make_shared<FxBsPiecewiseConstantParametrization>(USDCurrency(), usdEurSpotToday, fxTimes, fxSigmas);

        boost::shared_ptr<EqBsParametrization> eqSpBsParam = boost::make_shared<EqBsPiecewiseConstantParametrization>(
            USDCurrency(), "SP", spSpotToday, usdEurSpotToday, eqSpTimes, spSigmas, usdYts, eqDivSp);

        boost::shared_ptr<EqBsParametrization> eqLhBsParam = boost::make_shared<EqBsPiecewiseConstantParametrization>(
            EURCurrency(), "LH", lhSpotToday, eurEurSpotToday, eqLhTimes, lhSigmas, eurYts, eqDivLh);

        singleModels.resize(0);
        singleModels.push_back(eurLgmParam);
        singleModels.push_back(usdLgmParam);
        singleModels.push_back(fxUsdEurBsParam);
        singleModels.push_back(eqSpBsParam);
        singleModels.push_back(eqLhBsParam);

        ccLgm = boost::make_shared<CrossAssetModel>(singleModels);

        eurIdx = ccLgm->ccyIndex(EURCurrency());
        usdIdx = ccLgm->ccyIndex(USDCurrency());
        eurUsdIdx = usdIdx - 1;
        eqSpIdx = ccLgm->eqIndex("SP");
        eqLhIdx = ccLgm->eqIndex("LH");

        ccLgm->correlation(IR, eurIdx, IR, usdIdx, -0.2);
        ccLgm->correlation(IR, eurIdx, FX, eurUsdIdx, 0.8);
        ccLgm->correlation(IR, usdIdx, FX, eurUsdIdx, -0.5);
        ccLgm->correlation(EQ, eqSpIdx, EQ, eqLhIdx, 0.6);
        ccLgm->correlation(EQ, eqSpIdx, IR, usdIdx, -0.1);
        ccLgm->correlation(EQ, eqLhIdx, IR, eurIdx, -0.05);
        ccLgm->correlation(EQ, eqSpIdx, FX, eurUsdIdx, 0.1);
    }

    SavedSettings backup;
    Date referenceDate;
    Handle<YieldTermStructure> eurYts, usdYts;
    Handle<YieldTermStructure> eqDivSp, eqDivLh;
    Handle<Quote> usdEurSpotToday, eurEurSpotToday, spSpotToday, lhSpotToday;
    std::vector<boost::shared_ptr<Parametrization> > singleModels;
    boost::shared_ptr<CrossAssetModel> ccLgm;
    Size eurIdx, usdIdx, eurUsdIdx, eqSpIdx, eqLhIdx;
    std::vector<Date> volstepdatesEqSp, volstepdatesEqLh;
};

} // anonymous namespace

namespace testsuite {

void EquityCrossAssetModelTest::testEqLgm5fPayouts() {

    BOOST_TEST_MESSAGE("Testing pricing of equity payouts under domestic "
                       "measure in CrossAsset LGM model...");

    CrossAssetData d;
    Settings::instance().evaluationDate() = d.referenceDate;

    boost::shared_ptr<StochasticProcess> process = d.ccLgm->stateProcess(CrossAssetStateProcess::exact);
    boost::shared_ptr<StochasticProcess> process2 = d.ccLgm->stateProcess(CrossAssetStateProcess::euler);

    // path generation

    Size n = 500000; // number of paths
    Size seed = 121; // seed
    // maturity of test payoffs
    Time T = 5.0;
    // take large steps, but not only one (since we are testing)
    Size steps = static_cast<Size>(T * 2.0);
    Size steps_euler = static_cast<Size>(T * 52.0);
    TimeGrid grid(T, steps);
    TimeGrid grid_euler(T, steps_euler);
    PseudoRandom::rsg_type sg2 = PseudoRandom::make_sequence_generator(steps, seed);

    MultiPathGeneratorMersenneTwister pg(process, grid, seed, false);
    MultiPathGeneratorMersenneTwister pg2(process2, grid_euler, seed, false);

    // test
    // 1 LH (EUR) forward under CrossAsset numeraire vs. analytic pricing engine
    // 2 SP (USD) forward (converted to EUR) under CrossAsset numeraire vs. analytic pricing engine
    // 3 LH (EUR) EQ option under CrossAsset numeraire vs. analytic pricing engine
    // 4 SP (USD) EQ option under CrossAsset numeraire vs. analytic pricing engine

    accumulator_set<double, stats<tag::mean, tag::error_of<tag::mean> > > stat1, stat2, stat3a, stat3b, stat4a, stat4b;

    Real strikeLh = 12.7;
    Real strikeSp = 2150.0;

    // same for paths2 since shared time grid
    for (Size j = 0; j < n; ++j) {
        Sample<MultiPath> path = pg.next();
        // Sample<MultiPath> path = pg2.next();
        Size l = path.value[0].length() - 1;
        Real eurusdfx = std::exp(path.value[2][l]);
        Real zeur = path.value[0][l];
        Real eqsp = std::exp(path.value[3][l]);
        Real eqlh = std::exp(path.value[4][l]);
        Real ccnum = d.ccLgm->numeraire(0, T, zeur);

        // 1 LH forward settled at T deflated with numeraire
        Real lhFwd = eqlh - strikeLh;
        stat1(lhFwd / ccnum);

        // 2 SP forward settled at T (converted to base) deflated with numeraire
        Real spFwd = eurusdfx * (eqsp - strikeSp);
        stat2(spFwd / ccnum);

        // 3 LH option exercise at T deflated with numeraire
        Real lhCall = std::max(lhFwd, 0.0);
        Real lhPut = std::max(-1.0 * lhFwd, 0.0);
        stat3a(lhCall / ccnum);
        stat3b(lhPut / ccnum);

        // 4 SP option exercise at T (converted to base) deflated with numeraire
        Real spCall = std::max(spFwd, 0.0);
        Real spPut = std::max(-1.0 * spFwd, 0.0);
        stat4a(spCall / ccnum);
        stat4b(spPut / ccnum);
    }

    Date tradeMaturity = d.referenceDate + 5 * 365;

    boost::shared_ptr<EquityForward> lhFwdTrade =
        boost::make_shared<EquityForward>("LH", EURCurrency(), Position::Long, 1, tradeMaturity, strikeLh);
    boost::shared_ptr<EquityForward> spFwdTrade =
        boost::make_shared<EquityForward>("SP", USDCurrency(), Position::Long, 1, tradeMaturity, strikeSp);

    boost::shared_ptr<VanillaOption> lhCall =
        boost::make_shared<VanillaOption>(boost::make_shared<PlainVanillaPayoff>(Option::Call, strikeLh),
                                          boost::make_shared<EuropeanExercise>(d.referenceDate + 5 * 365));
    boost::shared_ptr<VanillaOption> lhPut =
        boost::make_shared<VanillaOption>(boost::make_shared<PlainVanillaPayoff>(Option::Put, strikeLh),
                                          boost::make_shared<EuropeanExercise>(d.referenceDate + 5 * 365));
    boost::shared_ptr<VanillaOption> spCall =
        boost::make_shared<VanillaOption>(boost::make_shared<PlainVanillaPayoff>(Option::Call, strikeSp),
                                          boost::make_shared<EuropeanExercise>(d.referenceDate + 5 * 365));
    boost::shared_ptr<VanillaOption> spPut =
        boost::make_shared<VanillaOption>(boost::make_shared<PlainVanillaPayoff>(Option::Put, strikeSp),
                                          boost::make_shared<EuropeanExercise>(d.referenceDate + 5 * 365));

    boost::shared_ptr<DiscountingEquityForwardEngine> lhFwdEngine =
        boost::make_shared<DiscountingEquityForwardEngine>(d.eurYts, d.eqDivLh, d.lhSpotToday, d.eurYts);
    boost::shared_ptr<DiscountingEquityForwardEngine> spFwdEngine =
        boost::make_shared<DiscountingEquityForwardEngine>(d.usdYts, d.eqDivSp, d.spSpotToday, d.usdYts);

    lhFwdTrade->setPricingEngine(lhFwdEngine);
    spFwdTrade->setPricingEngine(spFwdEngine);

    boost::shared_ptr<AnalyticXAssetLgmEquityOptionEngine> spEqOptionEngine =
        boost::make_shared<AnalyticXAssetLgmEquityOptionEngine>(
            d.ccLgm, d.eqSpIdx, d.ccLgm->ccyIndex(d.ccLgm->eqbs(d.eqSpIdx)->currency()));
    boost::shared_ptr<AnalyticXAssetLgmEquityOptionEngine> lhEqOptionEngine =
        boost::make_shared<AnalyticXAssetLgmEquityOptionEngine>(
            d.ccLgm, d.eqLhIdx, d.ccLgm->ccyIndex(d.ccLgm->eqbs(d.eqLhIdx)->currency()));

    lhCall->setPricingEngine(lhEqOptionEngine);
    lhPut->setPricingEngine(lhEqOptionEngine);
    spCall->setPricingEngine(spEqOptionEngine);
    spPut->setPricingEngine(spEqOptionEngine);

    Real npv1 = mean(stat1);
    Real error1 = error_of<tag::mean>(stat1);
    Real expected1 = lhFwdTrade->NPV();

    Real npv2 = mean(stat2);
    Real error2 = error_of<tag::mean>(stat2);
    Real expected2 = d.usdEurSpotToday->value() * spFwdTrade->NPV();

    Real npv3a = mean(stat3a);
    Real error3a = error_of<tag::mean>(stat3a);
    Real expected3a = lhCall->NPV();
    Real npv3b = mean(stat3b);
    Real error3b = error_of<tag::mean>(stat3b);
    Real expected3b = lhPut->NPV();

    Real npv4a = mean(stat4a);
    Real error4a = error_of<tag::mean>(stat4a);
    Real expected4a = d.usdEurSpotToday->value() * spCall->NPV();
    Real npv4b = mean(stat4b);
    Real error4b = error_of<tag::mean>(stat4b);
    Real expected4b = d.usdEurSpotToday->value() * spPut->NPV();

    Real tolErrEst = 1.5; // allow absolute diffs to be within 1.5 standard errors
    // TODO : IS THIS STRICT ENOUGH?
    BOOST_CHECK_LE(std::fabs(npv1 - expected1), tolErrEst * error1);
    BOOST_CHECK_LE(std::fabs(npv2 - expected2), tolErrEst * error2);
    BOOST_CHECK_LE(std::fabs(npv3a - expected3a), tolErrEst * error3a);
    BOOST_CHECK_LE(std::fabs(npv3b - expected3b), tolErrEst * error3b);
    BOOST_CHECK_LE(std::fabs(npv4a - expected4a), tolErrEst * error4a);
    BOOST_CHECK_LE(std::fabs(npv4b - expected4b), tolErrEst * error4b);

} // testEqLgm5fPayouts

void EquityCrossAssetModelTest::testLgm5fEqCalibration() {

    BOOST_TEST_MESSAGE("Testing EQ calibration of IR-FX-EQ LGM 5F model...");

    CrossAssetData d;
    Settings::instance().evaluationDate() = d.referenceDate;

    // calibration baskets
    std::vector<boost::shared_ptr<CalibrationHelper> > basketSp, basketLh;

    for (Size i = 0; i < d.volstepdatesEqSp.size(); ++i) {
        Date tmp = i < d.volstepdatesEqSp.size() ? d.volstepdatesEqSp[i] : d.volstepdatesEqSp.back() + 365;
        basketSp.push_back(boost::make_shared<FxEqOptionHelper>(
            tmp, Null<Real>(), d.spSpotToday, Handle<Quote>(boost::make_shared<SimpleQuote>(0.20)), d.usdYts, d.eqDivSp,
            CalibrationHelper::RelativePriceError));
    }
    for (Size i = 0; i < d.volstepdatesEqLh.size(); ++i) {
        Date tmp = i < d.volstepdatesEqLh.size() ? d.volstepdatesEqLh[i] : d.volstepdatesEqLh.back() + 365;
        basketLh.push_back(boost::make_shared<FxEqOptionHelper>(
            tmp, Null<Real>(), d.lhSpotToday, Handle<Quote>(boost::make_shared<SimpleQuote>(0.20)), d.eurYts, d.eqDivLh,
            CalibrationHelper::RelativePriceError));
    }

    // pricing engines
    boost::shared_ptr<AnalyticXAssetLgmEquityOptionEngine> spEqOptionEngine =
        boost::make_shared<AnalyticXAssetLgmEquityOptionEngine>(
            d.ccLgm, d.eqSpIdx, d.ccLgm->ccyIndex(d.ccLgm->eqbs(d.eqSpIdx)->currency()));
    boost::shared_ptr<AnalyticXAssetLgmEquityOptionEngine> lhEqOptionEngine =
        boost::make_shared<AnalyticXAssetLgmEquityOptionEngine>(
            d.ccLgm, d.eqLhIdx, d.ccLgm->ccyIndex(d.ccLgm->eqbs(d.eqLhIdx)->currency()));

    // assign engines to calibration instruments
    for (Size i = 0; i < basketSp.size(); ++i) {
        basketSp[i]->setPricingEngine(spEqOptionEngine);
    }
    for (Size i = 0; i < basketLh.size(); ++i) {
        basketLh[i]->setPricingEngine(lhEqOptionEngine);
    }

    // calibrate the model
    LevenbergMarquardt lm(1E-8, 1E-8, 1E-8);
    EndCriteria ec(1000, 500, 1E-8, 1E-8, 1E-8);

    d.ccLgm->calibrateBsVolatilitiesIterative(CrossAssetModelTypes::EQ, d.eqSpIdx, basketSp, lm, ec);
    d.ccLgm->calibrateBsVolatilitiesIterative(CrossAssetModelTypes::EQ, d.eqLhIdx, basketLh, lm, ec);

    // check the results
    Real tol = 1E-6;

    for (Size i = 0; i < basketSp.size(); ++i) {
        Real model = basketSp[i]->modelValue();
        Real market = basketSp[i]->marketValue();
        if (std::abs((model - market) / market) > tol)
            BOOST_ERROR("calibration failed for instrument #"
                        << i << " in SP basket, model value is " << model << " market value is " << market
                        << " relative error " << std::abs((model - market) / market) << " tolerance " << tol);
    }
    for (Size i = 0; i < basketLh.size(); ++i) {
        Real model = basketLh[i]->modelValue();
        Real market = basketLh[i]->marketValue();
        if (std::abs((model - market) / market) > tol)
            BOOST_ERROR("calibration failed for instrument #"
                        << i << " in LH basket, model value is " << model << " market value is " << market
                        << " relative error " << std::abs((model - market) / market) << " tolerance " << tol);
    }
}

void EquityCrossAssetModelTest::testLgm5fMoments() {

    // TODO : REVIEW TOLERANCES
    BOOST_TEST_MESSAGE("Testing analytic moments vs. Euler and exact discretization "
                       "in IR-FX-EQ LGM 5F model...");

    CrossAssetData d;
    Settings::instance().evaluationDate() = d.referenceDate;

    boost::shared_ptr<StochasticProcess> p_exact = d.ccLgm->stateProcess(CrossAssetStateProcess::exact);
    boost::shared_ptr<StochasticProcess> p_euler = d.ccLgm->stateProcess(CrossAssetStateProcess::euler);

    Real T = 10.0;                                  // horizon at which we compare the moments
    Size steps_euler = static_cast<Size>(T * 50.0); // number of simulation steps
    Size steps_exact = 1;
    Size paths = 25000; // number of paths

    Array e_an = p_exact->expectation(0.0, p_exact->initialValues(), T);
    Matrix v_an = p_exact->covariance(0.0, p_exact->initialValues(), T);
    Matrix v_an_eu = p_euler->covariance(0.0, p_euler->initialValues(), T);

    TimeGrid grid_euler(T, steps_euler);
    TimeGrid grid_exact(T, steps_exact);

    MultiPathGeneratorSobolBrownianBridge pgen(p_euler, grid_euler);
    MultiPathGeneratorSobolBrownianBridge pgen2(p_exact, grid_exact);

    accumulator_set<double, stats<tag::mean, tag::error_of<tag::mean> > > e_eu[5], e_eu2[5];
    accumulator_set<double, stats<tag::covariance<double, tag::covariate1> > > v_eu[5][5], v_eu2[5][5];

    for (Size i = 0; i < paths; ++i) {
        Sample<MultiPath> path = pgen.next();
        Sample<MultiPath> path2 = pgen2.next();
        for (Size ii = 0; ii < 5; ++ii) {
            Real cii = path.value[ii].back();
            Real cii2 = path2.value[ii].back();
            e_eu[ii](cii);
            e_eu2[ii](cii2);
            for (Size jj = 0; jj <= ii; ++jj) {
                Real cjj = path.value[jj].back();
                v_eu[ii][jj](cii, covariate1 = cjj);
                Real cjj2 = path2.value[jj].back();
                v_eu2[ii][jj](cii2, covariate1 = cjj2);
            }
        }
    }

    Real errTol[] = { 0.2E-4, 0.2E-4, 10.0E-4, 10.0E-4, 10.0E-4 };

    for (Size i = 0; i < 5; ++i) {
        // check expectation against analytical calculation (Euler)
        if (std::fabs(mean(e_eu[i]) - e_an[i]) > errTol[i]) {
            BOOST_ERROR("analytical expectation for component #"
                        << i << " (" << e_an[i] << ") is inconsistent with numerical value (Euler "
                                                   "discretization, " << mean(e_eu[i]) << "), error is "
                        << e_an[i] - mean(e_eu[i]) << " tolerance is " << errTol[i]);
        }
        // check expectation against analytical calculation (exact disc)
        if (std::fabs(mean(e_eu2[i]) - e_an[i]) > errTol[i]) {
            BOOST_ERROR("analytical expectation for component #"
                        << i << " (" << e_an[i] << ") is inconsistent with numerical value (Exact "
                                                   "discretization, " << mean(e_eu2[i]) << "), error is "
                        << e_an[i] - mean(e_eu2[i]) << " tolerance is " << errTol[i]);
        }
    }

    // we have to deal with different natures of volatility
    // for ir (normal) and fx (ln) so different error
    // tolerances apply
    Real tollNormal = 0.1E-4; // ir-ir
    Real tolMixed = 0.25E-4;  // ir-fx, ir-eq
    Real tolLn = 8.0E-4;      // fx-fx, fx-eq
    Real tolEq = 12.0E-4;     // eq-eq (to account for higher eq vols)
    Real tol;                 // set below

    for (Size i = 0; i < 5; ++i) {
        for (Size j = 0; j <= i; ++j) {
            if (i < 2) {
                tol = tollNormal;
            } else if ((i >= 3) && (j >= 3)) {
                tol = tolEq;
            } else {
                if (j < 2) {
                    tol = tolMixed;
                } else {
                    tol = tolLn;
                }
            }
            if (std::fabs(covariance(v_eu[i][j]) - v_an[i][j]) > tol) {
                BOOST_ERROR("analytical covariance at (" << i << "," << j << ") (" << v_an[i][j]
                                                         << ") is inconsistent with numerical "
                                                            "value (Euler discretization, " << covariance(v_eu[i][j])
                                                         << "), error is " << v_an[i][j] - covariance(v_eu[i][j])
                                                         << " tolerance is " << tol);
            }
            if (std::fabs(covariance(v_eu2[i][j]) - v_an[i][j]) > tol) {
                BOOST_ERROR("analytical covariance at (" << i << "," << j << ") (" << v_an[i][j]
                                                         << ") is inconsistent with numerical "
                                                            "value (Exact discretization, " << covariance(v_eu2[i][j])
                                                         << "), error is " << v_an[i][j] - covariance(v_eu2[i][j])
                                                         << " tolerance is " << tol);
            }
        }
    }

    BOOST_TEST_MESSAGE("Testing correlation matrix recovery in presence of equity simulation");
    Matrix corr_input = d.ccLgm->correlation();
    BOOST_CHECK(corr_input.rows() == corr_input.columns());
    Size dim = corr_input.rows();
    BOOST_CHECK(corr_input.rows() == 5);
    Matrix r1(dim, dim), r2(dim, dim);
    Real dt = 1.0E-6;
    Real tol_corr = 1.0E-7;
    Matrix v_an_dt = p_exact->covariance(0.0, p_exact->initialValues(), dt);
    Matrix v_an_eu_dt = p_euler->covariance(0.0, p_euler->initialValues(), dt);
    BOOST_CHECK(v_an_dt.rows() == v_an_eu_dt.rows());
    BOOST_CHECK(v_an_dt.columns() == v_an_eu_dt.columns());
    BOOST_CHECK(corr_input.rows() == v_an_dt.rows());
    BOOST_CHECK(corr_input.columns() == corr_input.columns());

    for (Size i = 0; i < dim; ++i) {
        for (Size j = 0; j <= i; ++j) {
            r1[i][j] = r1[j][i] = v_an_dt[i][j] / std::sqrt(v_an_dt[i][i] * v_an_dt[j][j]);
            r2[i][j] = r2[j][i] = v_an_eu_dt[i][j] / std::sqrt(v_an_eu_dt[i][i] * v_an_eu_dt[j][j]);
            BOOST_CHECK_MESSAGE(std::fabs(r1[i][j] - corr_input[i][j]) < tol_corr,
                                "failed to recover correlation matrix from "
                                "exact state process (i,j)=("
                                    << i << "," << j << "), input correlation is " << corr_input[i][j] << ", output is "
                                    << r1[i][j] << ", difference " << (corr_input[i][j] - r1[i][j]) << ", tolerance "
                                    << tol_corr);
            BOOST_CHECK_MESSAGE(std::fabs(r2[i][j] - corr_input[i][j]) < tol_corr,
                                "failed to recover correlation matrix from "
                                "Euler state process (i,j)=("
                                    << i << "," << j << "), input correlation is " << corr_input[i][j] << ", output is "
                                    << r2[i][j] << ", difference " << (corr_input[i][j] - r2[i][j]) << ", tolerance "
                                    << tol_corr);
        }
    }
    /*
    for (Size i = 0; i < 5; ++i) {
        Real meu = mean(e_eu[i]);
        Real s_meu = error_of<tag::mean>(e_eu[i]);
        BOOST_TEST_MESSAGE(i << ";EULER;" << e_an[i] << ";" << meu << ";" << s_meu);
        Real meu2 = mean(e_eu2[i]);
        Real s_meu2 = error_of<tag::mean>(e_eu2[i]);
        BOOST_TEST_MESSAGE(i << ";EXACT;" << e_an[i] << ";" << meu2 << ";" << s_meu2);
    }
    for (Size i = 0; i < 5; ++i) {
        for (Size j = 0; j <= i; ++j) {
            Real cov = covariance(v_eu[i][j]);
            BOOST_TEST_MESSAGE(i << ";" << j << ";" << "EULER;" << v_an[i][j] << ";" << cov);
            Real cov2 = covariance(v_eu2[i][j]);
            BOOST_TEST_MESSAGE(i << ";" << j << ";" << "EXACT;" << v_an[i][j] << ";" << cov2);
        }
    }
    */
} // testLgm5fMoments

test_suite* EquityCrossAssetModelTest::suite() {
    test_suite* suite = BOOST_TEST_SUITE("EquityCrossAssetModelTests");
    suite->add(QUANTLIB_TEST_CASE(&EquityCrossAssetModelTest::testEqLgm5fPayouts));
    suite->add(QUANTLIB_TEST_CASE(&EquityCrossAssetModelTest::testLgm5fEqCalibration));
    suite->add(QUANTLIB_TEST_CASE(&EquityCrossAssetModelTest::testLgm5fMoments));
    return suite;
}
}

max_stars_repo_name: mrslezak/Engine

max_issues_repo_name: mrslezak/Engine

max_forks_repo_name: mrslezak/Engine


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file    testNonlinearOptimizer.cpp
 * @brief   Unit tests for NonlinearOptimizer class
 * @author  Frank Dellaert
 */

#include <tests/smallExample.h>
#include <gtsam/slam/PriorFactor.h>
#include <gtsam/slam/BetweenFactor.h>
#include <gtsam/nonlinear/NonlinearFactorGraph.h>
#include <gtsam/nonlinear/Values.h>
#include <gtsam/nonlinear/Symbol.h>
#include <gtsam/nonlinear/NonlinearFactorGraph.h>
#include <gtsam/nonlinear/GaussNewtonOptimizer.h>
#include <gtsam/nonlinear/DoglegOptimizer.h>
#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
#include <gtsam/linear/GaussianFactorGraph.h>
#include <gtsam/linear/NoiseModel.h>
#include <gtsam/geometry/Pose2.h>
#include <gtsam/base/Matrix.h>

#include <CppUnitLite/TestHarness.h>

#include <boost/shared_ptr.hpp>
#include <boost/assign/std/list.hpp> // for operator +=
using namespace boost::assign;

#include <iostream>

using namespace std;
using namespace gtsam;

const double tol = 1e-5;

using symbol_shorthand::X;
using symbol_shorthand::L;

/* ************************************************************************* */
TEST( NonlinearOptimizer, iterateLM )
{
	// really non-linear factor graph
  example::Graph fg(example::createReallyNonlinearFactorGraph());

	// config far from minimum
	Point2 x0(3,0);
	Values config;
	config.insert(X(1), x0);

	// normal iterate
	GaussNewtonParams gnParams;
	GaussNewtonOptimizer gnOptimizer(fg, config, gnParams);
	gnOptimizer.iterate();

	// LM iterate with lambda 0 should be the same
	LevenbergMarquardtParams lmParams;
	lmParams.lambdaInitial = 0.0;
	LevenbergMarquardtOptimizer lmOptimizer(fg, config, lmParams);
	lmOptimizer.iterate();

	CHECK(assert_equal(gnOptimizer.values(), lmOptimizer.values(), 1e-9));
}

/* ************************************************************************* */
TEST( NonlinearOptimizer, optimize )
{
  example::Graph fg(example::createReallyNonlinearFactorGraph());

	// test error at minimum
	Point2 xstar(0,0);
	Values cstar;
	cstar.insert(X(1), xstar);
	DOUBLES_EQUAL(0.0,fg.error(cstar),0.0);

	// test error at initial = [(1-cos(3))^2 + (sin(3))^2]*50 =
	Point2 x0(3,3);
	Values c0;
	c0.insert(X(1), x0);
	DOUBLES_EQUAL(199.0,fg.error(c0),1e-3);

	// optimize parameters
	Ordering ord;
	ord.push_back(X(1));

	// Gauss-Newton
	GaussNewtonParams gnParams;
	gnParams.ordering = ord;
	Values actual1 = GaussNewtonOptimizer(fg, c0, gnParams).optimize();
	DOUBLES_EQUAL(0,fg.error(actual1),tol);

	// Levenberg-Marquardt
	LevenbergMarquardtParams lmParams;
	lmParams.ordering = ord;
  Values actual2 = LevenbergMarquardtOptimizer(fg, c0, lmParams).optimize();
  DOUBLES_EQUAL(0,fg.error(actual2),tol);

  // Dogleg
  DoglegParams dlParams;
  dlParams.ordering = ord;
  Values actual3 = DoglegOptimizer(fg, c0, dlParams).optimize();
  DOUBLES_EQUAL(0,fg.error(actual3),tol);
}

/* ************************************************************************* */
TEST( NonlinearOptimizer, SimpleLMOptimizer )
{
	example::Graph fg(example::createReallyNonlinearFactorGraph());

	Point2 x0(3,3);
	Values c0;
	c0.insert(X(1), x0);

	Values actual = LevenbergMarquardtOptimizer(fg, c0).optimize();
	DOUBLES_EQUAL(0,fg.error(actual),tol);
}

/* ************************************************************************* */
TEST( NonlinearOptimizer, SimpleGNOptimizer )
{
  example::Graph fg(example::createReallyNonlinearFactorGraph());

  Point2 x0(3,3);
  Values c0;
  c0.insert(X(1), x0);

  Values actual = GaussNewtonOptimizer(fg, c0).optimize();
	DOUBLES_EQUAL(0,fg.error(actual),tol);
}

/* ************************************************************************* */
TEST( NonlinearOptimizer, SimpleDLOptimizer )
{
  example::Graph fg(example::createReallyNonlinearFactorGraph());

  Point2 x0(3,3);
  Values c0;
  c0.insert(X(1), x0);

  Values actual = DoglegOptimizer(fg, c0).optimize();
  DOUBLES_EQUAL(0,fg.error(actual),tol);
}

/* ************************************************************************* */
TEST( NonlinearOptimizer, optimization_method )
{
  LevenbergMarquardtParams paramsQR;
  paramsQR.linearSolverType = LevenbergMarquardtParams::MULTIFRONTAL_QR;
  LevenbergMarquardtParams paramsChol;
  paramsChol.linearSolverType = LevenbergMarquardtParams::MULTIFRONTAL_CHOLESKY;

	example::Graph fg = example::createReallyNonlinearFactorGraph();

	Point2 x0(3,3);
	Values c0;
	c0.insert(X(1), x0);

	Values actualMFQR = LevenbergMarquardtOptimizer(fg, c0, paramsQR).optimize();
	DOUBLES_EQUAL(0,fg.error(actualMFQR),tol);

  Values actualMFChol = LevenbergMarquardtOptimizer(fg, c0, paramsChol).optimize();
  DOUBLES_EQUAL(0,fg.error(actualMFChol),tol);
}

/* ************************************************************************* */
TEST( NonlinearOptimizer, Factorization )
{
	Values config;
	config.insert(X(1), Pose2(0.,0.,0.));
	config.insert(X(2), Pose2(1.5,0.,0.));

	NonlinearFactorGraph graph;
	graph.add(PriorFactor<Pose2>(X(1), Pose2(0.,0.,0.), noiseModel::Isotropic::Sigma(3, 1e-10)));
	graph.add(BetweenFactor<Pose2>(X(1),X(2), Pose2(1.,0.,0.), noiseModel::Isotropic::Sigma(3, 1)));

	Ordering ordering;
	ordering.push_back(X(1));
	ordering.push_back(X(2));

	LevenbergMarquardtOptimizer optimizer(graph, config, ordering);
	optimizer.iterate();

	Values expected;
	expected.insert(X(1), Pose2(0.,0.,0.));
	expected.insert(X(2), Pose2(1.,0.,0.));
	CHECK(assert_equal(expected, optimizer.values(), 1e-5));
}

/* ************************************************************************* */
TEST(NonlinearOptimizer, NullFactor) {

  example::Graph fg = example::createReallyNonlinearFactorGraph();

  // Add null factor
  fg.push_back(example::Graph::sharedFactor());

  // test error at minimum
  Point2 xstar(0,0);
  Values cstar;
  cstar.insert(X(1), xstar);
  DOUBLES_EQUAL(0.0,fg.error(cstar),0.0);

  // test error at initial = [(1-cos(3))^2 + (sin(3))^2]*50 =
  Point2 x0(3,3);
  Values c0;
  c0.insert(X(1), x0);
  DOUBLES_EQUAL(199.0,fg.error(c0),1e-3);

  // optimize parameters
  Ordering ord;
  ord.push_back(X(1));

  // Gauss-Newton
  Values actual1 = GaussNewtonOptimizer(fg, c0, ord).optimize();
  DOUBLES_EQUAL(0,fg.error(actual1),tol);

  // Levenberg-Marquardt
  Values actual2 = LevenbergMarquardtOptimizer(fg, c0, ord).optimize();
  DOUBLES_EQUAL(0,fg.error(actual2),tol);

  // Dogleg
  Values actual3 = DoglegOptimizer(fg, c0, ord).optimize();
  DOUBLES_EQUAL(0,fg.error(actual3),tol);
}

/* ************************************************************************* */
TEST(NonlinearOptimizer, MoreOptimization) {

  NonlinearFactorGraph fg;
  fg.add(PriorFactor<Pose2>(0, Pose2(0,0,0), noiseModel::Isotropic::Sigma(3,1)));
  fg.add(BetweenFactor<Pose2>(0, 1, Pose2(1,0,M_PI/2), noiseModel::Isotropic::Sigma(3,1)));
  fg.add(BetweenFactor<Pose2>(1, 2, Pose2(1,0,M_PI/2), noiseModel::Isotropic::Sigma(3,1)));

  Values init;
  init.insert(0, Pose2(3,4,-M_PI));
  init.insert(1, Pose2(10,2,-M_PI));
  init.insert(2, Pose2(11,7,-M_PI));

  Values expected;
  expected.insert(0, Pose2(0,0,0));
  expected.insert(1, Pose2(1,0,M_PI/2));
  expected.insert(2, Pose2(1,1,M_PI));

  // Try LM and Dogleg
  EXPECT(assert_equal(expected, LevenbergMarquardtOptimizer(fg, init).optimize()));
  EXPECT(assert_equal(expected, DoglegOptimizer(fg, init).optimize()));
}

/* ************************************************************************* */
int main() {
	TestResult tr;
	return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */

ext: cpp


text:
//
// Created by Alex Beccaro on 18/01/18.
//

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "../../src/problems/51-100/67/problem67.hpp"

BOOST_AUTO_TEST_SUITE( Problem67 )

    BOOST_AUTO_TEST_CASE( Solution ) {
        auto res = problems::problem67::solve();
        BOOST_CHECK_EQUAL(res, 7273);
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: abeccaro/project-euler

max_issues_repo_name: abeccaro/project-euler

max_forks_repo_name: abeccaro/project-euler


text:
#if !defined(TCC_PARSER_QI_AST_HPP)
#define TCC_PARSER_QI_AST_HPP

#include <boost/config/warning_disable.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/optional.hpp>
#include <boost/variant/recursive_variant.hpp>

#include <utility>
#include <vector>

namespace tcc
{
namespace ast
{

/**
 * @brief Used to annotate the AST with the iterator position.
 * This id is used as a key to a map<int, Iterator>.
 * Not really part of the AST.
 */
struct Tagged
{
    int id {};
};

/**
 * @brief Placeholder for nothing.
 */
struct Nil
{
};

struct Unary;

struct FunctionCall;

struct Expression;

/**
 * @brief Identifier.
 */
struct Identifier : Tagged
{
    // NOLINTNEXTLINE(hicpp-explicit-conversions)
    Identifier(std::string n = "") : name(std::move(n)) { }
    std::string name;
};

/**
 * @brief Operand.
 */
using Operand = boost::variant<              //
    Nil,                                     //
    bool,                                    //
    unsigned int,                            //
    Identifier,                              //
    boost::recursive_wrapper<Unary>,         //
    boost::recursive_wrapper<FunctionCall>,  //
    boost::recursive_wrapper<Expression>     //
    >;

/**
 * @brief Operation Token.
 */
enum class OpToken
{
    Invalid,
    Plus,
    Minus,
    Times,
    Divide,
    Positive,
    Negative,
    Not,
    Equal,
    NotEqual,
    Less,
    LessEqual,
    Greater,
    GreaterEqual,
    And,
    Or
};

/**
 * @brief Unary Expression.
 */
struct Unary
{
    OpToken Operator {OpToken::Invalid};
    Operand operand;
};

/**
 * @brief Operation.
 */
struct Operation
{
    OpToken Operator {OpToken::Invalid};
    Operand operand;
};

/**
 * @brief Function call.
 */
struct FunctionCall
{
    Identifier funcName;
    std::vector<Expression> args;
};

/**
 * @brief Expression.
 */
struct Expression
{
    Operand first;
    std::vector<Operation> rest;
};

/**
 * @brief Assignment.
 */
struct Assignment
{
    Identifier left;
    Expression right;
};

/**
 * @brief Variable Declaration.
 */
struct VariableDeclaration
{
    Identifier left;
    boost::optional<Expression> right;
};

struct IfStatement;
struct WhileStatement;
struct StatementList;
struct ReturnStatement;

/**
 * @brief Statement.
 */
using Statement = boost::variant<               //
    VariableDeclaration,                        //
    Assignment,                                 //
    boost::recursive_wrapper<IfStatement>,      //
    boost::recursive_wrapper<WhileStatement>,   //
    boost::recursive_wrapper<ReturnStatement>,  //
    boost::recursive_wrapper<StatementList>     //
    >;

/**
 * @brief Statement list.
 */
struct StatementList : std::vector<Statement>
{
};

/**
 * @brief If statement.
 */
struct IfStatement
{
    Expression condition;
    Statement then;
    boost::optional<Statement> Else;
};

/**
 * @brief While statement.
 */
struct WhileStatement
{
    Expression condition;
    Statement body;
};

/**
 * @brief Return statement.
 */
struct ReturnStatement : Tagged
{
    boost::optional<Expression> expr;
};

/**
 * @brief Function.
 */
struct Function
{
    std::string returnType;
    Identifier funcName;
    std::vector<Identifier> args;
    StatementList body;
};

/**
 * @brief Function list.
 */
using FunctionList = std::vector<Function>;

/**
 * @brief Nil ostream operator.
 */
inline auto operator<<(std::ostream& out, Nil /*unused*/) -> std::ostream&
{
    out << "Nil";
    return out;
}

/**
 * @brief Identifier ostream operator.
 */
inline auto operator<<(std::ostream& out, Identifier const& id) -> std::ostream&
{
    out << id.name;
    return out;
}
}  // namespace ast
}  // namespace tcc

// NOLINTNEXTLINE(modernize-use-trailing-return-type)
BOOST_FUSION_ADAPT_STRUCT(         //
    tcc::ast::Unary,               //
    (tcc::ast::OpToken, Operator)  //
    (tcc::ast::Operand, operand)   //
)

// NOLINTNEXTLINE(modernize-use-trailing-return-type)
BOOST_FUSION_ADAPT_STRUCT(         //
    tcc::ast::Operation,           //
    (tcc::ast::OpToken, Operator)  //
    (tcc::ast::Operand, operand)   //
)

// NOLINTNEXTLINE(modernize-use-trailing-return-type)
BOOST_FUSION_ADAPT_STRUCT(                     //
    tcc::ast::FunctionCall,                    //
    (tcc::ast::Identifier, funcName)           //
    (std::vector<tcc::ast::Expression>, args)  //
)

// NOLINTNEXTLINE(modernize-use-trailing-return-type)
BOOST_FUSION_ADAPT_STRUCT(                    //
    tcc::ast::Expression,                     //
    (tcc::ast::Operand, first)                //
    (std::vector<tcc::ast::Operation>, rest)  //
)

// NOLINTNEXTLINE(modernize-use-trailing-return-type)
BOOST_FUSION_ADAPT_STRUCT(                          //
    tcc::ast::VariableDeclaration,                  //
    (tcc::ast::Identifier, left)                    //
    (boost::optional<tcc::ast::Expression>, right)  //
)

// NOLINTNEXTLINE(modernize-use-trailing-return-type)
BOOST_FUSION_ADAPT_STRUCT(         //
    tcc::ast::Assignment,          //
    (tcc::ast::Identifier, left)   //
    (tcc::ast::Expression, right)  //
)

// NOLINTNEXTLINE(modernize-use-trailing-return-type)
BOOST_FUSION_ADAPT_STRUCT(                        //
    tcc::ast::IfStatement,                        //
    (tcc::ast::Expression, condition)             //
    (tcc::ast::Statement, then)                   //
    (boost::optional<tcc::ast::Statement>, Else)  //
)

// NOLINTNEXTLINE(modernize-use-trailing-return-type)
BOOST_FUSION_ADAPT_STRUCT(             //
    tcc::ast::WhileStatement,          //
    (tcc::ast::Expression, condition)  //
    (tcc::ast::Statement, body)        //
)

// NOLINTNEXTLINE(modernize-use-trailing-return-type)
BOOST_FUSION_ADAPT_STRUCT(                         //
    tcc::ast::ReturnStatement,                     //
    (boost::optional<tcc::ast::Expression>, expr)  //
)

// NOLINTNEXTLINE(modernize-use-trailing-return-type)
BOOST_FUSION_ADAPT_STRUCT(                     //
    tcc::ast::Function,                        //
    (std::string, returnType)                  //
    (tcc::ast::Identifier, funcName)           //
    (std::vector<tcc::ast::Identifier>, args)  //
    (tcc::ast::StatementList, body)            //
)

#endif

ext: hpp

max_stars_repo_name: tobiashienzsch/tcc

max_issues_repo_name: tobiashienzsch/tcc

max_forks_repo_name: tobiashienzsch/tcc


text:
#include "DataChunk.pb.h"
#include "MessageReader.h"
#include "MessageDispatcher.h"
#include "Socket.h"
#include <exception>
#include <iostream>
#include <boost/asio.hpp>
#include <google/protobuf/message.h>
#include <boost/typeof/typeof.hpp>
#include <sstream>

using namespace tpool;
using namespace std;
using boost::asio::ip::tcp;
using boost::shared_ptr;
using google::protobuf::Message;

Message* HandleSimpleDataChunkRequest(simple::GetSimpleDataChunkRequest* request)
{
  using simple::GetSimpleDataChunkRequest;
  using simple::SimpleDataChunkResponse;

  cout << "In HandleSimpleDataChunkRequest" << endl;

  const int responseNum = request->num();
  cout << "responseNum: " << responseNum << endl;

  SimpleDataChunkResponse* response = new SimpleDataChunkResponse;
  for (int i = 0; i < responseNum; ++i)
    {
      BOOST_AUTO(chunk, response->add_chunks());
      chunk->set_x((double) i);
      chunk->set_y((double) i);
    }

  ostringstream oss;
  response->SerializeToOstream(&oss);
  cout << "response length: " << oss.str().length() << endl;

  return response;
}

int main(int argc, char** argv)
{
  const unsigned int SERVER_PORT = 29995;

  try
    {
      boost::asio::io_service io_service;
      tcp::acceptor acceptor(io_service,
			     tcp::endpoint(tcp::v4(), SERVER_PORT));
      cout << "Server starts listening port " << SERVER_PORT << endl;

      Socket socket(boost::shared_ptr<tcp::socket>(new tcp::socket(io_service)));
      acceptor.accept(*(socket.GetImpl()));

      MessageDispatcher::GetInstance().SetSocket(socket);
      MessageDispatcher::GetInstance().
	SetMessageHandler<simple::GetSimpleDataChunkRequest>
	(boost::bind(&HandleSimpleDataChunkRequest, _1));

      MessageReader reader(socket);
      reader.Loop();
    }
  catch (std::exception& e)
    {
      cerr << e.what() << endl;
    }

  return 0;
}

max_stars_repo_name: airekans/Tpool

max_issues_repo_name: guker/Tpool

max_forks_repo_name: guker/Tpool


text:
#include <fiberchain/app/plugin.hpp>
#include <fiberchain/chain/fiberchain_object_types.hpp>

#include <boost/multi_index/composite_key.hpp>

namespace fiberchain{ namespace tags{

using namespace fiberchain::chain;
using namespace boost::multi_index;

using fiberchain::app::application;
using chainbase::object;
using chainbase::oid;
using chainbase::allocator;

typedef protocol::fixed_string_32 tag_name_type;

// Plugins need to define object type IDs such that they do not conflict
// globally. If each plugin uses the upper 8 bits as a space identifier,
// with 0 being for chain, then the lower 8 bits are free for each plugin
// to define as they see fit.
enum
{
   tag_object_type         = ( TAG_SPACE_ID << 8 ),
   comment_tag_type        = ( TAG_SPACE_ID << 8 ) + 1

};

class tag_object : public object< tag_object_type, tag_object >
{
   public:
      template< typename Constructor, typename Allocator >
      tag_object( Constructor&& c, allocator< Allocator > a )
      {
         c( *this );
      }

      tag_object() {}

      id_type           id;
      tag_name_type     tag;
      time_point_sec    created;
      int64_t           used_count;
};

typedef oid< tag_object > tag_id_type;

/**
 *  The purpose of the tag object is to allow the generation and listing of
 *  all top level posts by a string tag.  The desired sort orders include:
 *
 *  1. created - time of creation
 *  2. active - last reply the post or any child of the post
 *
 *  When ever a comment is modified, all tag_objects for that comment are updated to match.
 */
class comment_tag_object : public object< comment_tag_type, comment_tag_object >
{
   public:
      template< typename Constructor, typename Allocator >
      comment_tag_object( Constructor&& c, allocator< Allocator > a )
      {
         c( *this );
      }

      comment_tag_object() {}

      id_type           id;

      comment_id_type   comment;
      tag_id_type       tag;

      time_point_sec    created;
      time_point_sec    active;
      int32_t           children    = 0;
      account_id_type   author;
      comment_id_type   parent;
};

typedef oid< comment_tag_object > comment_tag_id_type;

struct by_tag_name;
struct by_tag_created;

typedef multi_index_container <
   tag_object,
   indexed_by <
      ordered_unique< tag< by_id >,
         member< tag_object, tag_id_type, &tag_object::id >
      >,
      ordered_unique< tag< by_tag_name >,
         composite_key< tag_object,
            member< tag_object, tag_name_type, &tag_object::tag >,
            member< tag_object, tag_id_type, &tag_object::id >
         >,
         composite_key_compare<
            std::less< tag_name_type >,
            std::less< tag_id_type >
         >
      >,
      ordered_unique< tag< by_tag_created >,
         composite_key< tag_object,
            member< tag_object, time_point_sec, &tag_object::created >,
            member< tag_object, tag_id_type, &tag_object::id >
         >,
         composite_key_compare<
            std::greater< time_point_sec >,
            std::less< tag_id_type >
         >
      >
   >,
   allocator< tag_object >
> tag_index;

struct by_parent_created;
struct by_parent_active;
struct by_parent_children; /// all top level posts with the most discussion (replies at all levels)
struct by_author_parent_created;  /// all blog posts by author with tag
struct by_author_comment;
struct by_comment;
struct by_tag;

typedef multi_index_container<
   comment_tag_object,
   indexed_by<
      ordered_unique< tag< by_id >, member< comment_tag_object, comment_tag_id_type, &comment_tag_object::id > >,
      ordered_unique< tag< by_comment >,
         composite_key< comment_tag_object,
            member< comment_tag_object, comment_id_type, &comment_tag_object::comment >,
            member< comment_tag_object, comment_tag_id_type, &comment_tag_object::id >
         >,
         composite_key_compare<
            std::less< comment_id_type >,
            std::less< comment_tag_id_type >
         >
      >,
      ordered_unique< tag< by_tag >,
         composite_key< comment_tag_object,
            member< comment_tag_object, tag_id_type, &comment_tag_object::tag >,
            member< comment_tag_object, comment_tag_id_type, &comment_tag_object::id >
         >,
         composite_key_compare<
            std::less< tag_id_type >,
            std::less< comment_tag_id_type >
         >
      >,
      ordered_unique< tag< by_author_comment >,
            composite_key< comment_tag_object,
               member< comment_tag_object, account_id_type, &comment_tag_object::author >,
               member< comment_tag_object, comment_id_type, &comment_tag_object::comment >,
               member< comment_tag_object, comment_tag_id_type, &comment_tag_object::id >
            >,
            composite_key_compare<
               std::less< account_id_type >,
               std::less< comment_id_type >,
               std::less< comment_tag_id_type >
            >
      >,
      ordered_unique< tag< by_parent_created >,
            composite_key< comment_tag_object,
               member< comment_tag_object, tag_id_type, &comment_tag_object::tag >,
               member< comment_tag_object, comment_id_type, &comment_tag_object::parent >,
               member< comment_tag_object, time_point_sec, &comment_tag_object::created >,
               member< comment_tag_object, comment_tag_id_type, &comment_tag_object::id >
            >,
            composite_key_compare<
               std::less< tag_id_type >,
               std::less< comment_id_type >,
               std::greater< time_point_sec >,
               std::less< comment_tag_id_type >
            >
      >,
      ordered_unique< tag< by_parent_active >,
            composite_key< comment_tag_object,
               member< comment_tag_object, tag_id_type, &comment_tag_object::tag >,
               member< comment_tag_object, comment_id_type, &comment_tag_object::parent >,
               member< comment_tag_object, time_point_sec, &comment_tag_object::active >,
               member< comment_tag_object, comment_tag_id_type, &comment_tag_object::id >
            >,
            composite_key_compare<
               std::less< tag_id_type >,
               std::less< comment_id_type >,
               std::greater< time_point_sec >,
               std::less< comment_tag_id_type >
            >
      >,
      ordered_unique< tag< by_parent_children >,
            composite_key< comment_tag_object,
               member< comment_tag_object, tag_id_type, &comment_tag_object::tag >,
               member< comment_tag_object, comment_id_type, &comment_tag_object::parent >,
               member< comment_tag_object, int32_t, &comment_tag_object::children >,
               member< comment_tag_object, comment_tag_id_type, &comment_tag_object::id >
            >,
            composite_key_compare<
               std::less< tag_id_type >,
               std::less< comment_id_type >,
               std::greater< int32_t >,
               std::less< comment_tag_id_type >
            >
      >,
      ordered_unique< tag< by_author_parent_created >,
            composite_key< comment_tag_object,
               member< comment_tag_object, tag_id_type, &comment_tag_object::tag >,
               member< comment_tag_object, account_id_type, &comment_tag_object::author >,
               member< comment_tag_object, time_point_sec, &comment_tag_object::created >,
               member< comment_tag_object, comment_tag_id_type, &comment_tag_object::id >
            >,
            composite_key_compare<
               std::less< tag_id_type >,
               std::less< account_id_type >,
               std::greater< time_point_sec >,
               std::less< comment_tag_id_type >
            >
      >
   >,
   allocator< comment_tag_object >
> comment_tag_index;

/**
 * Used to parse the metadata from the comment json_meta field.
 */
struct comment_metadata { set< string > tags; };

} } // namespace fiberchain::tags

FC_REFLECT( fiberchain::tags::tag_object,
   ( id )
   ( tag )
   ( created )
   ( used_count )
)
CHAINBASE_SET_INDEX_TYPE( fiberchain::tags::tag_object, fiberchain::tags::tag_index )

FC_REFLECT( fiberchain::tags::comment_tag_object,
   ( id )
   ( tag )
   ( created )
   ( active )
   ( children )
   ( author )
   ( parent )
   ( comment )
)
CHAINBASE_SET_INDEX_TYPE( fiberchain::tags::comment_tag_object, fiberchain::tags::comment_tag_index )

FC_REFLECT( fiberchain::tags::comment_metadata, ( tags ) )

max_stars_repo_name: FiberChain/FiberChain

max_issues_repo_name: FiberChain/FiberChain

max_forks_repo_name: FiberChain/FiberChain


text: #include <boost/variant/visitor_ptr.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#ifndef COROUTINE_HH
#define COROUTINE_HH

#include "config.h"

#include <boost/version.hpp>

#ifdef HAVE_BOOST_COROUTINE
#    if (BOOST_VERSION >= 106200)
#        include <atomic>
#        include <boost/coroutine2/all.hpp>
         namespace graph_tool
         {
             namespace coroutines = boost::coroutines2;
         }

         template <class Coro, class Dispatch>
         auto make_coro(Dispatch&& dispatch)
         {
             return std::make_shared<Coro>
                 (graph_tool::coroutines::fixedsize_stack(BOOST_COROUTINE_STACK_SIZE),
                  dispatch);
         }
#    else
#        include <boost/coroutine/all.hpp>
         namespace graph_tool
         {
             namespace coroutines = boost::coroutines;
         }

         template <class Coro, class Dispatch>
         auto make_coro(Dispatch&& dispatch)
         {
             return std::make_shared<Coro>
                 (dispatch,
                  graph_tool::coroutines::attributes(BOOST_COROUTINE_STACK_SIZE));
         }
#    endif

#endif // HAVE_BOOST_COROUTINE

#endif // COROUTINE_HH

ext: hh


text:
#include <boost/lambda/lambda.hpp>
#include "stdhdrs.h"

#include "PCList.h"
#include "Descriptor.h"
#include "WarCastle.h"
#include "Zone.h"
#include "CmdMsg.h"

PCManager* PCManager::instance()
{
	static PCManager __instance;
	return &__instance;
}

void PCManager::addPlayer(CPC* pPlayer)
{
	PlayerInfo playInfo;
	playInfo.userIndex		= pPlayer->m_desc->m_index;
	playInfo.charIndex		= pPlayer->m_index;
	playInfo.charName		= pPlayer->m_name;
	playInfo.charNickName	= pPlayer->m_nick;
	playInfo.pPlayer		= pPlayer;

	playerMap_.insert(playInfo);

	LOG_INFO("Player Add Data : userIndex[%d], charIndex[%d] charName[%s]",
			 playInfo.userIndex, playInfo.charIndex, playInfo.charName.c_str());
}

CPC* PCManager::getPlayerByUserIndex(int userIndex)
{
	map_t::index<Key_User_Index>::type& p = playerMap_.get<Key_User_Index>();
	map_t::index<Key_User_Index>::type::iterator it = p.find(userIndex);
	if (it == p.end())
		return NULL;

	if (it->pPlayer->m_bPlaying == false)
		return NULL;

	return (*it).pPlayer;
}

CPC* PCManager::getPlayerByCharIndex(int charIndex)
{
	map_t::index<Key_Char_Index>::type& p = playerMap_.get<Key_Char_Index>();
	map_t::index<Key_Char_Index>::type::iterator it = p.find(charIndex);
	if (it == p.end())
		return NULL;

	if (it->pPlayer->m_bPlaying == false)
		return NULL;

	return (*it).pPlayer;
}

CPC* PCManager::getPlayerByName(const char* name, bool isNickName)
{
	CPC * pc = NULL;

	pc = getPlayerByCharNickName(name);
	if (pc == NULL)
	{
		pc = getPlayerByCharName(name);
	}
	return pc;
}

CPC* PCManager::getPlayerByCharName(const char* charName)
{
	map_t::index<Key_Char_Name>::type& p = playerMap_.get<Key_Char_Name>();
	map_t::index<Key_Char_Name>::type::iterator it = p.find(charName);
	if (it == p.end())
		return NULL;

	if (it->pPlayer->m_bPlaying == false)
		return NULL;

	return (*it).pPlayer;
}

CPC* PCManager::getPlayerByCharNickName(const char* charName)
{
	map_t::index<Key_Char_Nick_Name>::type& p = playerMap_.get<Key_Char_Nick_Name>();
	map_t::index<Key_Char_Nick_Name>::type::iterator it = p.find(charName);
	if (it == p.end())
		return NULL;

	if (it->pPlayer->m_bPlaying == false)
		return NULL;

	return (*it).pPlayer;
}

void PCManager::deletePlayerByPC(CPC* pc)
{
	if (pc == NULL)
		return;

	deletePlayerByCharIndex(pc->m_index);
}

void PCManager::deletePlayerByUserIndex(int userIndex)
{
	map_t::index<Key_User_Index>::type& p = playerMap_.get<Key_User_Index>();
	map_t::index<Key_User_Index>::type::iterator it = p.find(userIndex);
	p.erase(userIndex);
}

void PCManager::deletePlayerByCharIndex(int charIndex)
{
	map_t::index<Key_Char_Index>::type& p = playerMap_.get<Key_Char_Index>();
	map_t::index<Key_Char_Index>::type::iterator it = p.find(charIndex);
	p.erase(charIndex);
}

void PCManager::deletePlayerByCharName(const char* charName)
{
	map_t::index<Key_Char_Name>::type& p = playerMap_.get<Key_Char_Name>();
	map_t::index<Key_Char_Name>::type::iterator it = p.find(charName);
	p.erase(charName);
}

void PCManager::deletePlayerByCharNickName(const char* charName)
{
	map_t::index<Key_Char_Nick_Name>::type& p = playerMap_.get<Key_Char_Nick_Name>();
	map_t::index<Key_Char_Nick_Name>::type::iterator it = p.find(charName);
	p.erase(charName);
}

bool PCManager::isPlaying(CPC *ch)
{
	if (ch == NULL || ch->m_name[0] == '\0')
	{
		return false;
	}

	CPC* findPlayer = getPlayerByCharIndex(ch->m_index);
	if (findPlayer != ch)
		return false;

	return true;
}

void PCManager::sendToAll(CNetMsg::SP& msg)
{
	map_t::iterator iter = playerMap_.begin();
	map_t::iterator endIter = playerMap_.end();
	for (; iter != endIter; ++iter)
	{
		CPC* pc = (*iter).pPlayer;
		if (pc)
		{
			SEND_Q(msg, pc->m_desc);
		}
	}
}

void PCManager::sendGuildWarPointMsg(CWarCastle* castle, int zoneindex)
{
	map_t::iterator iter = playerMap_.begin();
	map_t::iterator endIter = playerMap_.end();
	for (; iter != endIter; ++iter)
	{
		CPC* pc = (*iter).pPlayer;
		if (pc && pc->GetJoinFlag(zoneindex) != WCJF_NONE && pc->m_pZone && pc->m_pZone->m_index == zoneindex)
		{
			CNetMsg::SP rmsg(new CNetMsg);
			GuildWarPointMsg(rmsg, pc, castle);
			SEND_Q(rmsg, pc->m_desc);
		}
	}
}

void PCManager::sendToWarJoinUser(CNetMsg::SP& msg, int zoneindex, bool bInZone)
{
	map_t::iterator iter = playerMap_.begin();
	map_t::iterator endIter = playerMap_.end();
	for (; iter != endIter; ++iter)
	{
		CPC* pc = (*iter).pPlayer;
		if (pc && pc->GetJoinFlag(zoneindex) == WCJF_NONE)
		{
			continue;
		}

		if (pc && !bInZone || (pc->m_pZone && pc->m_pZone->m_index == zoneindex))
		{
			SEND_Q(msg, pc->m_desc);
		}
	}
}

void PCManager::sendToAllTeacher(CNetMsg::SP& msg)
{
	map_t::iterator iter = playerMap_.begin();
	map_t::iterator endIter = playerMap_.end();
	for (; iter != endIter; ++iter)
	{
		CPC* pc = (*iter).pPlayer;
		if (pc && pc->m_bTeacher)
		{
			SEND_Q(msg, pc->m_desc);
		}
	}
}

void PCManager::sendToZone(CNetMsg::SP& msg, int zoneIndex)
{
	map_t::iterator iter = playerMap_.begin();
	map_t::iterator endIter = playerMap_.end();
	for (; iter != endIter; ++iter)
	{
		CPC* pc = (*iter).pPlayer;
		if (pc && pc->m_pZone
				&& (pc->m_pZone->m_index == zoneIndex || zoneIndex == -1))
		{
			SEND_Q(msg, pc->m_desc);
		}
	}
}

void PCManager::changeNickName( const char* oldname, const char* newname )
{
	map_t::index<Key_Char_Nick_Name>::type& p = playerMap_.get<Key_Char_Nick_Name>();
	map_t::index<Key_Char_Nick_Name>::type::iterator it = p.find(oldname);
	if (it == p.end())
		return;

	p.modify_key(it, boost::lambda::_1=newname);
}

#ifdef PREMIUM_CHAR
void PCManager::resetPremiumCharJumpCount()
{
	map_t::iterator iter = playerMap_.begin();
	map_t::iterator endIter = playerMap_.end();
	for (; iter != endIter; ++iter)
	{
		CPC* pc = (*iter).pPlayer;
		pc->m_premiumChar.setJumpCount(0);
	}
}
#endif

max_stars_repo_name: Light-Games-Ink/LMLastChaosSource

max_issues_repo_name: Light-Games-Ink/LMLastChaosSource

max_forks_repo_name: Light-Games-Ink/LMLastChaosSource


text:
#include "SuffixMatchMiningTask.hpp"
#include <document-manager/DocumentManager.h>
#include <boost/filesystem.hpp>
#include <glog/logging.h>
#include <icma/icma.h>
#include <la-manager/KNlpWrapper.h>
#include <la-manager/LAPool.h>
#include <mining-manager/util/split_ustr.h>
#include <util/ustring/UString.h>
#include "FilterManager.h"
#include "FMIndexManager.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
namespace sf1r
{

SuffixMatchMiningTask::SuffixMatchMiningTask(
        boost::shared_ptr<DocumentManager>& document_manager,
        boost::shared_ptr<FMIndexManager>& fmi_manager,
        boost::shared_ptr<FilterManager>& filter_manager,
        std::string data_root_path,
        boost::shared_mutex& mutex)
    : isRtypeIncremental_(false)
    , document_manager_(document_manager)
    , fmi_manager_(fmi_manager)
    , filter_manager_(filter_manager)
    , data_root_path_(data_root_path)
    , is_incrememtalTask_(false)
    , mutex_(mutex)
{
}

SuffixMatchMiningTask::~SuffixMatchMiningTask()
{

}

bool SuffixMatchMiningTask::preProcess(int64_t timestamp)
{
    if (!is_incrememtalTask_)
    {
        new_filter_manager.reset(new FilterManager(document_manager_, filter_manager_->getGroupManager(), data_root_path_,
                    filter_manager_->getAttrManager(), filter_manager_->getNumericTableBuilder()));
        new_filter_manager->copyPropertyInfo(filter_manager_);
        new_filter_manager->generatePropertyId();

        new_fmi_manager.reset(new FMIndexManager(data_root_path_,
                                                 document_manager_,
                                                 new_filter_manager,
                                                 fmi_manager_->getFuzzyNormalizer()));

        std::vector<std::string> properties;
        VirtualConfig virtulProperty;
        for (int i = 0; i < FMIndexManager::FM_TYPE_COUNT; ++i)
        {
            fmi_manager_->getProperties(properties, (FMIndexManager::PropertyFMType)i);
            fmi_manager_->getVirtualProperty(virtulProperty);
            new_fmi_manager->addProperties(properties, (FMIndexManager::PropertyFMType)i);
            new_fmi_manager->setVirtualProperty(virtulProperty);
            std::vector<std::string>().swap(properties);
        }

        size_t last_docid = fmi_manager_ ? fmi_manager_->docCount() : 0;
        need_rebuild = false;

        std::vector<uint32_t> del_docid_list;
        document_manager_->getDeletedDocIdList(del_docid_list);

        if (last_docid == document_manager_->getMaxDocId())
        {
            // check if there is any new deleted doc.
            std::vector<size_t> doclen_list(del_docid_list.size(), 0);
            fmi_manager_->getDocLenList(del_docid_list, doclen_list);
            for (size_t i = 0; i < doclen_list.size(); ++i)
            {
                if (doclen_list[i] > 0)
                {
                    need_rebuild = true;
                    break;
                }
            }

            if (!need_rebuild)
            {
                /*
                @brief : in here document_manager_->isThereRtypePro() just means for the -R SCD,
                because the Rtype doc in -U SCD is not in this flow.
                */
                if (document_manager_->isThereRtypePro())
                {
                    LOG (INFO) << "Update for R-type SCD" << endl;
                    const std::vector<std::pair<int32_t, std::string> >& prop_list = filter_manager_->getProp_list();
                    for (std::vector<std::pair<int32_t, std::string> >::const_iterator i = prop_list.begin(); i != prop_list.end(); ++i)
                    {
                        std::set<string>::iterator iter = document_manager_->RtypeDocidPros_.find((*i).second);
                        if (iter == document_manager_->RtypeDocidPros_.end())
                        {
                            if (!filter_manager_->isNumericProp((*i).second) && !filter_manager_->isDateProp((*i).second))
                            {
                                new_filter_manager->addUnchangedProperty((*i).second);
                                LOG (INFO) << "Add Unchanged property : " << (*i).second << endl;
                            }
                        }
                    }
                }
                else
                {
                    LOG (INFO) << "All filter properties do not need rebuild ... " << endl;
                    return false;
                }
            }
        }
        else
        {
            LOG(INFO) << "old fmi docCount is : " << last_docid << ", document_manager count:" << document_manager_->getMaxDocId();
            need_rebuild = true;
        }

        if (need_rebuild)
        {
            LOG(INFO) << "rebuilding in fm-index is needed.";
        }
        else
        {
            new_fmi_manager->useOldDocCount(fmi_manager_.get());
        }

        bool isInitAndLoad = true;
        if (!need_rebuild) return true;

        if (!new_fmi_manager->initAndLoadOldDocs(fmi_manager_.get()))
        {
            LOG(ERROR) << "fmindex init building failed, must stop. ";
            new_fmi_manager->clearFMIData();
            isInitAndLoad = false;
        }
        if (!isInitAndLoad) return false;
    }
    return true;
}

bool SuffixMatchMiningTask::postProcess()
{
    if (!is_incrememtalTask_)
    {
        if (need_rebuild && !new_fmi_manager->buildCollectionAfter())
            return false;
        new_filter_manager->setRebuildFlag(filter_manager_.get());
        size_t last_docid = fmi_manager_ ? fmi_manager_->docCount() : 0;

        new_filter_manager->finishBuildStringFilters();
        new_filter_manager->buildFilters(last_docid, document_manager_->getMaxDocId());

        new_fmi_manager->setFilterList(new_filter_manager->getFilterList());

        LOG(INFO) << "building filter data finished";

        new_fmi_manager->buildLessDVProperties();
        new_fmi_manager->buildExternalFilter(); //although here is empty ... but it will swap Unchanged Filter ...

        {
            WriteLock lock(mutex_);
            if (!need_rebuild)
            {
                // no rebuilding, so just take the owner of old data.
                LOG(INFO) << "no rebuild need, just swap data for common properties.";
                new_fmi_manager->swapCommonProperties(fmi_manager_.get());
                new_fmi_manager->swapUnchangedFilter(fmi_manager_.get());
                new_filter_manager->swapUnchangedFilter(filter_manager_.get());
                new_filter_manager->clearUnchangedProperties();
            }

            fmi_manager_.swap(new_fmi_manager);
            filter_manager_.swap(new_filter_manager);

            filter_manager_->clearRebuildFlag();
            new_fmi_manager.reset();
            new_filter_manager.reset();
        }
        LOG(INFO) << "saving fm-index data";
        fmi_manager_->saveAll();
        filter_manager_->saveFilterId();
        filter_manager_->clearFilterList();
        LOG(INFO) << "building fm-index finished";
    }

    return true;
}

bool SuffixMatchMiningTask::buildDocument(docid_t docID, const Document& doc)
{
    if (!is_incrememtalTask_ && !isRtypeIncremental_)
    {
        bool failed = (doc.getId() == 0);
        new_fmi_manager->appendDocsAfter(failed, doc);
        if (!failed)
        {
            new_filter_manager->buildStringFiltersForDoc(docID, doc);
        }
    }
    return true;
}

docid_t SuffixMatchMiningTask::getLastDocId()
{
    return fmi_manager_ ? fmi_manager_->docCount() + 1 : 1;
}

void SuffixMatchMiningTask::setTaskStatus(bool is_incrememtalTask)
{
    is_incrememtalTask_ = is_incrememtalTask;
}

}


text:
#include <boost/regex.hpp>
#include <algorithm>

#include "HTMLTokenizer.hpp"
#include "tokens/StartToken.hpp"
#include "tokens/EndToken.hpp"
#include "tokens/DoctypeToken.hpp"
#include "tokens/CommentToken.hpp"
#include "tokens/CharacterToken.hpp"

int get_wstring_iposition(std::wstring long_str, std::wstring substr);

// A list of commonly used Unicode whitespace characters
// In order: tab, line feed, form feed, space
std::set<wchar_t> space_chars = {'\u0009', '\u000A', '\u000C', '\u0020'};

// TODO: Check HTML requirements more strictly
bool HTMLTokenizer::is_valid_html_string(const std::wstring &html_string)
{
    return HTMLTokenizer::contains_doctype(html_string) &&
           HTMLTokenizer::contains_root_element(html_string) &&
           HTMLTokenizer::doctype_before_root(html_string);
}

bool HTMLTokenizer::contains_doctype(const std::wstring &html_string)
{
    return (get_wstring_iposition(html_string, L"<!DOCTYPE") != -1);
}

bool HTMLTokenizer::contains_root_element(const std::wstring &html_string)
{
    return HTMLTokenizer::contains_root_open(html_string) &&
           HTMLTokenizer::contains_root_close(html_string) &&
           HTMLTokenizer::contains_root_open_before_close(html_string);
}

bool HTMLTokenizer::contains_root_open(const std::wstring &html_string)
{
    boost::wregex html_root(L"|");
    boost::wsmatch results;
    return boost::regex_search(html_string, results, html_root);
}

bool HTMLTokenizer::contains_root_close(const std::wstring &html_string)
{
    return (html_string.find(L"") != std::wstring::npos);
}

bool HTMLTokenizer::contains_root_open_before_close(const std::wstring
        &html_string)
{
    return (html_string.find(L"<html") < html_string.find(L""));
}

bool HTMLTokenizer::doctype_before_root(const std::wstring &html_string)
{
    return get_wstring_iposition(html_string, L"<!DOCTYPE") <
        get_wstring_iposition(html_string, L"<html");
}

std::shared_ptr<HTMLToken>
    HTMLTokenizer::create_token_from_string(const std::wstring &html_string)
{
    tokenizer_state state = data_state;
    std::wstring::const_iterator it = html_string.cbegin();
    return create_token_from_string(html_string, state, it);
}

std::shared_ptr<HTMLToken>
    HTMLTokenizer::create_token_from_string(const std::wstring &html_string,
        HTMLTokenizer::tokenizer_state &state, std::wstring::const_iterator &it)
{
    std::shared_ptr<HTMLToken> token = std::make_shared<HTMLToken>();

    // Can't use range-based loop, because we need to
    // be able to look forwards/go backwards
    for (; it != html_string.cend(); ++it)
    {
        wchar_t next_char = *it;
        switch (state)
        {
            case data_state:
            {
                // TODO: implement this state
                if (next_char == '&')
                    state = char_ref_in_data_state;

                else if (next_char == '<')
                    state = tag_open_state;

                // Handle \u0000, EOF
                else
                {
                    token = std::make_shared<CharacterToken>(next_char);
                    it++;
                    return token;
                }

                break;
            }

            case tag_open_state:
            {
                if (next_char == '!')
                    state = markup_declaration_open_state;

                else if (next_char == '/')
                    state = end_tag_open_state;

                else if (isalpha(next_char))
                {
                    token = std::make_shared<StartToken>(next_char);
                    state = tag_name_state;
                }

                // parse error
                else if (next_char == '?')
                    state = bogus_comment_state;

                break;
            }

            case tag_name_state:
            {
                if (space_chars.count(next_char) != 0)
                    state = before_attribute_name_state;

                else if (next_char == '/')
                    state = self_closing_start_tag_state;

                else if (next_char == '>')
                {
                    state = data_state;
                    it++;
                    return token;
                }

                else if (isalpha(next_char))
                    token->add_char_to_tag_name(next_char);

                // null, EOF: parse error

                else
                    token->add_char_to_tag_name(next_char);

                break;
            }

            case char_ref_in_data_state:
                break;

            case self_closing_start_tag_state:
            {
                if (next_char == '>')
                {
                    state = data_state;
                    token->set_self_closing(true);
                    it++;
                    return token;
                }

                // anything else: parse error
                break;
            }

            case before_attribute_name_state:
            {
                // End tokens should never have attributes
                if (space_chars.count(next_char) != 0)
                    break;

                else if (next_char == '/')
                    state = self_closing_start_tag_state;

                else if (next_char == '>')
                {
                    state = data_state;
                    it++;
                    return token;
                }

                // null, EOF, ", ', ?, =
                // parse error

                else
                {
                    state = attribute_name_state;
                    token->add_to_current_attribute_name(next_char);
                }

                break;
            }

            case attribute_name_state:
            {
                if (space_chars.count(next_char) != 0)
                    state = after_attribute_name_state;

                else if (next_char == '/')
                    state = self_closing_start_tag_state;

                else if (next_char == '=')
                    state = before_attribute_value_state;

                // EOF, ", ', <, null
                // parse error

                else
                {
                    token->add_to_current_attribute_name(next_char);
                }

                break;
            }

            case after_attribute_name_state:
            {
                if (space_chars.count(next_char) != 0)
                    break;

                if (next_char == '/')
                    state = self_closing_start_tag_state;

                if (next_char == '=')
                    state = before_attribute_value_state;

                // null, ", ', <, EOF
                // parse error

                break;
            }

            case before_attribute_value_state:
            {
                if (space_chars.count(next_char) != 0)
                    break;

                else if (next_char == '"')
                    state = attribute_value_double_quoted_state;

                // TODO: implement this state
                else if (next_char == '&')
                    state = attribute_value_unquoted_state;

                else if (next_char == '\'')
                    state = attribute_value_single_quoted_state;

                else if (next_char == '>')
                {
                    // parse error
                    state = data_state;
                    it++;
                    return token;
                }

                // <, =, `, EOF
                // parse error

                else
                {
                    token->add_to_current_attribute_name(next_char);
                    state = attribute_value_unquoted_state;
                }

                break;
            }

            case attribute_value_double_quoted_state:
            {
                if (next_char == '"')
                    state = after_attribute_value_quoted_state;

                // TODO: implement this state
                else if (next_char == '&')
                    state = char_ref_in_attribute_value_state;

                // null, EOF: parse error

                else
                    token->add_to_current_attribute_value(next_char);

                break;
            }

            case attribute_value_single_quoted_state:
            {
                if (next_char == '\'')
                    state = after_attribute_value_quoted_state;

                // TODO: handle this state
                else if (next_char == '&')
                    state = char_ref_in_attribute_value_state;

                // EOF: parse error

                else
                    token->add_to_current_attribute_value(next_char);

                break;
            }

            case attribute_value_unquoted_state:
            {
                if (space_chars.count(next_char) != 0)
                    state = before_attribute_value_state;

                // TODO: implement this state
                else if (next_char == '&')
                    state = char_ref_in_attribute_value_state;

                else if (next_char == '>')
                {
                    state = data_state;
                    it++;
                    return token;
                }

                // null, ", ', <, =, `, EOF: parse error

                else
                    token->add_to_current_attribute_value(next_char);

                break;
            }

            case after_attribute_value_quoted_state:
            {
                token->process_current_attribute();

                if (space_chars.count(next_char) != 0)
                    state = before_attribute_name_state;

                else if (next_char == '/')
                    state = self_closing_start_tag_state;

                else if (next_char == '>')
                {
                    state = data_state;
                    it++;
                    return token;
                }

                // EOF, anything else: parse error
                break;
            }

            case bogus_comment_state:
                break;

            case markup_declaration_open_state:
            {
                if (std::wstring(it, it + 2) == L"--")
                {
                    it += 1;
                    token = std::make_shared<CommentToken>();
                    state = comment_start_state;
                }

                std::wstring next_seven_chars(it, it + 7);

                if (get_wstring_iposition(next_seven_chars, L"doctype") == 0)
                {
                    // 6, not 7, because for loop increments one extra step
                    it += 6;
                    state = doctype_state;
                }

                break;
            }

            case doctype_state:
            {
                if (space_chars.count(next_char) != 0)
                    state = before_doctype_name_state;

                // EOF: parse error

                else
                {
                    it--;
                    state = before_doctype_name_state;
                }

                break;
            }

            case before_doctype_name_state:
            {
                if (space_chars.count(next_char) != 0)
                    break;

                token = std::make_shared<DoctypeToken>();

                if (next_char == '>')
                {
                    state = data_state;
                    token->set_quirks_required(true);
                    it++;
                    return token;
                }

                // EOF: parse error

                else
                {
                    token->add_char_to_tag_name(next_char);
                    state = doctype_name_state;
                    break;
                }
            }

            case doctype_name_state:
            {
                if (space_chars.count(next_char) != 0)
                {
                    state = after_doctype_name_state;
                    token->set_is_name_set(true);
                    break;
                }

                else if (next_char == '>')
                {
                    state = data_state;
                    token->set_is_name_set(true);
                    it++;
                    return token;
                }

                // null, EOF: parse error

                token->add_char_to_tag_name(next_char);
                break;
            }

            case after_doctype_name_state:
            {
                if (space_chars.count(next_char) != 0)
                    break;

                // EOF: parse error

                // More exotic doctypes are not yet supported
                token->set_quirks_required(true);
                state = bogus_doctype_state;

                break;
            }

            case bogus_doctype_state:
            {
                if (next_char == '>')
                {
                    state = data_state;
                    it++;
                    return token;
                }

                // EOF: reconsume
                break;
            }

            case end_tag_open_state:
            {
                if (isalpha(next_char))
                {
                    token = std::make_shared<EndToken>(next_char);
                    state = tag_name_state;
                }

                // anything else: parse error

                break;
            }

            case comment_start_state:
            {
                if (next_char == '-')
                    state = comment_start_dash_state;

                // NULL, EOF: parse error

                else if (next_char == '>')
                {
                    state = data_state;
                    it++;
                    return token;
                }

                else
                {
                    token->add_char_to_data(next_char);
                    state = comment_state;
                }

                break;
            }

            case comment_start_dash_state:
            {
                if (next_char == '-')
                    state = comment_end_state;

                else if (next_char == '>')
                {
                    state = data_state;
                    it++;
                    return token;
                }

                // EOF: parse error

                else
                {
                    token->add_char_to_data('-');
                    token->add_char_to_data(next_char);
                    state = comment_state;
                }

                break;
            }

            case comment_state:
            {
                if (next_char == '-')
                    state = comment_end_dash_state;

                // null, EOF: parse error

                else
                    token->add_char_to_data(next_char);

                break;
            }

            case comment_end_dash_state:
            {
                if (next_char == '-')
                    state = comment_end_state;

                else
                {
                    token->add_char_to_data('-');
                    token->add_char_to_data(next_char);
                    state = comment_state;
                }

                break;
            }

            case comment_end_state:
            {
                if (next_char == '>')
                {
                    state = data_state;
                    it++;
                    return token;
                }

                // parse error
                else if (next_char == '!')
                    state = comment_end_bang_state;

                else if (next_char == '-')
                    token->add_char_to_data(next_char);

                else
                {
                    token->add_char_to_data('-');
                    token->add_char_to_data('-');
                    token->add_char_to_data(next_char);
                    state = comment_state;
                }

                break;
            }

            case comment_end_bang_state:
            {
                if (next_char == '-')
                {
                    token->add_char_to_data('-');
                    token->add_char_to_data('-');
                    token->add_char_to_data('!');
                    state = comment_end_dash_state;
                }

                else if (next_char == '>')
                {
                    state = data_state;
                    it++;
                    return token;
                }

                // null, EOF: parse error

                else
                {
                    token->add_char_to_data('-');
                    token->add_char_to_data('-');
                    token->add_char_to_data('!');
                    token->add_char_to_data(next_char);
                    state = comment_state;
                }

                break;
            }

            default:
            {
                break;
            }
        }
    }

    // Shouldn't get here
    return token;
}

std::vector<std::shared_ptr<HTMLToken>>
    HTMLTokenizer::tokenize_string(const std::wstring &html_string)
{
    std::wstring::const_iterator it = html_string.cbegin();
    tokenizer_state state = data_state;

    std::shared_ptr<HTMLToken> token =
        create_token_from_string(html_string, state, it);
    std::vector<std::shared_ptr<HTMLToken>> tokens;

    while (!(it >= html_string.cend()))
    {
        tokens.push_back(token);
        token = create_token_from_string(html_string, state, it);
    }

    if (it == html_string.cend())
        tokens.push_back(token);

    return tokens;
}

max_stars_repo_name: windlessStorm/WebWhir

max_issues_repo_name: windlessStorm/WebWhir

max_forks_repo_name: windlessStorm/WebWhir


text:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                           */
/*  This file is part of the library KASKADE 7                               */
/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */
/*                                                                           */
/*  Copyright (C) 2015-2015 Zuse Institute Berlin                            */
/*                                                                           */
/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */
/*    see $KASKADE/academic.txt                                              */
/*                                                                           */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <iostream>

#include "dune/common/fvector.hh"

#include "linalg/numaMatrix.hh"

using namespace Kaskade;

#ifdef UNITTEST
#include <boost/timer/timer.hpp>

int main(void)
{
  using namespace std;

  std::cout << "8x8 matrix a_ij = i+j\n";
  NumaDenseMatrix<Dune::FieldVector<double,1>> mat(8,8);
  for (auto ri=mat.begin(); ri!=mat.end(); ++ri)
    for (auto ci=ri->begin(); ci!=ri->end(); ++ci)
      *ci = ri.index()+ci.index();

  std::cout << mat << "\nFrobenius norm: " << mat.frobenius_norm() << "\n";

  std::cout << "Timing test of 100 additions of two 60000x100 matrices\n";
  NumaDenseMatrix<Dune::FieldMatrix<double,1,1>> m2(60000,100);
  for (auto ri=m2.begin(); ri!=m2.end(); ++ri)
    for (auto ci=ri->begin(); ci!=ri->end(); ++ci)
      *ci = ri.index()+ci.index();
  boost::timer::cpu_timer timer;
  for (int i=0; i<100; ++i)
  {
    m2 += m2; // these two are a no-op
    m2 /= 2;
  }
  std::cout << timer.format() << "\n";
  // subtract original data - should be zero.
  for (auto ri=m2.begin(); ri!=m2.end(); ++ri)
    for (auto ci=ri->begin(); ci!=ri->end(); ++ci)
      *ci -= ri.index()+ci.index();
  std::cout << "Frobenius norm (should be 0): " << m2.frobenius_norm() << "\n";

  NumaVector<double> vec(12);
  for (auto i=begin(vec); i!=end(vec); ++i)
    *i = i.index();
  std::cout << "vec 12: " << vec << "\ndot product (should be 506): " << vec.dot(vec) << "\n2-norm (should be 22.4944): " << vec.two_norm() << "\n";

  vec.axpy(1.0,vec);
  std::cout << "twice vec: " << vec << "\n";

  return 0;
}

#endif

max_stars_repo_name: chenzongxiong/streambox

max_issues_repo_name: chenzongxiong/streambox

max_forks_repo_name: chenzongxiong/streambox


text:
/*
 * Copyright 2018-, Olivier Stasse LAAS-CNRS
 *
 */
#define EIGEN_RUNTIME_NO_MALLOC

#include <Eigen/Dense>
#include <dynamic-graph/factory.h>
#include <sot/core/debug.hh>
#include <sot/torque_control/commands-helper.hh>
#include <sot/torque_control/ddp-actuator-solver.hh>

#if DEBUG
#define ODEBUG(x) std::cout << x << std::endl
#else
#define ODEBUG(x)
#endif
#define ODEBUG3(x) std::cout << x << std::endl

#define DBGFILE "/tmp/debug-ddp_actuator_solver.dat"

#define RESETDEBUG5()                            \
  {                                              \
    std::ofstream DebugFile;                     \
    DebugFile.open(DBGFILE, std::ofstream::out); \
    DebugFile.close();                           \
  }
#define ODEBUG5FULL(x)                                                                          \
  {                                                                                \
    std::ofstream DebugFile;                                                                    \
    DebugFile.open(DBGFILE, std::ofstream::app);                                                \
    DebugFile << __FILE__ << ":" << __FUNCTION__ << "(#" << __LINE__ << "):" << x << std::endl; \
    DebugFile.close();                                                                          \
  }
#define ODEBUG5(x)                               \
  {                                              \
    std::ofstream DebugFile;                     \
    DebugFile.open(DBGFILE, std::ofstream::app); \
    DebugFile << x << std::endl;                 \
    DebugFile.close();                           \
  }

#define RESETDEBUG4()
#define ODEBUG4FULL(x)
#define ODEBUG4(x)

namespace dynamicgraph {
namespace sot {
namespace torque_control {

namespace dynamicgraph = ::dynamicgraph;
using namespace dynamicgraph;
using namespace dynamicgraph::command;
using namespace Eigen;

/// Define EntityClassName here rather than in the header file
/// so that it can be used by the macros DEFINE_SIGNAL_**_FUNCTION.
typedef DdpActuatorSolver EntityClassName;

/* --- DG FACTORY ------------------------------------------------------- */
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(DdpActuatorSolver, "DdpActuatorSolver");

DdpActuatorSolver::DdpActuatorSolver(const std::string &name)
    : Entity(name),
      CONSTRUCT_SIGNAL_IN(pos_des, dynamicgraph::Vector),
      CONSTRUCT_SIGNAL_IN(pos_motor_measure, dynamicgraph::Vector),
      CONSTRUCT_SIGNAL_IN(pos_joint_measure, dynamicgraph::Vector),
      CONSTRUCT_SIGNAL_IN(dx_measure, dynamicgraph::Vector),
      CONSTRUCT_SIGNAL_IN(tau_measure, dynamicgraph::Vector),
      CONSTRUCT_SIGNAL_IN(tau_des, dynamicgraph::Vector),
      CONSTRUCT_SIGNAL_IN(temp_measure, dynamicgraph::Vector),
      CONSTRUCT_SIGNAL_OUT(tau, dynamicgraph::Vector, m_pos_desSIN),
      m_dt(1e-3),
      m_solver(m_model, m_cost, DISABLE_FULLDDP, DISABLE_QPBOX),
      m_T(3000),
      m_stopCrit(1e-5),
      m_iterMax(100) {
  RESETDEBUG5();
  Entity::signalRegistration(ALL_INPUT_SIGNALS << ALL_OUTPUT_SIGNALS);

  m_zeroState.setZero();

  /* Commands. */
  addCommand("init", makeCommandVoid4(*this, &DdpActuatorSolver::param_init,
                                      docCommandVoid4("Initialize the DDP solver.", "Control timestep [s].",
                                                      "Size of the preview window (in nb of samples)",
                                                      "Max. nb. of iterations", "Stopping criteria")));
}

/* --- COMMANDS ---------------------------------------------------------- */
DEFINE_SIGNAL_OUT_FUNCTION(tau, dynamicgraph::Vector) {
  /// ---- Get the information -----
  /// Desired position
  const dynamicgraph::Vector &pos_des = m_pos_desSIN(iter);
  /// Measured position
  const dynamicgraph::Vector &pos_joint_measure = m_pos_joint_measureSIN(iter);
  /// Measured speed
  const dynamicgraph::Vector &dx_measure = m_dx_measureSIN(iter);
  /// Measured temperature
  const dynamicgraph::Vector &temp_measure = m_temp_measureSIN(iter);
  /// Measured torque
  const dynamicgraph::Vector &tau_measure = m_tau_measureSIN(iter);
  /// Desired torque
  const dynamicgraph::Vector &tau_des = m_tau_desSIN(iter);

  DDPSolver<double, 5, 1>::stateVec_t xinit, xDes;

  /// --- Initialize solver ---
  xinit << pos_joint_measure(0), dx_measure(0), temp_measure(0), tau_measure(0),
      // m_ambiant_temperature;
      25.0;

  xDes << pos_des, 0.0, 25.0, tau_des, 25.0;
  ODEBUG5(xinit);
  ODEBUG5("");
  ODEBUG5(xDes);

  DCTemp model;
  CostTemp cost;
  DDPSolver<double, 5, 1> m_solver(model, cost, 0, 0);

  m_solver.FirstInitSolver(xinit, xDes, m_T, m_dt, m_iterMax, m_stopCrit);
  ODEBUG5("FirstInitSolver");

  /// --- Solve the DDP ---
  m_solver.solveTrajectory();
  ODEBUG5("Trajectory solved");

  /// --- Get the command ---
  DDPSolver<double, 5, 1>::traj lastTraj;
  lastTraj = m_solver.getLastSolvedTrajectory();
  ODEBUG5("getLastSolvedTrajectory");

  DDPSolver<double, 5, 1>::commandVecTab_t uList;
  uList = lastTraj.uList;
  ODEBUG5("uList");

  // s = uList[0];
  s.resize(32);
  s << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, uList[0], 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;
  // s.setZero(32);
  ODEBUG5(s);
  return s;
}

void DdpActuatorSolver::param_init(const double &timestep, const int &T, const int &nbItMax,
                                   const double &stopCriteria) {
  m_T = T;
  m_dt = timestep;
  m_iterMax = nbItMax;
  m_stopCrit = stopCriteria;
  m_solver.FirstInitSolver(m_zeroState, m_zeroState, m_T, m_dt, m_iterMax, m_stopCrit);
}

void DdpActuatorSolver::display(std::ostream &os) const {
  os << " T: " << m_T << " timestep: " << m_dt << " nbItMax: " << m_iterMax << " stopCriteria: " << m_stopCrit
     << std::endl;
}
}  // namespace torque_control
}  // namespace sot
}  // namespace dynamicgraph