text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(PAWN_AAST_HPP)
#define PAWN_AAST_HPP

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

#include <iostream>
#include <list>
#include <map>
#include <vector>

#include <helper.hpp>

namespace client { namespace reduce { namespace ast
{
    using variable = std::string;
    using column = unsigned int;

    enum class optoken : int {
      sum,
      max,
      count
    };

    typedef boost::variant<variable , column> operand;

    struct operation {
      optoken operator_;
      operand operand_;
    };

    using expr = std::list<operation>;

    // print functions for debugging
    struct printer {
        typedef void result_type;

        void operator()(variable const& x) const { std::cout << '%' << x; }
        void operator()(column const& x) const { std::cout << '$' << x; }
        void operator()(optoken const &o) const {
            switch (o) {
                case optoken::sum: std::cout << " sum"; break;
                case optoken::max: std::cout << " max"; break;
                case optoken::count: std::cout << " count"; break;
            }
        }

        void operator()(operation const &x) const {
          (*this)(x.operator_);
          boost::apply_visitor(*this, x.operand_);
        }

        void operator()(expr const& x) const {
          for (auto&it : x) (*this)(it);
        }
    };

    struct colsEval {
    private:
      using ColIndices = client::helper::ColIndices;
      const ColIndices &_pre;
      bool _isInitial {true};
      std::vector<std::string> _headers;
    public:
      using result_type = std::pair<ColIndices, std::string>;
      colsEval(const ColIndices &v) : _pre{v} {}
      void setHeaders(const std::vector<std::string>& h) { _headers = h; }
      void notInitial() { _isInitial = false; }
      result_type operator()(variable const &x) {
        auto jt = std::find(begin(_headers), end(_headers), x);
        if (jt != std::end(_headers)) return (*this)((unsigned int)(jt - std::begin(_headers)) + 1, x);
        auto it = std::find(begin(_pre.var), end(_pre.var), x);
        if (it == std::end(_pre.var)) return std::make_pair(ColIndices{}, "Error: " + x + " used before declaration.");
        ColIndices res;
        res.var.push_back(_nm + "_" + x);
        return std::make_pair(res, "");
      }
      result_type operator()(column const &x, std::string colName = "") {
        if (!_isInitial) return std::make_pair(ColIndices{}, "Can't access number columns via column index after reduce.");
        ColIndices res;
        res.num.push_back(x);
        res.var.push_back(_nm + "_" + ((colName.size() > 0) ? colName : std::to_string(x)));
        return std::make_pair(res, "");
      }
      std::string _nm;
      result_type operator()(operation const& x) {
          switch (x.operator_) {
              case optoken::sum: _nm = std::string{"sum"}; break;
              case optoken::max: _nm = std::string{"max"};
              case optoken::count: _nm = std::string{"count"};
          }
          return boost::apply_visitor(*this, x.operand_);
      }
      result_type operator()(expr const& e) {
          result_type res{};
          for (const auto& oper : e) {
            auto x = (*this)(oper);
            if (x.second.size() > 0) return x;
            res.first.add(x.first);
          }
          return res;
      }
  };

    ///////////////////////////////////////////////////////////////////////////
    //  The AST evaluator
    ///////////////////////////////////////////////////////////////////////////
    struct evaluator {
    private:
      struct indexHelper {
        using result_type = int;
        const helper::positionTeller _index;
        indexHelper(helper::positionTeller p) : _index{p} {}
        int operator()(variable var) const {
          return _index.var(var);
        }

        int operator()(column n) const {
          return _index.num(n);
        }
      };

        const indexHelper _index;
        bool _sameIndex {false};
    public:
        using resT = std::tuple<std::vector<double>>&;
        using keyT = const std::vector<std::string>&;
        using rowT = const std::vector<double>&;
        using retFnT = std::function<resT(resT, keyT, rowT)>;
        typedef retFnT result_type;
        void sameIndex(bool isSameIndex = true) { _sameIndex = isSameIndex; }

        evaluator(helper::positionTeller p) : _index{p} {}

        retFnT operator()(operation const& x, int i) const {
            int j = _sameIndex ? i : boost::apply_visitor(_index, x.operand_);
            switch (x.operator_)
            {
                case optoken::sum: return [i, j](resT r, keyT, rowT c) -> auto& { std::get<0>(r)[i] += c[j]; return r; };
                case optoken::max: return [i, j](resT r, keyT, rowT c) -> auto& { if (c[j] > std::get<0>(r)[i]) std::get<0>(r)[i] = c[j]; return r; };
                case optoken::count: return [i, j](resT r, keyT, rowT c) -> auto& { std::get<0>(r)[i] += 1.0; return r; };
            }
            return [i, j](resT r, keyT, rowT c) -> auto& { if (c[j] > std::get<0>(r)[i]) std::get<0>(r)[i] = c[j]; return r; };
        }

        std::vector<retFnT> operator()(expr const& x) const {
            std::vector<retFnT> v;
            int i = 0;
            for (const auto& oper : x) {
                v.push_back((*this)(oper, i++));
            }
            return v;
        }

    };
}}}

BOOST_FUSION_ADAPT_STRUCT(
    client::reduce::ast::operation,
    (client::reduce::ast::optoken, operator_)
    (client::reduce::ast::operand, operand_)
)
#endif

max_stars_repo_name: haptork/pawn

max_issues_repo_name: haptork/pawn

max_forks_repo_name: haptork/pawn


text:
#include "password.hpp"

#include <boost/version.hpp>
#if BOOST_VERSION > 106800
	#include <boost/uuid/detail/sha1.hpp>
#else
	#include <boost/uuid/sha1.hpp>
#endif
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/algorithm/string.hpp>

std::string encode64(const std::string& val) {
    using namespace boost::archive::iterators;
    using It = base64_from_binary<transform_width<std::string::const_iterator, 6, 8>>;
    auto tmp = std::string(It(std::begin(val)), It(std::end(val)));
    return tmp.append((3 - val.size() % 3) % 3, '=');
}

std::string calculatePassword(const std::string& secret, const std::string& alias) {
	std::string secretAndAlias = secret + alias;
	boost::uuids::detail::sha1 sha1;
	sha1.process_bytes(secretAndAlias.c_str(), secretAndAlias.size());
	unsigned int digest[5];
	sha1.get_digest(digest);
	std::string hash;
	hash.resize(20);
	for (size_t i = 0; i < 5; ++i) {
		// Swap byte order because of Little Endian
		const char* tmp = reinterpret_cast<char*>(digest);
		hash[i * 4    ] = tmp[i * 4 + 3];
		hash[i * 4 + 1] = tmp[i * 4 + 2];
		hash[i * 4 + 2] = tmp[i * 4 + 1];
		hash[i * 4 + 3] = tmp[i * 4    ];
	}
	return encode64(hash).substr(0, 16);
}

ext: cpp

max_stars_repo_name: jhasse/pwcalculator

max_issues_repo_name: jhasse/pwcalculator

max_forks_repo_name: jhasse/pwcalculator


text:
//
//  FILE NAME:  $HeadURL$
//
//  DESCRIPTION:
//
//  REVISION:	   $Revision$
//
//  COPYRIGHT:  (c) 2007 Advertising.com All Rights Reserved.
//
//  LAST UPDATED:   $Date$
//  UPDATED BY: $Author$

#ifndef __DATA_PROXY_SERVICE_SYSTEST_HPP__
#define __DATA_PROXY_SERVICE_SYSTEST_HPP__

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <boost/scoped_ptr.hpp>

class TempDirectory;

class DataProxyServiceSystest : public CppUnit::TestFixture
{
private:
	CPPUNIT_TEST_SUITE( DataProxyServiceSystest );
	CPPUNIT_TEST( testHappyPath );
	CPPUNIT_TEST_SUITE_END();

public:
	DataProxyServiceSystest( void );
	virtual ~DataProxyServiceSystest( void );

	void setUp( void );
	void tearDown( void );

	void testHappyPath( void );

private:
	boost::scoped_ptr<TempDirectory> m_pTempDir;
};

#endif // __DATA_PROXY_SERVICE_SYSTEST_HPP__

ext: hpp

max_stars_repo_name: aol/DataProxyLibrary

max_issues_repo_name: aol/DataProxyLibrary

max_forks_repo_name: aol/DataProxyLibrary


text:
//==================================================================================================
/*!
  @file

  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/pack.hpp>
#include <boost/simd/function/expocvt.hpp>
#include <boost/simd/function/is_even.hpp>
#include <boost/simd/function/complement.hpp>
#include <boost/simd/meta/cardinal_of.hpp>
#include <boost/simd/detail/dispatch/meta/as_integer.hpp>
#include <simd_test.hpp>
#include <boost/simd/constant/minf.hpp>

template <typename T, std::size_t N, typename Env>
void test(Env& $)
{
  namespace bs = boost::simd;
  namespace bd = boost::dispatch;
  using p_t = bs::pack<T, N>;

  T a1[N];
  T b[N];
  for(std::size_t i = 0; i < N; ++i)
  {
     a1[i] = T(i+1);
     b[i]  = bs::expocvt(a1[i]);
   }
  p_t aa1(&a1[0], &a1[0]+N);
  p_t bb(&b[0], &b[0]+N);
  STF_EQUAL(bs::expocvt(aa1), bb);
}

STF_CASE_TPL("Check expocvt on pack",STF_IEEE_TYPES)
{
  namespace bs = boost::simd;
  using p_t = bs::pack<T>;
  static const std::size_t N = bs::cardinal_of<p_t>::value;
  test<T, N>($);
  test<T, N/2>($);
  test<T, N*2>($);
}

  namespace bs = boost::simd;
  namespace bd = boost::dispatch;

STF_CASE_TPL (" expocvt real",  STF_IEEE_TYPES)
{
  namespace bs = boost::simd;
  namespace bd = boost::dispatch;
  using iT = bd::as_integer_t<T>;
  using bs::expocvt;
  using p_t = bs::pack<T>;
  using r_t = decltype(expocvt(p_t()));

  // return type conformity test
  STF_TYPE_IS(r_t, p_t);

  // specific values tests

  for( iT i= bs::Minexponent<T>(); i < bs::Maxexponent<T>(); ++i)
  {
    p_t z1 = expocvt(p_t(i));
    STF_EQUAL(z1, p_t(std::ldexp(T(1), i)));
  }

} // end of test for floating_

max_stars_repo_name: nickporubsky/boost-simd-clone

max_issues_repo_name: nickporubsky/boost-simd-clone

max_forks_repo_name: nickporubsky/boost-simd-clone


text:
/*    Copyright (c) 2010-2019, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#define BOOST_TEST_MAIN

#include <limits>
#include <string>
#include <thread>

#include <boost/make_shared.hpp>
#include <boost/test/unit_test.hpp>

#include "Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h"
#include "Tudat/Mathematics/BasicMathematics/linearAlgebra.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h"

#include "Tudat/External/SpiceInterface/spiceInterface.h"
#include "Tudat/Mathematics/NumericalIntegrators/rungeKuttaCoefficients.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/accelerationModel.h"
#include "Tudat/InputOutput/basicInputOutput.h"
#include "Tudat/SimulationSetup/PropagationSetup/dynamicsSimulator.h"
#include "Tudat/SimulationSetup/EnvironmentSetup/defaultBodies.h"
#include "Tudat/SimulationSetup/EnvironmentSetup/createBodies.h"
#include "Tudat/SimulationSetup/EstimationSetup/createNumericalSimulator.h"
#include "Tudat/Mathematics/NumericalIntegrators/createNumericalIntegrator.h"

namespace tudat
{
namespace unit_tests
{

BOOST_AUTO_TEST_SUITE( test_encke_propagator )

// Test Encke propagator for point mass central body.
BOOST_AUTO_TEST_CASE( testEnckePopagatorForPointMassCentralBodies )
{
    // Test simulation for diffe  rent central body cases
    for( unsigned int simulationCase = 0; simulationCase < 2; simulationCase++ )
    {
        //Using declarations.
        using namespace tudat::interpolators;
        using namespace tudat::numerical_integrators;
        using namespace tudat::spice_interface;
        using namespace tudat::simulation_setup;
        using namespace tudat::basic_astrodynamics;
        using namespace tudat::orbital_element_conversions;
        using namespace tudat::propagators;

        //Load spice kernels.
        spice_interface::loadStandardSpiceKernels( );

        // Define bodies in simulation.
        unsigned int totalNumberOfBodies = 7;
        std::vector< std::string > bodyNames;
        bodyNames.resize( totalNumberOfBodies );
        bodyNames[ 0 ] = "Earth";
        bodyNames[ 1 ] = "Mars";
        bodyNames[ 2 ] = "Sun";
        bodyNames[ 3 ] = "Venus";
        bodyNames[ 4 ] = "Moon";
        bodyNames[ 5 ] = "Mercury";
        bodyNames[ 6 ] = "Jupiter";

        double initialEphemerisTime = 1.0E7;
        double finalEphemerisTime = 2.0E7;
        double maximumTimeStep = 3600.0;
        double buffer = 5.0 * maximumTimeStep;

        // Create bodies needed in simulation
        NamedBodyMap bodyMap = createBodies(
                    getDefaultBodySettings( bodyNames, initialEphemerisTime - buffer, finalEphemerisTime + buffer ) );
        setGlobalFrameBodyEphemerides( bodyMap, "SSB", "ECLIPJ2000" );

        // Set accelerations between bodies that are to be taken into account.
        SelectedAccelerationMap accelerationMap;
        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfEarth;
        accelerationsOfEarth[ "Sun" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );
        accelerationsOfEarth[ "Moon" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );
        accelerationsOfEarth[ "Jupiter" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );
        accelerationMap[ "Earth" ] = accelerationsOfEarth;

        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfMars;
        accelerationsOfMars[ "Sun" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );
        accelerationsOfMars[ "Earth" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );
        accelerationsOfMars[ "Jupiter" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );
        accelerationMap[ "Mars" ] = accelerationsOfMars;

        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfMoon;
        accelerationsOfMoon[ "Sun" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );
        accelerationsOfMoon[ "Earth" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );
        accelerationsOfMoon[ "Jupiter" ].push_back( std::make_shared< AccelerationSettings >( central_gravity ) );
        accelerationMap[ "Moon" ] = accelerationsOfMoon;

        // Propagate Earth, Mars and Moon
        std::vector< std::string > bodiesToPropagate;
        bodiesToPropagate.push_back( "Earth" );
        bodiesToPropagate.push_back( "Mars" );
        bodiesToPropagate.push_back( "Moon" );

        unsigned int numberOfNumericalBodies = bodiesToPropagate.size( );

        // Define central bodies: all Sun for simulationCase = 0, Earth and Mars: Sun, Moon: Earth for simulationCase = 1
        std::vector< std::string > centralBodies;
        std::map< std::string, std::string > centralBodyMap;
        centralBodies.resize( numberOfNumericalBodies );
        for( int i = 0; i < 3; i++ )
        {
            if( i == 2 && simulationCase == 1 )
            {
                centralBodies[ i ] = "Earth";
            }
            else
            {
                centralBodies[ i ] = "Sun";
            }
            centralBodyMap[ bodiesToPropagate[ i ] ] = centralBodies[ i ];
        }

        // Get initial states for bodies.
        Eigen::VectorXd systemInitialState = Eigen::VectorXd( bodiesToPropagate.size( ) * 6 );
        for( unsigned int i = 0; i < numberOfNumericalBodies ; i++ )
        {
            systemInitialState.segment( i * 6 , 6 ) =
                    bodyMap[ bodiesToPropagate[ i ] ]->getStateInBaseFrameFromEphemeris( initialEphemerisTime ) -
                    bodyMap[ centralBodies[ i ] ]->getStateInBaseFrameFromEphemeris( initialEphemerisTime );
        }

        // Create acceleratiuon models.
        AccelerationMap accelerationModelMap = createAccelerationModelsMap(
                    bodyMap, accelerationMap, centralBodyMap );

        // Create integrator settings.
        std::shared_ptr< IntegratorSettings< > > integratorSettings =
                std::make_shared< IntegratorSettings< > >
                ( rungeKutta4,
                  initialEphemerisTime, 250.0 );

        // Create propagation settings (Cowell)
        std::shared_ptr< TranslationalStatePropagatorSettings< double > > propagatorSettings =
                std::make_shared< TranslationalStatePropagatorSettings< double > >
                ( centralBodies, accelerationModelMap, bodiesToPropagate, systemInitialState, finalEphemerisTime );

        // Propagate orbit with Cowell method
        SingleArcDynamicsSimulator< double > dynamicsSimulator2(
                    bodyMap, integratorSettings, propagatorSettings, true, false, true );

        // Define ephemeris interrogation settings.
        double initialTestTime = initialEphemerisTime + 10.0 * maximumTimeStep;
        double finalTestTime = finalEphemerisTime - 10.0 * maximumTimeStep;
        double testTimeStep = 1.0E4;

        // Get resutls of Cowell integration at given times.
        double currentTestTime = initialTestTime;
        std::map< double, Eigen::Matrix< double, 18, 1 > > cowellIntegrationResults;
        while( currentTestTime < finalTestTime )
        {
            cowellIntegrationResults[ currentTestTime ].segment( 0, 6 ) =
                    bodyMap[ "Earth" ]->getStateInBaseFrameFromEphemeris( currentTestTime );
            cowellIntegrationResults[ currentTestTime ].segment( 6, 6 ) =
                    bodyMap[ "Mars" ]->getStateInBaseFrameFromEphemeris( currentTestTime );
            cowellIntegrationResults[ currentTestTime ].segment( 12, 6 ) =
                    bodyMap[ "Moon" ]->getStateInBaseFrameFromEphemeris( currentTestTime );

            currentTestTime += testTimeStep;
        }

        // Create propagation settings (Encke)
        propagatorSettings = std::make_shared< TranslationalStatePropagatorSettings< double > >
                ( centralBodies, accelerationModelMap, bodiesToPropagate, systemInitialState, finalEphemerisTime, encke );

        // Propagate orbit with Encke method
        SingleArcDynamicsSimulator< double > dynamicsSimulator(
                    bodyMap, integratorSettings, propagatorSettings, true, false, true );

        // Get resutls of Encke integration at given times.
        currentTestTime = initialTestTime;
        std::map< double, Eigen::Matrix< double, 18, 1 > > enckeIntegrationResults;
        while( currentTestTime < finalTestTime )
        {
            enckeIntegrationResults[ currentTestTime ].segment( 0, 6 ) =
                    bodyMap[ "Earth" ]->getStateInBaseFrameFromEphemeris( currentTestTime );
            enckeIntegrationResults[ currentTestTime ].segment( 6, 6 ) =
                    bodyMap[ "Mars" ]->getStateInBaseFrameFromEphemeris( currentTestTime );
            enckeIntegrationResults[ currentTestTime ].segment( 12, 6 ) =
                    bodyMap[ "Moon" ]->getStateInBaseFrameFromEphemeris( currentTestTime );
            currentTestTime += testTimeStep;
        }

        // Compare results of Cowell and Encke propagations
        std::map< double, Eigen::Matrix< double, 18, 1 > >::iterator enckeIterator = enckeIntegrationResults.begin( );
        std::map< double, Eigen::Matrix< double, 18, 1 > >::iterator cowellIterator = cowellIntegrationResults.begin( );
        for( unsigned int i = 0; i < enckeIntegrationResults.size( ); i++ )
        {
            for( int j= 0; j< 3; j++ )
            {
                BOOST_CHECK_SMALL( ( enckeIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 0.01 );
            }

            for( int j = 6; j < 9; j++ )
            {
                BOOST_CHECK_SMALL( ( enckeIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 0.01 );
            }

            for( int j = 12; j < 15; j++ )
            {
                BOOST_CHECK_SMALL( ( enckeIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 0.1 );
            }

            for( int j = 3; j < 6; j++ )
            {
                BOOST_CHECK_SMALL( ( enckeIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 1.0E-8 );
            }

            for( int j = 9; j < 12; j++ )
            {
                BOOST_CHECK_SMALL( ( enckeIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 1.0E-8 );

            }

            for( int j = 15; j < 18; j++ )
            {
                BOOST_CHECK_SMALL( ( enckeIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 1.0E-6 );

            }
            enckeIterator++;
            cowellIterator++;
        }
    }
}

// Test Encke propagator for point mass, and spherical harmonics central body.
BOOST_AUTO_TEST_CASE( testEnckePopagatorForSphericalHarmonicCentralBodies )
{
    for( unsigned int simulationCase = 0; simulationCase < 4; simulationCase++ )
    {
        using namespace tudat;
        using namespace simulation_setup;
        using namespace propagators;
        using namespace numerical_integrators;
        using namespace orbital_element_conversions;
        using namespace basic_mathematics;
        using namespace gravitation;
        using namespace numerical_integrators;

        // Load Spice kernels.
        spice_interface::loadStandardSpiceKernels( );

        // Set simulation time settings.
        const double simulationStartEpoch = 0.0;
        const double simulationEndEpoch = tudat::physical_constants::JULIAN_DAY;

        // Define body settings for simulation.
        std::vector< std::string > bodiesToCreate;
        bodiesToCreate.push_back( "Sun" );
        bodiesToCreate.push_back( "Earth" );
        bodiesToCreate.push_back( "Moon" );
        bodiesToCreate.push_back( "Mars" );
        bodiesToCreate.push_back( "Venus" );

        // Create body objects.
        std::map< std::string, std::shared_ptr< BodySettings > > bodySettings =
                getDefaultBodySettings( bodiesToCreate, simulationStartEpoch - 300.0, simulationEndEpoch + 300.0 );
        for( unsigned int i = 0; i < bodiesToCreate.size( ); i++ )
        {
            bodySettings[ bodiesToCreate.at( i ) ]->ephemerisSettings->resetFrameOrientation( "J2000" );
            bodySettings[ bodiesToCreate.at( i ) ]->rotationModelSettings->resetOriginalFrame( "J2000" );
        }
        NamedBodyMap bodyMap = createBodies( bodySettings );

        // Create spacecraft object.
        bodyMap[ "Vehicle" ] = std::make_shared< simulation_setup::Body >( );
        bodyMap[ "Vehicle" ]->setConstantBodyMass( 400.0 );
        bodyMap[ "Vehicle" ]->setEphemeris( std::make_shared< ephemerides::TabulatedCartesianEphemeris< > >(
                                                std::shared_ptr< interpolators::OneDimensionalInterpolator
                                                < double, Eigen::Vector6d  > >( ), "Earth", "J2000" ) );
        std::shared_ptr< RadiationPressureInterfaceSettings > vehicleRadiationPressureSettings =
                std::make_shared< CannonBallRadiationPressureInterfaceSettings >(
                    "Sun", 4.0, 1.2, std::vector< std::string >{ "Earth", "Moon" } );
        bodyMap[ "Vehicle" ]->setRadiationPressureInterface(
                    "Sun", createRadiationPressureInterface(
                        vehicleRadiationPressureSettings, "Vehicle", bodyMap ) );

        // Finalize body creation.
        setGlobalFrameBodyEphemerides( bodyMap, "SSB", "J2000" );

        // Define propagator settings variables.
        SelectedAccelerationMap accelerationMap;
        std::vector< std::string > bodiesToPropagate;
        std::vector< std::string > centralBodies;

        // Define propagation settings.
        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfVehicle;

        // Use only central gravity for Earth
        if( simulationCase < 2 )
        {
            accelerationsOfVehicle[ "Earth" ].push_back( std::make_shared< AccelerationSettings >(
                                                             basic_astrodynamics::central_gravity ) );
        }
        // Use spherical harmonics for Earth
        else
        {
            accelerationsOfVehicle[ "Earth" ].push_back(
                        std::make_shared< SphericalHarmonicAccelerationSettings >( 5, 5 ) );

        }

        // Use perturbations other than Earth gravity
        if( simulationCase % 2 == 0 )
        {
            accelerationsOfVehicle[ "Sun" ].push_back( std::make_shared< AccelerationSettings >(
                                                           basic_astrodynamics::central_gravity ) );
            accelerationsOfVehicle[ "Moon" ].push_back( std::make_shared< AccelerationSettings >(
                                                            basic_astrodynamics::central_gravity ) );
            accelerationsOfVehicle[ "Mars" ].push_back( std::make_shared< AccelerationSettings >(
                                                            basic_astrodynamics::central_gravity ) );
            accelerationsOfVehicle[ "Venus" ].push_back( std::make_shared< AccelerationSettings >(
                                                             basic_astrodynamics::central_gravity ) );
            accelerationsOfVehicle[ "Sun" ].push_back( std::make_shared< AccelerationSettings >(
                                                           basic_astrodynamics::cannon_ball_radiation_pressure ) );
        }
        accelerationMap[ "Vehicle" ] = accelerationsOfVehicle;
        bodiesToPropagate.push_back( "Vehicle" );
        centralBodies.push_back( "Earth" );
        basic_astrodynamics::AccelerationMap accelerationModelMap = createAccelerationModelsMap(
                    bodyMap, accelerationMap, bodiesToPropagate, centralBodies );

        // Set Keplerian elements for Vehicle.
        Eigen::Vector6d vehicleInitialStateInKeplerianElements;
        vehicleInitialStateInKeplerianElements( semiMajorAxisIndex ) = 8000.0E3;
        vehicleInitialStateInKeplerianElements( eccentricityIndex ) = 0.1;
        vehicleInitialStateInKeplerianElements( inclinationIndex ) = unit_conversions::convertDegreesToRadians( 85.3 );
        vehicleInitialStateInKeplerianElements( argumentOfPeriapsisIndex )
                = unit_conversions::convertDegreesToRadians( 235.7 );
        vehicleInitialStateInKeplerianElements( longitudeOfAscendingNodeIndex )
                = unit_conversions::convertDegreesToRadians( 23.4 );
        vehicleInitialStateInKeplerianElements( trueAnomalyIndex ) = unit_conversions::convertDegreesToRadians( 139.87 );

        double earthGravitationalParameter = bodyMap.at( "Earth" )->getGravityFieldModel( )->getGravitationalParameter( );
        const Eigen::Vector6d vehicleInitialState = convertKeplerianToCartesianElements(
                    vehicleInitialStateInKeplerianElements, earthGravitationalParameter );

        // Define propagator settings (Cowell)
        std::shared_ptr< TranslationalStatePropagatorSettings< double > > propagatorSettings =
                std::make_shared< TranslationalStatePropagatorSettings< double > >
                ( centralBodies, accelerationModelMap, bodiesToPropagate, vehicleInitialState, simulationEndEpoch );

        // Define integrator settings.
        const double fixedStepSize = 5.0;
        std::shared_ptr< IntegratorSettings< > > integratorSettings =
                std::make_shared< IntegratorSettings< > >
                ( rungeKutta4, 0.0, fixedStepSize );

        // Propagate orbit with Cowell method
        SingleArcDynamicsSimulator< double > dynamicsSimulator2(
                    bodyMap, integratorSettings, propagatorSettings, true, false, true );

        // Define ephemeris interrogation settings.
        double initialTestTime = simulationStartEpoch + 10.0 * fixedStepSize;
        double finalTestTime = simulationEndEpoch - 10.0 * fixedStepSize;
        double testTimeStep = 1.0E4;

        // Get resutls of Cowell integration at given times.
        double currentTestTime = initialTestTime;
        std::map< double, Eigen::Matrix< double, 6, 1 > > cowellIntegrationResults;
        while( currentTestTime < finalTestTime )
        {
            cowellIntegrationResults[ currentTestTime ].segment( 0, 6 ) =
                    bodyMap[ "Vehicle" ]->getEphemeris( )->getCartesianState( currentTestTime );

            currentTestTime += testTimeStep;
        }

        // Create propagation settings (Encke)
        propagatorSettings = std::make_shared< TranslationalStatePropagatorSettings< double > >
                ( centralBodies, accelerationModelMap, bodiesToPropagate, vehicleInitialState, simulationEndEpoch, encke );

        // Propagate orbit with Encke method
        SingleArcDynamicsSimulator< double > dynamicsSimulator(
                    bodyMap, integratorSettings, propagatorSettings, true, false, true );

        // Get resutls of Encke integration at given times.
        currentTestTime = initialTestTime;
        std::map< double, Eigen::Matrix< double, 6, 1 > > enckeIntegrationResults;
        while( currentTestTime < finalTestTime )
        {
            enckeIntegrationResults[ currentTestTime ].segment( 0, 6 ) =
                    bodyMap[ "Vehicle" ]->getEphemeris( )->getCartesianState( currentTestTime );
            currentTestTime += testTimeStep;
        }

        // Compare results of Cowell and Encke propagations
        std::map< double, Eigen::Matrix< double, 6, 1 > >::iterator enckeIterator = enckeIntegrationResults.begin( );
        std::map< double, Eigen::Matrix< double, 6, 1 > >::iterator cowellIterator = cowellIntegrationResults.begin( );
        for( unsigned int i = 0; i < enckeIntegrationResults.size( ); i++ )
        {
            for( int j= 0; j< 3; j++ )
            {
                BOOST_CHECK_SMALL( ( enckeIterator->second - cowellIterator->second )( j ), 0.02 );
            }

            for( int j = 3; j < 6; j++ )
            {
                BOOST_CHECK_SMALL( ( enckeIterator->second - cowellIterator->second )( j ), 1.0E-5 );

            }
            enckeIterator++;
            cowellIterator++;
        }
    }
}

//! test if Encke propagator works properly for high eccentricities. Test if the propagation continmues unimpeded for
//! large eccentricities (was found to fail in rpevious version due to no convergence of root finder
BOOST_AUTO_TEST_CASE( testEnckePopagatorForHighEccentricities )
{
    using namespace tudat;
    using namespace simulation_setup;
    using namespace propagators;
    using namespace numerical_integrators;
    using namespace orbital_element_conversions;
    using namespace basic_mathematics;
    using namespace gravitation;
    using namespace numerical_integrators;
    using namespace unit_conversions;

    std::vector< double > testEccentricities;
    testEccentricities.push_back( 0.8 );
    testEccentricities.push_back( 0.9 );
    testEccentricities.push_back( 0.95 );
    testEccentricities.push_back( 0.99 );

    for( unsigned testCase = 0; testCase < testEccentricities.size( ); testCase++ )
    {
        // Set simulation end epoch.
        const double simulationEndEpoch = 2.0 * tudat::physical_constants::JULIAN_DAY;

        // Set numerical integration fixed step size.
        const double fixedStepSize = 15.0;

        // Define body settings for simulation.
        std::map< std::string, std::shared_ptr< BodySettings > > bodySettings;
        bodySettings[ "Earth" ] = std::make_shared< BodySettings >( );
        bodySettings[ "Earth" ]->ephemerisSettings = std::make_shared< ConstantEphemerisSettings >(
                    Eigen::Vector6d::Zero( ), "SSB", "J2000" );
        bodySettings[ "Earth" ]->gravityFieldSettings = std::make_shared< GravityFieldSettings >( central_spice );

        // Create Earth object
        NamedBodyMap bodyMap = createBodies( bodySettings );

        // Create spacecraft object.
        bodyMap[ "Asterix" ] = std::make_shared< simulation_setup::Body >( );

        // Finalize body creation.
        setGlobalFrameBodyEphemerides( bodyMap, "SSB", "J2000" );

        // Define propagator settings variables.
        SelectedAccelerationMap accelerationMap;
        std::vector< std::string > bodiesToPropagate;
        std::vector< std::string > centralBodies;

        // Define propagation settings.
        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfAsterix;
        accelerationsOfAsterix[ "Earth" ].push_back( std::make_shared< AccelerationSettings >(
                                                         basic_astrodynamics::central_gravity ) );
        accelerationMap[ "Asterix" ] = accelerationsOfAsterix;
        bodiesToPropagate.push_back( "Asterix" );
        centralBodies.push_back( "Earth" );

        // Create acceleration models and propagation settings.
        basic_astrodynamics::AccelerationMap accelerationModelMap = createAccelerationModelsMap(
                    bodyMap, accelerationMap, bodiesToPropagate, centralBodies );

        // Set Keplerian elements for Asterix.
        Eigen::Vector6d asterixInitialStateInKeplerianElements;
        asterixInitialStateInKeplerianElements( semiMajorAxisIndex ) = 7500.0E3;
        asterixInitialStateInKeplerianElements( eccentricityIndex ) = testEccentricities.at( testCase );
        asterixInitialStateInKeplerianElements( inclinationIndex ) = convertDegreesToRadians( 85.3 );
        asterixInitialStateInKeplerianElements( argumentOfPeriapsisIndex )
                = convertDegreesToRadians( 235.7 );
        asterixInitialStateInKeplerianElements( longitudeOfAscendingNodeIndex )
                = convertDegreesToRadians( 23.4 );
        asterixInitialStateInKeplerianElements( trueAnomalyIndex ) = convertDegreesToRadians( 139.87 );

        // Convert Asterix state from Keplerian elements to Cartesian elements.
        double earthGravitationalParameter = bodyMap.at( "Earth" )->getGravityFieldModel( )->getGravitationalParameter( );
        Eigen::VectorXd systemInitialState = convertKeplerianToCartesianElements(
                    asterixInitialStateInKeplerianElements,
                    earthGravitationalParameter );

        TranslationalPropagatorType propagatorType = encke;
        std::shared_ptr< TranslationalStatePropagatorSettings< double > > propagatorSettings =
                std::make_shared< TranslationalStatePropagatorSettings< double > >
                ( centralBodies, accelerationModelMap, bodiesToPropagate, systemInitialState, simulationEndEpoch, propagatorType);

        std::shared_ptr< IntegratorSettings< > > integratorSettings =
                std::make_shared< RungeKuttaVariableStepSizeSettings< > >
                ( 0.0, fixedStepSize,
                  RungeKuttaCoefficients::rungeKuttaFehlberg78, 1.0E-4, 3600.0, 1.0E-14, 1.0E-14 );

        // Create simulation object and propagate dynamics.
        SingleArcDynamicsSimulator< > dynamicsSimulator(
                    bodyMap, integratorSettings, propagatorSettings, true, false, false );
        std::map< double, Eigen::VectorXd > integrationResult = dynamicsSimulator.getEquationsOfMotionNumericalSolution( );

        // Check if orbit is properly propagated
        Eigen::VectorXd analyticalSolution;
        double finalTime = integrationResult.rbegin( )->first;

        // Check if final time is correctly reached
        BOOST_CHECK_EQUAL( simulationEndEpoch <=  finalTime, true );

        // Loosen velocity tolerance for high eccentricity
        double toleranceMultiplier = ( testCase > 2 ) ? 100.0 : 1.0;

        // Compare propagated orbit against numerical result.
        for( std::map< double, Eigen::VectorXd >::const_iterator resultIterator = integrationResult.begin( );
             resultIterator != integrationResult.end( ); resultIterator++ )
        {
            analyticalSolution = convertKeplerianToCartesianElements( propagateKeplerOrbit(
                        asterixInitialStateInKeplerianElements, resultIterator->first, earthGravitationalParameter ),
                                         earthGravitationalParameter );
            for( unsigned int i = 0; i < 3; i++ )
            {
                BOOST_CHECK_SMALL( std::fabs( analyticalSolution( i ) - resultIterator->second( i ) ), 1.0E-2 );
                BOOST_CHECK_SMALL( std::fabs( analyticalSolution( i  + 3 ) - resultIterator->second( i + 3  ) ),
                                   toleranceMultiplier * 5.0E-6 );

            }
        }
    }

}
BOOST_AUTO_TEST_SUITE_END( )

}

}

max_stars_repo_name: sebranchett/tudat

max_issues_repo_name: sebranchett/tudat

max_forks_repo_name: sebranchett/tudat


text:
/*
 This program is free software; you can redistribute it and/or modify it under
 the terms of the European Union Public Licence - EUPL v.1.1 as published by
 the European Commission.

 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 European Union Public Licence - EUPL v.1.1
 for more details.

 You should have received a copy of the European Union Public Licence - EUPL v.1.1
 along with this program.

 Further information about the European Union Public Licence - EUPL v.1.1 can
 also be found on the world wide web at http://ec.europa.eu/idabc/eupl

*/

/*
 ------ Copyright (C) 2011 STA Steering Board (space.trajectory.analysis AT gmail.com) ----
*/
/*
------------------ Author: Guillermo Ortega  ----------------------------------------
 May 2011

 */

#include "serviceDistanceRateUnit.h"

#include <Eigen/Core>

using namespace Eigen;

#include "QDebug"

DialogServiceDistanceRateUnitFrame::DialogServiceDistanceRateUnitFrame( QWidget * parent, Qt::WindowFlags f) : QFrame(parent,f)
{
	setupUi(this);
    distanceRateUnitWidget = DialogServiceDistanceRateUnitFrame::comboBoxDistanceRateUnitsChoice;
    myPastUnits = 0;
    comboBoxDistanceRateUnitsChoice->setCurrentIndex(myPastUnits);
}

DialogServiceDistanceRateUnitFrame::~DialogServiceDistanceRateUnitFrame()
{
}

// Index meaning is as follows:
// index = 0  is Kilometers/s
// index = 1  is meters/s
// index = 2  is centi-meters/s
// index = 3  is mili-meters/s
// index = 4 is Astronomical Units/s

// Matrix coefficients as follows
//  Km->Km, Km->m, Km->cm, Km->mm, Km->AU,
//  m->Km,   m->m,  m->cm,  m->mm,  m->AU,
//  cm->Km, cm->m, cm->cm, cm->mm, cm-> AU,
//  mm->Km, mm->m, mm->cm, mm->mm, mm->AU,
//  AU->Km, AU->m, AU->cm, AU->mm, AU->AU
// The matrice has to be transposed !!

static double distanceRateConversionMatrixCoeffs[25] =
{1.0,            0.001,           0.00001,        0.000001,       1.495978707e+08,
 1000.0,         1.0,             0.01,           0.001,          1.495978707e+11,
 100000.0,       100.0,           1.0,            0.1,            1.495978707e+13,
 1000000.0,      1000.0,          10.0,           1.0,            1.495978707e+14,
 0.6684587e-19,  0.6684587e-12,   0.6684587e-13,  0.6684587e-16,  1.0};

static const Matrix<double, 5, 5> distanceRateConversionMatrix(distanceRateConversionMatrixCoeffs);

double DialogServiceDistanceRateUnitFrame::convertDistanceRate(int fromDistanceRateUnit, int toDistanceRateUnit, double distance)
{
    double finalDistanceRate = distance * distanceRateConversionMatrix(fromDistanceRateUnit, toDistanceRateUnit);
    return finalDistanceRate;
}

//// Sets the input distance, the output distance and the current index inside the method
void DialogServiceDistanceRateUnitFrame::setInputDistanceRate(double niceInputDistanceRate)
{
    myPastDistanceRate = niceInputDistanceRate;
}

// Index meaning is as follows:
// index = 0  is Kilometers/s
// index = 1  is meters/s
// index = 2  is centi-meters/s
// index = 3  is mili-meters/s
// index = 4 is Astronomical Units/s
void DialogServiceDistanceRateUnitFrame::on_comboBoxDistanceRateUnitsChoice_currentIndexChanged(int myIndex)
{
    myFutureUnits = myIndex;
    myFutureDistanceRate = convertDistanceRate(myPastUnits, myFutureUnits, myPastDistanceRate);
    myPastDistanceRate = myFutureDistanceRate;
    myPastUnits = myFutureUnits;
    myRealDistanceRateForXMLSchema = convertDistanceRate (myPastUnits, 0, myFutureDistanceRate);
}

max_stars_repo_name: hoehnp/SpaceDesignTool

max_issues_repo_name: hoehnp/SpaceDesignTool

max_forks_repo_name: hoehnp/SpaceDesignTool


text:
#include <iostream>
#include <rw/rw.hpp>
#include <rw/loaders/model3d/STLFile.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/option.hpp>
#include <boost/program_options/parsers.hpp>
#include "JawPrimitive.hpp"

using namespace std;

USE_ROBWORK_NAMESPACE;
using namespace robwork;
using namespace boost::program_options;
namespace po = boost::program_options;

int main(int argc, char* argv[])
{
	Q params(10, 0, 0.1, 0.025, 0.02, 0, 0*Deg2Rad, 0, 0, 90*Deg2Rad, 0.0);

	options_description desc("Allowed options");
	desc.add_options()
		("help,h", "help message")
		("length,l", value<double>(), "length of gripper")
		("width,w", value<double>(), "width of gripper")
		("depth,d", value<double>(), "depth of gripper")
		("adepth,c", value<double>(), "depth of chamfer")
		("aangle,x", value<double>(), "angle of chamfer")
		("cpos,p", value<double>(), "cut position")
		("cdepth,v", value<double>(), "cut depth")
		("cangle,a", value<double>(), "cut angle")
	;

	variables_map vm;
	store(po::parse_command_line(argc, argv, desc), vm);
	notify(vm);

	if (vm.count("help")) {
		cout << desc << endl;
		return 1;
	}

	if (vm.count("length")) params[0] = vm["length"].as<double>();
	if (vm.count("width")) params[1] = vm["width"].as<double>();
	if (vm.count("depth")) params[2] = vm["depth"].as<double>();
	if (vm.count("adepth")) params[3] = vm["adepth"].as<double>();
	if (vm.count("aangle")) params[4] = Deg2Rad*vm["aangle"].as<double>();
	if (vm.count("cpos")) params[5] = vm["cpos"].as<double>();
	if (vm.count("cdepth")) params[6] = vm["cdepth"].as<double>();
	if (vm.count("cangle")) params[7] = Deg2Rad*vm["cangle"].as<double>();

	//cout << params[1] << endl;

	//JawPrimitive::Ptr jaw = ownedPtr(new JawPrimitive(params));
	JawPrimitive jaw(params);

	TriMesh::Ptr mesh = jaw.createMesh(0);
	STLFile::save(*mesh, "left.stl");
	STLFile::save(*mesh, "right.stl");

	return 0;
}


text:
//==============================================================================
//         Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 & onward LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_CONSTANT_REGISTER_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_REGISTER_HPP_INCLUDED

/*!
 * \file
 * \brief Defines the BOOST_SIMD_CONSTANT_REGISTER_VALUE macro
 */

#include <boost/simd/meta/int_c.hpp>
#include <boost/simd/meta/float.hpp>
#include <boost/simd/meta/double.hpp>

//==============================================================================
/*!
 * Generate a named constant from an integral, float and double value set
 * and a default type
 * \param TAG    ID of the constant to generate
 * \param TYPE   Default type of the constant
 * \param INT    Integral value of the constant
 * \param FLOAT  Float value of the constant
 * \param DOUBLE Double value of the constant
 */
//==============================================================================
#if defined(DOXYGEN_ONLY)
#define BOOST_SIMD_CONSTANT_REGISTER(TAG,TYPE,INT,FLOAT,DOUBLE) \
struct TAG  : boost::simd::ext::pure_constant_<TAG>             \
{                                                               \
  typedef boost::simd::ext::pure_constant_<TAG> parent;         \
  typedef TYPE default_type;                                    \
};                                                              \
/**/
#else
#define BOOST_SIMD_CONSTANT_REGISTER(TAG,TYPE,INT,FLOAT,DOUBLE)             \
struct TAG : boost::simd::ext::pure_constant_<TAG>                          \
{                                                                           \
  typedef boost::simd::ext::pure_constant_<TAG> parent;                     \
  typedef TYPE default_type;                                                \
  template<class T, class D=void> struct apply                              \
    : boost::simd::meta::int_c<typename T::type,typename T::type(INT)> {};  \
                                                                            \
  template<class... Args>                                                   \
  static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)     \
  BOOST_AUTO_DECLTYPE_BODY( BOOST_PP_CAT(dispatching_, TAG)( ext::adl_helper(), static_cast<Args&&>(args)... ) ) \
};                                                                          \
template<class T, class D>                                                  \
struct  TAG::apply<boost::dispatch::meta::single_<T>,D>                     \
      : boost::simd::meta::single_<FLOAT> {};                               \
template<class T, class D>                                                  \
struct  TAG::apply<boost::dispatch::meta::double_<T>,D>                     \
      : boost::simd::meta::double_<DOUBLE> {};                              \
/**/
#endif

#endif


text:
// MIT License

// Copyright (c) 2021 Daniel Kowalczyk

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

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

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

#ifndef NODE_DURATION_HPP
#define NODE_DURATION_HPP

#include <gurobi_c++.h>                             // for GRBVar
#include <array>                                    // for array
#include <boost/dynamic_bitset/dynamic_bitset.hpp>  // for dynamic_bitset
#include <boost/multiprecision/cpp_int.hpp>         // for cpp_int
#include <cstddef>                                  // for size_t
#include <memory>                                   // for allocator, shared...
#include <ostream>                                  // for operator<<, ostream
#include <range/v3/algorithm/any_of.hpp>            // for any_of
#include <range/v3/algorithm/max.hpp>               // for max, max_fn
#include <range/v3/functional/arithmetic.hpp>       // for plus
#include <range/v3/functional/comparisons.hpp>      // for less
#include <range/v3/functional/identity.hpp>         // for identity
#include <range/v3/numeric/accumulate.hpp>          // for accumulate, accum...
#include <vector>                                   // for vector
#include "BddCoeff.hpp"                             // for BddCoeff
#include "Job.h"                                    // for Job
#include "Label.hpp"                                // for Label
#include "ModernDD/NodeBase.hpp"                    // for NodeBase
#include "ModernDD/NodeId.hpp"                      // for NodeId

class NodeBdd : public NodeBase {
   public:
    using dbl_array = std::array<double, 2>;
    using int_array = std::array<int, 2>;
    using size_t_array [[maybe_unused]] = std::array<size_t, 2>;
    using bool_array = std::array<bool, 2>;
    using grb_array = std::array<GRBVar, 2>;
    using big_int = boost::multiprecision::cpp_int;
    using weak_ptr_nodeid = std::weak_ptr<NodeId>;
    using weak_ptr_bddcoeff = std::weak_ptr<BddCoeff>;

   private:
    /** Job chatacteristics */
    Job*   job{nullptr};
    size_t weight{};
    size_t key{};
    size_t key_model{};

    bool   visited{false};
    NodeId ptr_node_id{};

    /** Calculation jobs */
    boost::dynamic_bitset<> all{};

    /** original model data */
    dbl_array lp_x{0.0, 0.0};
    dbl_array cost{0.0, 0.0};
    dbl_array best_sol_x{0.0, 0.0};
    dbl_array reduced_cost{0.0, 0.0};

    std::array<std::vector<weak_ptr_bddcoeff>, 2> coeff_list{};

    /** Evaluation of backward distance */
    int_array backward_distance{};

    /** Evaluation nb_paths */
    big_int nb_paths{};

    /** Reducing size of decision diagram */
    bool_array calc{true, true};

    /** Searching equivalent paths */
    int_array in_degree{};

    /** Zero-Half cuts formulation variables */
    bool                               lp_visited{false};
    std::array<std::vector<size_t>, 2> in_edges{};
    std::array<size_t, 2>              key_edges{};
    dbl_array                          coeff_cut{0.0, 0.0};
    grb_array                          y{};
    grb_array                          r{};
    GRBVar                             sigma{};

   public:
    std::array<Label<NodeBdd>, 2> forward_label{};
    std::array<Label<NodeBdd>, 2> backward_label{};

    /**
     * Constructor
     */
    NodeBdd() = default;
    NodeBdd(size_t i, size_t j) : NodeBase(i, j) {}

    NodeBdd(const NodeBdd& src) = default;
    NodeBdd(NodeBdd&& src) noexcept = default;
    ~NodeBdd() = default;

    auto operator=(const NodeBdd& src) -> NodeBdd& = default;
    auto operator=(NodeBdd&& src) noexcept -> NodeBdd& = default;

    void               set_weight(int _weight);
    [[nodiscard]] auto get_weight() const -> size_t;

    [[nodiscard]] auto get_job() const -> Job*;
    [[nodiscard]] auto get_nb_job() const -> size_t;
    void               set_job(Job* _job);

    void add_coeff_list(const std::shared_ptr<BddCoeff>& ptr, bool high);
    void add_coeff_list_clear();
    auto get_coeff_list() -> std::array<std::vector<weak_ptr_bddcoeff>, 2>&;

    auto operator!=(NodeBdd const& o) const -> bool;

    friend auto operator<<(std::ostream& os, NodeBdd const& o) -> std::ostream&;

    void init_node(size_t                _weight,
                   [[maybe_unused]] bool _root_node = false,
                   bool                  _terminal_node = false);

    void set_node_id_label(const NodeId& _id);

    void set_job_label(Job* _job);

    auto operator<=>(const NodeBdd& rhs);

    /** Functions concerning reduced_cost */
    auto get_reduced_cost() -> dbl_array&;
    void reset_reduced_costs();
    void reset_reduced_costs_farkas();
    void adjust_reduced_costs(double _x, bool high);

    /** Functions concerning ptr_node_id */
    void set_ptr_node_id(size_t i, size_t j);
    void set_ptr_node_id(const NodeId& _node_id);
    auto get_ptr_node_id() -> NodeId&;
    void reset_ptr_node_id();

    /** Functions for manipulation of nb_paths */
    auto get_nb_paths() -> big_int&;
    void reset_nb_paths();
    void update_nb_paths(const big_int& x = 1);

    /** Functions for manipulation of visited */
    void               reset_visited();
    void               update_visited();
    [[nodiscard]] auto get_visited() const -> bool;

    /** Functions for manipulation of key */
    void set_key(const size_t& _key);
    auto get_key() -> size_t&;

    void set_key_model(const size_t& _key);
    auto get_key_model() -> size_t&;
    /** Functions for manipulation of lp_visited */
    void               update_lp_visited(bool _update);
    [[nodiscard]] auto get_lp_visited() const -> bool;

    /** Functions for manipulation of lp_x */
    [[nodiscard]] auto get_lp_x() -> dbl_array&;
    auto               get_lp_x(bool _high) -> double&;

    void update_lp_x(double _x, bool _high);

    void reset_lp_x();

    /** Functions for manipulation of cost */
    void set_cost(double _cost);

    /** Functions for manipulation of best_sol_x */
    void update_best_sol_x(bool _high);
    auto get_best_sol_x(bool _high) -> double;

    /** Functions for manipulation of backward distance */
    void reset_backward_distance(int _x = 0);
    void update_backward_distance(const std::array<int, 2>& _backward_distance,
                                  bool                      _high);

    auto get_backward_distance() -> int_array&;

    /** Functions for manipulation of all */
    void reset_all(size_t _nb_elements);

    auto get_all() -> boost::dynamic_bitset<>&;

    void intersect_all(const boost::dynamic_bitset<>& _set);
    void union_all(const boost::dynamic_bitset<>& _set);
    void add_element(size_t _element);
    auto is_element(size_t _element) -> bool;
    auto all_is_empty() -> bool;
    auto get_first_all() -> size_t;
    auto get_next_all(size_t _index) -> size_t;

    /** Functions for manipulation of calc */
    void reset_calc();
    auto any_of_calc() -> bool;

    auto get_calc(bool _high) -> bool;

    void update_calc(bool _high, bool _update = false);

    /** Functions for manipulation of in_degree */
    auto get_in_degree(bool _high) -> int;

    void update_in_degree(bool _high);

    auto alternative_paths() -> bool;

    void reset_in_degree();

    /** Functions for manipulation of Zero-Half cuts formulation cut problem */
    void reset_in_edges();

    auto get_in_edges(bool _high) -> std::vector<size_t>&;
    void add_in_edge(bool _high, size_t _key_parent);

    void set_key_edge(bool _high, size_t _key);

    auto get_key_edge(bool _high) -> size_t&;

    void reset_coeff_cut();
    void reset_coeff_cut(bool _high);

    void update_coeff_cut(bool _high);

    void reduce_coeff_cut(bool _high);

    auto get_coeff_cut(bool _high) -> double;

    auto get_y() -> grb_array&;
    auto get_r() -> grb_array&;
    void set_sigma(GRBVar&& _sigma);
    auto get_sigma() -> GRBVar&;
};

#endif  // NODE_DURATION_HPP


text:
#include "JoinSplit.hpp"
#include "prf.h"
#include "sodium.h"

#include "arnak/util.h"

#include <memory>

#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/optional.hpp>
#include <fstream>
#include "tinyformat.h"
#include "sync.h"
#include "amount.h"

#include "librustzcash.h"
#include "streams.h"
#include "version.h"

namespace libzcash {

static CCriticalSection cs_ParamsIO;

template<size_t NumInputs, size_t NumOutputs>
class JoinSplitCircuit : public JoinSplit<NumInputs, NumOutputs> {
public:
    JoinSplitCircuit() {}
    ~JoinSplitCircuit() {}

    SproutProof prove(
        const std::array<JSInput, NumInputs>& inputs,
        const std::array<JSOutput, NumOutputs>& outputs,
        std::array<SproutNote, NumOutputs>& out_notes,
        std::array<ZCNoteEncryption::Ciphertext, NumOutputs>& out_ciphertexts,
        uint256& out_ephemeralKey,
        const uint256& joinSplitPubKey,
        uint256& out_randomSeed,
        std::array<uint256, NumInputs>& out_macs,
        std::array<uint256, NumInputs>& out_nullifiers,
        std::array<uint256, NumOutputs>& out_commitments,
        uint64_t vpub_old,
        uint64_t vpub_new,
        const uint256& rt,
        bool computeProof,
        uint256 *out_esk // Payment disclosure
    ) {
        if (vpub_old > MAX_MONEY) {
            throw std::invalid_argument("nonsensical vpub_old value");
        }

        if (vpub_new > MAX_MONEY) {
            throw std::invalid_argument("nonsensical vpub_new value");
        }

        uint64_t lhs_value = vpub_old;
        uint64_t rhs_value = vpub_new;

        for (size_t i = 0; i < NumInputs; i++) {
            // Sanity checks of input
            {
                // If note has nonzero value
                if (inputs[i].note.value() != 0) {
                    // The witness root must equal the input root.
                    if (inputs[i].witness.root() != rt) {
                        throw std::invalid_argument("joinsplit not anchored to the correct root");
                    }

                    // The tree must witness the correct element
                    if (inputs[i].note.cm() != inputs[i].witness.element()) {
                        throw std::invalid_argument("witness of wrong element for joinsplit input");
                    }
                }

                // Ensure we have the key to this note.
                if (inputs[i].note.a_pk != inputs[i].key.address().a_pk) {
                    throw std::invalid_argument("input note not authorized to spend with given key");
                }

                // Balance must be sensical
                if (inputs[i].note.value() > MAX_MONEY) {
                    throw std::invalid_argument("nonsensical input note value");
                }

                lhs_value += inputs[i].note.value();

                if (lhs_value > MAX_MONEY) {
                    throw std::invalid_argument("nonsensical left hand size of joinsplit balance");
                }
            }

            // Compute nullifier of input
            out_nullifiers[i] = inputs[i].nullifier();
        }

        // Sample randomSeed
        out_randomSeed = random_uint256();

        // Compute h_sig
        uint256 h_sig = this->h_sig(out_randomSeed, out_nullifiers, joinSplitPubKey);

        // Sample phi
        uint252 phi = random_uint252();

        // Compute notes for outputs
        for (size_t i = 0; i < NumOutputs; i++) {
            // Sanity checks of output
            {
                if (outputs[i].value > MAX_MONEY) {
                    throw std::invalid_argument("nonsensical output value");
                }

                rhs_value += outputs[i].value;

                if (rhs_value > MAX_MONEY) {
                    throw std::invalid_argument("nonsensical right hand side of joinsplit balance");
                }
            }

            // Sample r
            uint256 r = random_uint256();

            out_notes[i] = outputs[i].note(phi, r, i, h_sig);
        }

        if (lhs_value != rhs_value) {
            throw std::invalid_argument("invalid joinsplit balance");
        }

        // Compute the output commitments
        for (size_t i = 0; i < NumOutputs; i++) {
            out_commitments[i] = out_notes[i].cm();
        }

        // Encrypt the ciphertexts containing the note
        // plaintexts to the recipients of the value.
        {
            ZCNoteEncryption encryptor(h_sig);

            for (size_t i = 0; i < NumOutputs; i++) {
                SproutNotePlaintext pt(out_notes[i], outputs[i].memo);

                out_ciphertexts[i] = pt.encrypt(encryptor, outputs[i].addr.pk_enc);
            }

            out_ephemeralKey = encryptor.get_epk();

            // !!! Payment disclosure START
            if (out_esk != nullptr) {
                *out_esk = encryptor.get_esk();
            }
            // !!! Payment disclosure END
        }

        // Authenticate h_sig with each of the input
        // spending keys, producing macs which protect
        // against malleability.
        for (size_t i = 0; i < NumInputs; i++) {
            out_macs[i] = PRF_pk(inputs[i].key, i, h_sig);
        }

        if (!computeProof) {
            return GrothProof();
        }

        GrothProof proof;

        CDataStream ss1(SER_NETWORK, PROTOCOL_VERSION);
        ss1 << inputs[0].witness.path();
        std::vector<unsigned char> auth1(ss1.begin(), ss1.end());

        CDataStream ss2(SER_NETWORK, PROTOCOL_VERSION);
        ss2 << inputs[1].witness.path();
        std::vector<unsigned char> auth2(ss2.begin(), ss2.end());

        librustzcash_sprout_prove(
            proof.begin(),

            phi.begin(),
            rt.begin(),
            h_sig.begin(),

            inputs[0].key.begin(),
            inputs[0].note.value(),
            inputs[0].note.rho.begin(),
            inputs[0].note.r.begin(),
            auth1.data(),

            inputs[1].key.begin(),
            inputs[1].note.value(),
            inputs[1].note.rho.begin(),
            inputs[1].note.r.begin(),
            auth2.data(),

            out_notes[0].a_pk.begin(),
            out_notes[0].value(),
            out_notes[0].r.begin(),

            out_notes[1].a_pk.begin(),
            out_notes[1].value(),
            out_notes[1].r.begin(),

            vpub_old,
            vpub_new
        );

        return proof;
    }
};

template<size_t NumInputs, size_t NumOutputs>
JoinSplit<NumInputs, NumOutputs>* JoinSplit<NumInputs, NumOutputs>::Prepared()
{
    return new JoinSplitCircuit<NumInputs, NumOutputs>();
}

template<size_t NumInputs, size_t NumOutputs>
uint256 JoinSplit<NumInputs, NumOutputs>::h_sig(
    const uint256& randomSeed,
    const std::array<uint256, NumInputs>& nullifiers,
    const uint256& joinSplitPubKey
) {
    const unsigned char personalization[crypto_generichash_blake2b_PERSONALBYTES]
        = {'Z','c','a','s','h','C','o','m','p','u','t','e','h','S','i','g'};

    std::vector<unsigned char> block(randomSeed.begin(), randomSeed.end());

    for (size_t i = 0; i < NumInputs; i++) {
        block.insert(block.end(), nullifiers[i].begin(), nullifiers[i].end());
    }

    block.insert(block.end(), joinSplitPubKey.begin(), joinSplitPubKey.end());

    uint256 output;

    if (crypto_generichash_blake2b_salt_personal(output.begin(), 32,
                                                 &block[0], block.size(),
                                                 NULL, 0, // No key.
                                                 NULL,    // No salt.
                                                 personalization
                                                ) != 0)
    {
        throw std::logic_error("hash function failure");
    }

    return output;
}

SproutNote JSOutput::note(const uint252& phi, const uint256& r, size_t i, const uint256& h_sig) const {
    uint256 rho = PRF_rho(phi, i, h_sig);

    return SproutNote(addr.a_pk, value, rho, r);
}

JSOutput::JSOutput() : addr(uint256(), uint256()), value(0) {
    SproutSpendingKey a_sk = SproutSpendingKey::random();
    addr = a_sk.address();
}

JSInput::JSInput() : witness(SproutMerkleTree().witness()),
                     key(SproutSpendingKey::random()) {
    note = SproutNote(key.address().a_pk, 0, random_uint256(), random_uint256());
    SproutMerkleTree dummy_tree;
    dummy_tree.append(note.cm());
    witness = dummy_tree.witness();
}

template class JoinSplit<ZC_NUM_JS_INPUTS,
                         ZC_NUM_JS_OUTPUTS>;

}

max_stars_repo_name: michailduzhanski/crypto-release

max_issues_repo_name: michailduzhanski/crypto-release

max_forks_repo_name: michailduzhanski/crypto-release