text:
// [===========================================================================]
// [                                M o n e t a                                ]
// [---------------------------------------------------------------------------]
// [                                                                           ]
// [                          Copyright (C) 2005-2015                          ]
// [                      Rodrigo Madera <madera@acm.org>                      ]
// [                                                                           ]
// [---------------------------------------------------------------------------]
// [         Distributed under the Boost Software License, Version 1.0         ]
// [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ]
// [===========================================================================]

#pragma once
#include "rtuple.hxx"
#include "../traits/detail/sepacon_opfx.hxx"
#include "../traits/is_entity.hxx"
#include "../traits/tuple.hxx"
#include "../traits/pk.hxx"
#include "../traits/extract_pk.hxx"
#include "../traits/detail/blanker.hxx"
#include <boost/utility/enable_if.hpp>
#include <boost/fusion/algorithm/transformation.hpp>

namespace moneta { namespace traits {

	namespace detail {

		template <class Entity>
		struct rtuple_maker {
			typename rtuple<Entity>::type
			operator()(Entity& entity) {
				return moneta::traits::detail::sepacon_opfx<
					typename moneta::traits::members<Entity>::type,
					typename rtuple<Entity>::type,
					Entity&,
					moneta::traits::get_pk_functor
				>()(entity);
			}
		};

	}

	template <class Entity>
	typename rtuple<Entity>::type
	to_rtuple(Entity& x) {
		return detail::rtuple_maker<Entity>()(x);
	}

	// XXX: Move this somewhere else.
	template <class Entity>
	typename traits::rtuple<Entity>::type make_rtuple() {
		typename traits::rtuple<Entity>::type result;
		return boost::fusion::transform(result, moneta::traits::detail::blanker());
	}

}}

ext: hxx

max_stars_repo_name: madera/Moneta

max_issues_repo_name: madera/Moneta

max_forks_repo_name: madera/Moneta


text:
/*** Copyright (c), The Regents of the University of California            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/
#ifndef RODS_PATH_HPP
#define RODS_PATH_HPP

#include "rodsDef.hpp"
#include "rods.hpp"
#include "getRodsEnv.hpp"
#include "rodsType.hpp"
#include "objStat.hpp"

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
using namespace std;
using namespace boost::filesystem;

extern "C" {

#define STDOUT_FILE_NAME	"-"	/* pipe to stdout */

    typedef struct RodsPath {
        objType_t objType;
        objStat_t objState;
        rodsLong_t size;
        uint objMode;
        char inPath[MAX_NAME_LEN];	 /* input from commnad line */
        char outPath[MAX_NAME_LEN];	 /* the path after parsing the inPath */
        char dataId[NAME_LEN];
        char chksum[NAME_LEN];
        rodsObjStat_t *rodsObjStat;
    } rodsPath_t;

    /* This is the struct for a command line path input. Normall it containers
     * one or more source inpput paths and 0 or 1 destination path */

    typedef struct RodsPathInp {
        int numSrc;
        rodsPath_t *srcPath;	/* pointr to an array of rodsPath_t */
        rodsPath_t *destPath;
        rodsPath_t *targPath;	/* This is a target path for a
                                  * source/destination type command */
        int resolved;
    } rodsPathInp_t;

    /* definition for flag in parseCmdLinePath */

#define	ALLOW_NO_SRC_FLAG	0x1

    int
    parseRodsPath( rodsPath_t *rodsPath, rodsEnv *myRodsEnv );
    int
    parseRodsPathStr( char *inPath, rodsEnv *myRodsEnv, char *outPath );
    int
    addSrcInPath( rodsPathInp_t *rodsPathInp, char *inPath );
    int
    parseLocalPath( rodsPath_t *rodsPath );
    int
    parseCmdLinePath( int argc, char **argv, int optInd, rodsEnv *myRodsEnv,
                      int srcFileType, int destFileType, int flag, rodsPathInp_t *rodsPathInp );

    int
    getLastPathElement( char *inPath, char *lastElement );

    int
    resolveRodsTarget( rcComm_t *conn, rodsEnv *myRodsEnv,
                       rodsPathInp_t *rodsPathInp, int oprType );
    int
    getFileType( rodsPath_t *rodsPath );
    void
    clearRodsPath( rodsPath_t *rodsPath );
}

#endif	/* RODS_PATH_H*/

ext: hpp

max_stars_repo_name: PlantandFoodResearch/irods

max_issues_repo_name: PlantandFoodResearch/irods

max_forks_repo_name: PlantandFoodResearch/irods


text:
//  (C) Copyright John Maddock 2007.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include "mp_t.hpp"
#include <boost/math/special_functions/expint.hpp>
#include <boost/math/constants/constants.hpp>
#include <fstream>
#include <boost/math/tools/test_data.hpp>

using namespace boost::math::tools;

struct expint_data_generator
{
   mp_t operator()(mp_t a, mp_t b)
   {
      unsigned n = boost::math::tools::real_cast<unsigned>(a);
      std::cout << n << "  " << b << "  ";
      mp_t result = boost::math::expint(n, b);
      std::cout << result << std::endl;
      return result;
   }
};

int main()
{
   boost::math::expint(1, 0.06227754056453704833984375);
   std::cout << boost::math::expint(1, mp_t(0.5)) << std::endl;

   parameter_info<mp_t> arg1, arg2;
   test_data<mp_t> data;

   std::cout << "Welcome.\n"
      "This program will generate spot tests for the expint function:\n"
      "  expint(a, b)\n\n";

   bool cont;
   std::string line;

   do{
      get_user_parameter_info(arg1, "a");
      get_user_parameter_info(arg2, "b");
      data.insert(expint_data_generator(), arg1, arg2);

      std::cout << "Any more data [y/n]?";
      std::getline(std::cin, line);
      boost::algorithm::trim(line);
      cont = (line == "y");
   }while(cont);

   std::cout << "Enter name of test data file [default=expint_data.ipp]";
   std::getline(std::cin, line);
   boost::algorithm::trim(line);
   if(line == "")
      line = "expint_data.ipp";
   std::ofstream ofs(line.c_str());
   ofs << std::scientific << std::setprecision(40);
   write_code(ofs, data, "expint_data");

   return 0;
}

ext: cpp

max_stars_repo_name: oleg-alexandrov/math

max_issues_repo_name: oleg-alexandrov/math


text:
#include <cctbx/boost_python/flex_fwd.h>
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/list.hpp>
#include <scitbx/array_family/flex_types.h>
#include <scitbx/array_family/shared.h>
#include <scitbx/array_family/versa.h>
#include <scitbx/array_family/accessors/c_grid.h>
#include <cctbx/miller.h>
#include <dials/array_family/reflection_table.h>
#include <algorithm>

typedef cctbx::miller::index<> miller_index_t;

namespace sx_merging {
  void foo2(){
    std::cout <<"HELLO merging foo2"<< std::endl;
  }

  void get_hkl_chunks_cpp(dials::af::reflection_table reflections,
                          const scitbx::af::shared<miller_index_t>& hkl_list,
                          const scitbx::af::shared<int>& chunk_id_list,
                          boost::python::list hkl_chunks_cpp){

    // set up a map hkl:chunk_id
    std::map<miller_index_t, size_t> chunk_lookup;
    for(size_t i = 0UL; i < hkl_list.size(); ++i){
      chunk_lookup[hkl_list[i]] = (size_t)chunk_id_list[i];
    }

    SCITBX_ASSERT(reflections.contains("miller_index_asymmetric"));
    SCITBX_ASSERT(reflections.contains("intensity.sum.value"));
    SCITBX_ASSERT(reflections.contains("intensity.sum.variance"));

    scitbx::af::ref<miller_index_t> miller_index = reflections["miller_index_asymmetric"];
    scitbx::af::ref<double> intensity = reflections["intensity.sum.value"];
    scitbx::af::ref<double> variance = reflections["intensity.sum.variance"];

    miller_index_t* mi_ptr = miller_index.begin();
    double* intensity_ptr = intensity.begin();
    double* variance_ptr = variance.begin();

    int n_chunks = boost::python::len(hkl_chunks_cpp);
    std::vector<dials::af::reflection_table> tables;
    for(size_t i=0UL; i < n_chunks; ++i){
      tables.push_back(boost::python::extract<dials::af::reflection_table>(hkl_chunks_cpp[i]));
      SCITBX_ASSERT(tables.back().contains("miller_index_asymmetric"));
    }

    // cache all columns for all hkl chunks
    std::vector<scitbx::af::shared<miller_index_t> >  mi_cols;
    std::vector<scitbx::af::shared<double> >          intensity_cols;
    std::vector<scitbx::af::shared<double> >          variance_cols;

    for(size_t i=0UL; i < n_chunks; ++i){
      mi_cols.push_back(tables[i]["miller_index_asymmetric"]);
      intensity_cols.push_back(tables[i]["intensity.sum.value"]);
      variance_cols.push_back(tables[i]["intensity.sum.variance"]);
    }

    // distribute reflections over chunks
    for(size_t i=0UL; i < reflections.size(); ++i){
      miller_index_t  hkl       = *mi_ptr++;
      double          intensity = *intensity_ptr++;
      double          variance  = *variance_ptr++;

      if( 0 != chunk_lookup.count(hkl) )
      {
          size_t chunk_id  = chunk_lookup[hkl];
          mi_cols[chunk_id].push_back(hkl);
          intensity_cols[chunk_id].push_back(intensity);
          variance_cols[chunk_id].push_back(variance);
       }
    }
  }
}

using namespace boost::python;
namespace sx_merging{
namespace boost_python { namespace {

  void
  sx_merging_init_module() {
    using namespace boost::python;
    typedef return_value_policy<return_by_value> rbv;
    typedef default_call_policies dcp;

    def("foo2",&sx_merging::foo2);
    def("get_hkl_chunks_cpp",&sx_merging::get_hkl_chunks_cpp);
  }

}
}} // namespace sx_merging::boost_python::<anonymous>

BOOST_PYTHON_MODULE(sx_merging_ext)
{
  sx_merging::boost_python::sx_merging_init_module();
}


text:
//   Copyright 2015 Patrick Putnam
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
#ifndef SEQUENCE_SPACE_HPP_
#define SEQUENCE_SPACE_HPP_

#include <vector>
#include <boost/property_tree/ptree.hpp>
#include <boost/dynamic_bitset.hpp>

#include "allele_space.hpp"

class SequenceSpace {
public:
    typedef boost::dynamic_bitset< unsigned long >  sequence_type;
    typedef std::shared_ptr< sequence_type >        sequence_ptr;

    SequenceSpace( boost::property_tree::ptree & config );

    sequence_ptr create();

    sequence_ptr clone( sequence_ptr s );

    size_t size();
    void prune();

    virtual ~SequenceSpace();
protected:
    AlleleSpace m_alleles;

    std::vector< sequence_ptr > m_seq_map;
};

#endif  // SEQUENCE_SPACE_HPP_

max_stars_repo_name: putnampp/clotho

max_issues_repo_name: putnampp/clotho

max_forks_repo_name: putnampp/clotho


text:
/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include <boost/assign/list_of.hpp>

#include <cfg/cfg_init.h>
#include <cfg/cfg_interface.h>
#include <oper/operdb_init.h>
#include <controller/controller_init.h>
#include <pkt/pkt_init.h>
#include <services/services_init.h>
#include <ksync/ksync_init.h>
#include <cmn/agent_cmn.h>
#include <base/task.h>
#include <io/event_manager.h>
#include <base/util.h>
#include <ifmap/ifmap_agent_parser.h>
#include <ifmap/ifmap_agent_table.h>
#include <oper/vn.h>
#include <oper/vm.h>
#include <oper/interface_common.h>
#include <openstack/instance_service_server.h>

#include <io/test/event_manager_test.h>
#include "testing/gunit.h"
#include "test_cmn_util.h"
#include "vr_types.h"

#include <async/TAsioAsync.h>
#include <protocol/TBinaryProtocol.h>
#include <gen-cpp/InstanceService.h>

#include <async/TFuture.h>
#include <io/event_manager.h>
#include <db/db.h>
#include <cmn/agent_cmn.h>
#include <cfg/cfg_interface.h>
#include <cfg/cfg_types.h>
#include <base/test/task_test_util.h>

using namespace std;
using namespace boost::assign;
using namespace apache::thrift;
using boost::shared_ptr;

extern void InstanceInfoServiceServerInit(Agent *agent);

void RouterIdDepInit(Agent *agent) {
}

//namespace {
class NovaInfoServerTest : public ::testing::Test {
protected:
};

DB *db;

uint32_t base_port_count = 3;
int8_t port_id []     = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int8_t instance_id [] = {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int8_t vn_id []       = {0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
string mac("00:00:00:00:00:");
string ip_address("10.10.10.");
string tap_name("vmport");
string display_name("vm");
string host_name("vm");
string host("vm");

bool connection_complete = false;
bool port_resp_done  = false;

boost::shared_ptr<InstanceServiceAsyncClient> client_service;

void AddPortCallback(tuuid port_id, std::string tap_name, bool ret)
{
    std::cout << "Device " << tap_name << ", Return value " << ret << std::endl;
}

void AddPortErrback(const InstanceService_AddPort_result& result)
{
    std::cout << "Exception caught " << __FUNCTION__ << std::endl;
}

void DeletePortCallback(tuuid port_id, bool ret)
{
    std::cout << "DeletePort " << ret << std::endl;
}

void DeletePortErrback(const InstanceService_DeletePort_result& result)
{
    std::cout << "Exception caught " << __FUNCTION__ << std::endl;
}

void ConnectCallback(bool ret)
{
    std::cout << "Connect, " << "Return value " << ret << std::endl;
}

void KeepAliveCallback(bool ret)
{
    std::cout << "Keepalive, " << "Return value " << ret << std::endl;
}

static inline const std::string integerToHexString(const int8_t &num)
{
    std::stringstream ss;
    ss << std::hex << (uint16_t)num;
    return ss.str();
}

void CreatePort(Port &port, int8_t portid, int8_t instanceid,
                 int8_t vnid, int16_t port_type) {
    std::string id_hex_str = integerToString(portid);
    port.tap_name = (tap_name + id_hex_str);
    port.ip_address = (ip_address + integerToString(portid));
    port.mac_address = (mac + id_hex_str);
    port.__set_display_name(display_name + integerToString(instanceid));
    port.__set_hostname(host_name + integerToHexString(instanceid));
    port.__set_host(host + integerToHexString(instanceid));
    port.__set_port_type(port_type);

    tuuid port_tuuid;
    int8_t t_port_id[sizeof(port_id)];
    memcpy(t_port_id, port_id, sizeof(t_port_id));
    t_port_id[15] = portid;
    port_tuuid.insert(port_tuuid.begin(), t_port_id,
                      t_port_id + (sizeof(t_port_id)/sizeof(int8_t)));
    port.port_id = port_tuuid;

    tuuid instance_tuuid;
    int8_t t_instance_id[sizeof(instance_id)];
    memcpy(t_instance_id, instance_id, sizeof(t_instance_id));
    t_instance_id[15] = instanceid;
    instance_tuuid.insert(instance_tuuid.begin(), t_instance_id,
                          t_instance_id + (sizeof(t_instance_id)/sizeof(int8_t)));
    port.instance_id = instance_tuuid;

    tuuid vn_tuuid;
    int8_t t_vn_id[sizeof(vn_id)];
    memcpy(t_vn_id, vn_id, sizeof(t_vn_id));
    t_vn_id[15] = vnid;
    vn_tuuid.insert(vn_tuuid.begin(), t_vn_id,
                    t_vn_id + (sizeof(t_vn_id)/sizeof(int8_t)));
    port.vn_id = vn_tuuid;
}

void DelVmPort(boost::shared_ptr<InstanceServiceAsyncClient> inst_client, int8_t portid) {
    tuuid port_tuuid;
    int8_t t_port_id[sizeof(port_id)];
    memcpy(t_port_id, port_id, sizeof(t_port_id));
    t_port_id[15] = portid;
    port_tuuid.insert(port_tuuid.begin(), t_port_id,
                      t_port_id + (sizeof(t_port_id)/sizeof(int8_t)));
    inst_client->DeletePort(port_tuuid).setCallback(
        boost::bind(&DeletePortCallback, port_tuuid, _1)).setErrback(DeletePortErrback);
}

void AddVmPort(boost::shared_ptr<InstanceServiceAsyncClient> inst_client, int8_t portid,
               int8_t instanceid, int8_t vnid, int16_t port_type) {
    std::vector<Port> pl;
    Port port;
    CreatePort(port, portid, instanceid, vnid, port_type);
    pl.push_back(port);
    inst_client->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port.port_id, port.tap_name, _1)).setErrback(AddPortErrback);
}

void ConnectToServer(boost::shared_ptr<InstanceServiceAsyncClient> inst_client) {
    inst_client->Connect().setCallback(
        boost::bind(&ConnectCallback, _1));
}

void SendKeepAlive(boost::shared_ptr<InstanceServiceAsyncClient> inst_client) {
    inst_client->KeepAliveCheck().setCallback(
        boost::bind(&KeepAliveCallback, _1));
}

void connected(boost::shared_ptr<InstanceServiceAsyncClient> inst_client) {
    std::cout << "connected!!!" << std::endl;
    client_service = inst_client;
    connection_complete = true;
}

static void PortReqResponse(Sandesh *sandesh, string &resp_str) {
    PortResp *resp = dynamic_cast<PortResp *>(sandesh);
    std::string s_resp_str = resp->get_resp();
    EXPECT_EQ(resp_str, s_resp_str);
    port_resp_done = true;
}

TEST_F(NovaInfoServerTest, IntrospecPortAdd) {
    AddPortReq *req = new AddPortReq();
    req->set_port_uuid(std::string("00000000-0000-0000-0000-000000000001"));
    req->set_instance_uuid(std::string("00000000-0000-0000-0000-000000000001"));
    req->set_tap_name(std::string("tap1"));
    req->set_ip_address(std::string("1.1.1.1"));
    req->set_vn_uuid(std::string("00000000-0000-0000-0000-000000000001"));
    req->set_mac_address(std::string("00:00:00:00:00:1"));
    req->set_vm_name(std::string("vm1"));
    req->set_vlan_id(100);
    req->set_vm_project_uuid("00000000-0000-0000-0000-000000000001");
    port_resp_done = false;
    Sandesh::set_response_callback(boost::bind(PortReqResponse, _1, std::string("Success")));
    req->HandleRequest();
    client->WaitForIdle();
    EXPECT_EQ(1, Agent::GetInstance()->interface_config_table()->Size());
    req->Release();
}

TEST_F(NovaInfoServerTest, IntrospecPortDelete) {
    DeletePortReq *req = new DeletePortReq();
    req->set_port_uuid(std::string("00000000-0000-0000-0000-000000000001"));
    port_resp_done = false;
    Sandesh::set_response_callback(boost::bind(PortReqResponse, _1, std::string("Success")));
    req->HandleRequest();
    client->WaitForIdle();
    EXPECT_EQ(0, Agent::GetInstance()->interface_config_table()->Size());
    req->Release();
}

EventManager *client_evm;
ServerThread *client_thread;

class NovaInfoClientServerTest : public ::testing::Test {
protected:
};

TEST_F(NovaInfoClientServerTest, ConnectionStart) {
    client_evm = new EventManager();
    client_thread = new ServerThread(client_evm);
    boost::shared_ptr<protocol::TProtocolFactory>
            protocolFactory(new protocol::TBinaryProtocolFactory());
    boost::shared_ptr<async::TAsioClient> nova_client (
        new async::TAsioClient(
            *(client_evm->io_service()),
            protocolFactory,
            protocolFactory));
    client_thread->Start();
    nova_client->connect("localhost", 9090, connected);
    TASK_UTIL_EXPECT_EQ(true, connection_complete);
}

TEST_F(NovaInfoClientServerTest, ConnectTest) {
    ConnectToServer(client_service);
}

TEST_F(NovaInfoClientServerTest, KeepAliveTest) {
    SendKeepAlive(client_service);
}

TEST_F(NovaInfoClientServerTest, PortAdd) {
    // Add and delete port check the status of the cfg intf db
    AddVmPort(client_service, 1, 1, 1, PortTypes::NovaVMPort);
    CfgIntTable *cfgtable = Agent::GetInstance()->interface_config_table();
    CfgIntKey key(MakeUuid(1));
    TASK_UTIL_EXPECT_EQ(1, Agent::GetInstance()->interface_config_table()->Size());
    CfgIntEntry *cfg_entry;
    TASK_UTIL_EXPECT_NE((CfgIntEntry *)NULL,
                        (cfg_entry =
                         static_cast<CfgIntEntry *>(Agent::GetInstance()->interface_config_table()->Find(&key))));
    EXPECT_EQ(cfg_entry->GetVersion(), 1);
}

TEST_F(NovaInfoClientServerTest, PortDelete) {
    CfgIntTable *cfgtable = Agent::GetInstance()->interface_config_table();
    CfgIntKey key(MakeUuid(1));
    TASK_UTIL_EXPECT_EQ(1, Agent::GetInstance()->interface_config_table()->Size());
    CfgIntEntry *cfg_entry;
    TASK_UTIL_EXPECT_NE((CfgIntEntry *)NULL,
                        (cfg_entry =
                         static_cast<CfgIntEntry *>(Agent::GetInstance()->interface_config_table()->Find(&key))));
    EXPECT_EQ(cfg_entry->GetVersion(), 1);
    DelVmPort(client_service, 1);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->interface_config_table()->Size());
    TASK_UTIL_EXPECT_EQ(base_port_count, Agent::GetInstance()->interface_table()->Size());
}

TEST_F(NovaInfoClientServerTest, StaleTimer) {
    // 1) Add name space port
    // 2) Add nova port
    // 3) Run stale timer
    // 4) Verifuy nova port deleted and name space port exists
    // 5) Delete name space port
    AddVmPort(client_service, 1, 1, 1, PortTypes::NameSpacePort);
    CfgIntTable *cfgtable = Agent::GetInstance()->interface_config_table();
    CfgIntKey key(MakeUuid(1));
    TASK_UTIL_EXPECT_EQ(1, Agent::GetInstance()->interface_config_table()->Size());
    CfgIntEntry *cfg_entry;
    TASK_UTIL_EXPECT_NE((CfgIntEntry *)NULL,
                        (cfg_entry =
                         static_cast<CfgIntEntry *>(Agent::GetInstance()->interface_config_table()->Find(&key))));
    EXPECT_EQ(cfg_entry->GetVersion(), 0);
    EXPECT_EQ(cfg_entry->port_type(), CfgIntEntry::CfgIntNameSpacePort);

    AddVmPort(client_service, 2, 2, 2, PortTypes::NovaVMPort);
    CfgIntKey key1(MakeUuid(2));
    TASK_UTIL_EXPECT_EQ(2, Agent::GetInstance()->interface_config_table()->Size());
    CfgIntEntry *cfg_entry1;
    TASK_UTIL_EXPECT_NE((CfgIntEntry *)NULL,
                        (cfg_entry1 =
                         static_cast<CfgIntEntry *>(Agent::GetInstance()->interface_config_table()->Find(&key1))));
    EXPECT_EQ(cfg_entry1->GetVersion(), 1);
    EXPECT_EQ(cfg_entry1->port_type(), CfgIntEntry::CfgIntVMPort);

    std::auto_ptr<InterfaceConfigStaleCleaner> st(new InterfaceConfigStaleCleaner(Agent::GetInstance()));
    st->OnInterfaceConfigStaleTimeout(2);

    TASK_UTIL_EXPECT_EQ(1, Agent::GetInstance()->interface_config_table()->Size());
    CfgIntKey key2(MakeUuid(1));
    CfgIntEntry *cfg_entry2;
    TASK_UTIL_EXPECT_NE((CfgIntEntry *)NULL,
                        (cfg_entry2 =
                         static_cast<CfgIntEntry *>(Agent::GetInstance()->interface_config_table()->Find(&key2))));
    EXPECT_EQ(cfg_entry2->port_type(), CfgIntEntry::CfgIntNameSpacePort);

    DelVmPort(client_service, 1);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->interface_config_table()->Size());
}

TEST_F(NovaInfoClientServerTest, ReconnectVersionCheck) {
    AddVmPort(client_service, 1, 1, 1, PortTypes::NovaVMPort);
    ConnectToServer(client_service);
    CfgIntTable *cfgtable = Agent::GetInstance()->interface_config_table();
    CfgIntKey key(MakeUuid(1));
    TASK_UTIL_EXPECT_EQ(1, Agent::GetInstance()->interface_config_table()->Size());
    CfgIntEntry *cfg_entry;
    TASK_UTIL_EXPECT_NE((CfgIntEntry *)NULL,
                        (cfg_entry =
                         static_cast<CfgIntEntry *>(Agent::GetInstance()->interface_config_table()->Find(&key))));
    EXPECT_EQ(cfg_entry->GetVersion(), 1);
    DelVmPort(client_service, 1);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->interface_config_table()->Size());
    TASK_UTIL_EXPECT_EQ(base_port_count, Agent::GetInstance()->interface_table()->Size());
}

TEST_F(NovaInfoClientServerTest, MultiPortAddDelete) {
    // Add Multiple ports
    Port port1;
    Port port2;
    Port port3;
    CreatePort(port1, 3, 3, 1, PortTypes::NovaVMPort);
    CreatePort(port2, 4, 4, 1, PortTypes::NovaVMPort);
    CreatePort(port3, 5, 5, 1, PortTypes::NovaVMPort);
    std::vector<Port> pl;
    pl.clear();
    pl.push_back(port1);
    pl.push_back(port2);
    pl.push_back(port3);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port3.port_id, port3.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(3, Agent::GetInstance()->interface_config_table()->Size());
    // Add again same muliple ports
    pl.clear();
    pl.push_back(port1);
    pl.push_back(port2);
    pl.push_back(port3);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port3.port_id, port3.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(3, Agent::GetInstance()->interface_config_table()->Size());
    // Delete Multiple ports
    DelVmPort(client_service, 3);
    DelVmPort(client_service, 4);
    DelVmPort(client_service, 5);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->interface_config_table()->Size());
    TASK_UTIL_EXPECT_EQ(base_port_count, Agent::GetInstance()->interface_table()->Size());
}

TEST_F(NovaInfoClientServerTest, AddPortWrongIP) {
    // Test negitive inputs
    // Wrong IP address
    Port port;
    std::vector<Port> pl;
    CreatePort(port, 2, 2, 2, PortTypes::NovaVMPort);
    port.ip_address = "TestIP";
    pl.push_back(port);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port.port_id, port.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->interface_config_table()->Size());
    TASK_UTIL_EXPECT_EQ(base_port_count, Agent::GetInstance()->interface_table()->Size());
}

TEST_F(NovaInfoClientServerTest, NullUUIDTest) {
    Port port;
    // Null uuids, we are allowing them
    CreatePort(port, 3, 3, 3, PortTypes::NovaVMPort);
    tuuid null_tuuid;
    int8_t t_port_id[sizeof(port_id)];
    memcpy(t_port_id, port_id, sizeof(t_port_id));
    null_tuuid.insert(null_tuuid.begin(), t_port_id,
                      t_port_id + (sizeof(t_port_id)/sizeof(int8_t)));
    port.port_id = null_tuuid;
    port.instance_id = null_tuuid;
    port.vn_id = null_tuuid;
    std::vector<Port> pl;
    pl.clear();
    pl.push_back(port);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port.port_id, port.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(1, Agent::GetInstance()->interface_config_table()->Size());
    client_service->DeletePort(null_tuuid).setCallback(
        boost::bind(&DeletePortCallback, null_tuuid, _1)).setErrback(DeletePortErrback);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->interface_config_table()->Size());
    TASK_UTIL_EXPECT_EQ(base_port_count, Agent::GetInstance()->interface_table()->Size());
}

TEST_F(NovaInfoClientServerTest, WrongUUIDTest1) {
    // Send extra bytes in the uuid, and it shouldn't get added
    Port port;
    CreatePort(port, 4, 4, 4, PortTypes::NovaVMPort);
    tuuid extra_tuuid;
    int8_t t_extraport_id[sizeof(port_id) + 1];
    memcpy(t_extraport_id, port_id, sizeof(port_id));
    extra_tuuid.insert(extra_tuuid.begin(), t_extraport_id,
                       t_extraport_id + (sizeof(t_extraport_id)/sizeof(int8_t)));
    port.port_id = extra_tuuid;
    port.instance_id = extra_tuuid;
    port.vn_id = extra_tuuid;
    std::vector<Port> pl;
    pl.clear();
    pl.push_back(port);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port.port_id, port.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->interface_config_table()->Size());
    TASK_UTIL_EXPECT_EQ(base_port_count, Agent::GetInstance()->interface_table()->Size());
}

TEST_F(NovaInfoClientServerTest, WrongUUIDTest2) {
    // Send less number of bytes in uuids, and it shouldn't get added
    Port port;
    CreatePort(port, 5, 5, 5, PortTypes::NovaVMPort);
    tuuid small_tuuid;
    int8_t s_port_id[sizeof(port_id)];
    memcpy(s_port_id, port_id, sizeof(port_id));
    small_tuuid.insert(small_tuuid.begin(), s_port_id,
                       s_port_id + (sizeof(s_port_id)/sizeof(int8_t) - 1));
    port.port_id = small_tuuid;
    port.instance_id = small_tuuid;
    tuuid vn_tuuid;
    int8_t t_vn_id[sizeof(vn_id)];
    memcpy(t_vn_id, vn_id, sizeof(t_vn_id));
    vn_tuuid.insert(vn_tuuid.begin(), t_vn_id,
                    t_vn_id + (sizeof(t_vn_id)/sizeof(int8_t)));
    port.vn_id = vn_tuuid;
    std::vector<Port> pl;
    pl.clear();
    pl.push_back(port);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port.port_id, port.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->interface_config_table()->Size());
    TASK_UTIL_EXPECT_EQ(base_port_count, Agent::GetInstance()->interface_table()->Size());
}

TEST_F(NovaInfoClientServerTest, ConnectionDelete) {
    client_evm->Shutdown();
    client_thread->Join();
    delete client_evm;
    delete client_thread;
}

int main (int argc, char **argv) {
    GETUSERARGS();
    client = TestInit(init_file, ksync_init);
    EventManager *evm = Agent::GetInstance()->event_manager();
    InstanceInfoServiceServerInit(Agent::GetInstance());
    int ret = RUN_ALL_TESTS();
    client->WaitForIdle();
    TestShutdown();
    delete client;
    return ret;
}

ext: cc

max_stars_repo_name: Juniper/contrail-dev-controller

max_issues_repo_name: Juniper/contrail-dev-controller

max_forks_repo_name: Juniper/contrail-dev-controller


text:
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE

#include "python_script.h"

#include <cstdio>
#include <fstream>
#include <iostream>
#include <iterator>

#include "anh/logger.h"

#include <boost/python.hpp>
#include <Python.h>

#include "swganh/scripting/utilities.h"

using namespace boost::python;
using namespace std;
using namespace swganh::scripting;

PythonScript::PythonScript(const string& filename)
        : filename_(filename)
{
    ReadFileContents();
    swganh::scripting::ScopedGilLock lock;

	try
    {
        PyRun_SimpleString("import sys; sys.path.append('.');");

		boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed(
			PyImport_AddModule("__main__")
		)));

        globals_ = main.attr("__dict__");
        globals_["swgpy"] = boost::python::import("swgpy");
        globals_["context"] = dict();
    }
    catch (error_already_set &)
    {
        PyErr_Print();
    }
}

void PythonScript::Run()
{
	try
    {
#ifdef _DEBUG
        ReadFileContents();
#endif
        LOG(info) << "Executing script: " << filename_;
        swganh::scripting::ScopedGilLock lock;
		file_object_ = exec(filecontents_.c_str(), globals_, globals_);
    }
    catch (error_already_set &)
    {
        GetPythonException();
    }
}

void PythonScript::ReadFileContents()
{
    ifstream filestream(filename_);
    filestream >> noskipws;

    filecontents_ = string(
        (istreambuf_iterator<char>(filestream)),
        istreambuf_iterator<char>());
}

void PythonScript::GetPythonException()
{
    swganh::scripting::ScopedGilLock lock;

    std::ostringstream os;
    os << "Python error:\n  " << std::flush;

    PyObject *type = 0, *val = 0, *tb = 0;
    PyErr_Fetch(&type, &val, &tb);
    handle<> e_val(val), e_type(type), e_tb(allow_null(tb));

    try {
        object t = extract<object>(e_type.get());
        object t_name = t.attr("__name__");
        std::string typestr = extract<std::string>(t_name);

        os << typestr << std::flush;
    } catch (error_already_set const &) {
        os << "Internal error getting error type:\n";
        PyErr_Print();
    }

    os << ": ";

    try {
        object v = extract<object>(e_val.get());
        std::string valuestr = extract<std::string>(v.attr("__str__")());
        os  << valuestr << std::flush;
    } catch (error_already_set const &) {
        os << "Internal error getting value type:\n";
        PyErr_Print();
    }

    if (tb) {
        try {
            object tb_list = import("traceback").attr("format_tb")(e_tb);
            object tb_str = str("").attr("join")(tb_list);
            std::string str = extract<std::string>(tb_str);

            os << "\nTraceback (recent call last):\n" << str;
        } catch (error_already_set const &) {
            os << "Internal error getting traceback:\n";
            PyErr_Print();
        }
    } else {
        os << std::endl;
    }
    PyErr_Clear();
    std::cerr << os.str() << endl;
    LOG(warning) << os.str();
}

max_stars_repo_name: JohnShandy/swganh

max_issues_repo_name: JohnShandy/swganh

max_forks_repo_name: JohnShandy/swganh


text:
// Copyright (c) 2019 Christopher A. Taylor.  All rights reserved.

/*
    Common code for RGBD capture

    This tries to not have any camera-specific includes leak into it,
    so that we can cleanly separate camera capture from processing.
*/

#pragma once

#include <cstdint>
#include <memory>
#include <vector>
#include <atomic>
#include <functional>

#include <core.hpp> // core
#include <Eigen/Core> // Eigen
#include <DepthCalibration.hpp> // depth_mesh
#include <DepthMesh.hpp> // depth_mesh
#include <MfxTools.hpp> // mfx
#include <CaptureProtocol.hpp> // capture_protocol

namespace core {

//------------------------------------------------------------------------------
// RgbdImage

struct RgbdImage
{
    //--------------------------------------------------------------------------
    // Set by CaptureDevice:
    //--------------------------------------------------------------------------

    // Image source
    int DeviceIndex = -1;
    int FrameNumber = 0; // Frame number for this camera
    int Framerate = 0; // FPS

    // Color image
    std::vector<uint8_t> ColorImage;
    int ColorWidth = 0, ColorHeight = 0, ColorStride = 0;

    // Does this contain a JPEG image?
    bool IsJpegBuffer = false;

    // Depth image
    std::vector<uint16_t> DepthImage;
    int DepthWidth = 0, DepthHeight = 0, DepthStride = 0;

    // Device timestamp in units specific to this device
    uint64_t DepthDeviceUsec = 0;

    // Host time when host finished receiving the depth
    uint64_t DepthSystemUsec = 0;

    // Device timestamp in units specific to this device
    uint64_t ColorDeviceUsec = 0;

    // Host time when host finished receiving the image
    uint64_t ColorSystemUsec = 0;

    // Temperature in Celsius
    float TemperatureC = 0.f;

    // Auto exposure duration for this color frame
    uint64_t ColorExposureUsec = 0;

    // Auto white balance for this color frame
    uint32_t ColorWhiteBalanceUsec = 0;

    // ISO speed for color frame
    uint32_t ColorIsoSpeed = 0;

    // Device-specific thread-safe mesher
    std::shared_ptr<DepthMesher> Mesher;

    // IMU sample for this frame
    Eigen::Vector3f AccelerationSample{};

    // Device time for sync pulse
    uint64_t SyncDeviceUsec = 0;

    // Host time for sync pulse
    uint64_t SyncSystemUsec = 0;

    //--------------------------------------------------------------------------
    // Set by CaptureManager:
    //--------------------------------------------------------------------------

    // Is this matched with a full multi-camera image set?
    std::atomic<bool> Matched = ATOMIC_VAR_INIT(false);

    //--------------------------------------------------------------------------
    // Set by BatchProcessor:
    //--------------------------------------------------------------------------

    // Batch number for all cameras
    int BatchNumber = 0;

    // This is the number of chroma components in width and height
    int ChromaWidth = 0, ChromaHeight = 0, ChromaStride = 0;

    // Some decoders produce NV12 output.
    // In this case Color[1] = interleaved U,V data, Color[2] = nullptr
    bool IsNV12 = false;

    // Decompressed YUV420 image data.
    uint8_t* Color[3];

    // Used for extrinsics calibration.
    // x,y,z,u,v coordinates of each vertex of the depth camera
    // in the frame of the color camera.
    // Not transformed to scene space, so we can use this for registration.
    std::vector<float> MeshVertices;

    // Color data copied back from GPU memory
    mfx::frameref_t CopyBack;

    // Indices for each triangle
    std::vector<uint32_t> MeshTriangles;

    // Factor applied by video processing step
    float Brightness = 0.f;
    float Saturation = 0.f;

    // Crop chosen for this video frame
    bool EnableCrop = false;
    ImageCropRegion CropRegion;

    // Compressed image and depth for streaming
    std::vector<uint8_t> CompressedImage;
    std::vector<uint8_t> CompressedDepth;
};

//------------------------------------------------------------------------------
// ImageBatch

// One image from each camera that goes through the processing pipeline
struct ImageBatch
{
    //--------------------------------------------------------------------------
    // Provided by CaptureManager:
    //--------------------------------------------------------------------------

    // Images in the batch
    std::vector< std::shared_ptr<RgbdImage> > Images;

    //--------------------------------------------------------------------------
    // Provided by BatchProcessor (Foreground):
    //--------------------------------------------------------------------------

    // Start time for processing the image set
    uint64_t BatchStartMsec = 0;

    // Incrementing number for this batch
    int BatchNumber = 0;

    //--------------------------------------------------------------------------
    // Provided by BatchProcessor (Background):
    //--------------------------------------------------------------------------

    // Time at which frame read occurred in system time since boot in usec
    //uint64_t UsbReadSystemUsec = 0;

    // End time for processing the image set
    uint64_t BatchEndMsec = 0;

    // Time at which sync pulse occurred in system time since boot in microseconds
    uint64_t SyncSystemUsec = 0;

    // Sync pulse time in microseconds since the Unix epoch
    uint64_t SyncEpochUsec = 0;

    // Video frame time since Unix epoch in microseconds
    uint64_t VideoEpochUsec = 0;

    // Is this frame following a discontinuity in the stream?
    bool Discontinuity = false;

    // Is this a keyframe?
    bool Keyframe = false;

    // Batch info for delivery
    protos::MessageBatchInfo StreamInfo{};

    // Number that increments each time the video info updates
    uint32_t VideoInfoEpoch = 0;

    // Video info for delivery
    protos::MessageVideoInfo VideoInfo{};

    // Error occurred during pipeline operations
    // e.g. JPEG decode failed or video encode failed
    std::atomic<bool> PipelineError = ATOMIC_VAR_INIT(false);

    // A stage in the pipeline failed to keep up with the input rate
    // and at least one image was dropped for this batch
    std::atomic<bool> SlowDrop = ATOMIC_VAR_INIT(false);

    // This frame was dropped due to some reason above
    std::atomic<bool> Aborted = ATOMIC_VAR_INIT(false);
};

using BatchCallback = std::function<void(std::shared_ptr<ImageBatch>& batch)>;

} // namespace core

max_stars_repo_name: catid/xrcap

max_issues_repo_name: catid/xrcap

max_forks_repo_name: catid/xrcap


text:
#define CATCH_CONFIG_MAIN
#include <Eigen/Dense>
#include <catch.hpp>
#include <random>

#include "EDP/ConstructSparseMat.hpp"
#include "EDP/LocalHamiltonian.hpp"

#include "yavque/Circuit.hpp"
#include "yavque/operators.hpp"
#include "yavque/utils.hpp"

#include "common.hpp"

tbb::global_control gc(tbb::global_control::max_allowed_parallelism, 2);

yavque::Circuit construct_diagonal_tfi(const uint32_t N)
{
	yavque::Circuit circ(1 << N);
	Eigen::VectorXd zz_all(1 << N);

	for(uint32_t n = 0; n < (1u << N); ++n)
	{
		int elt = 0;
		for(uint32_t k = 0; k < N; ++k)
		{
			int z0 = 1 - 2 * ((n >> k) & 1);
			int z1 = 1 - 2 * ((n >> ((k + 1) % N)) & 1);
			elt += z0 * z1;
		}
		zz_all(n) = elt;
	}

	auto zz_all_ham = yavque::DiagonalOperator(zz_all, "zz all");
	auto x_all_ham
		= yavque::SumLocalHam(N, yavque::pauli_x().cast<yavque::cx_double>(), "x all");

	for(uint32_t p = 0; p < 4; ++p)
	{
		circ.add_op_right<yavque::DiagonalHamEvol>(zz_all_ham);
		circ.add_op_right<yavque::SumLocalHamEvol>(x_all_ham);
	}
	circ.add_op_right<yavque::DiagonalHamEvol>(zz_all_ham);
	return circ;
}

auto construct_bare_tfi(const uint32_t N)
{
	yavque::Circuit circ(1U << N);
	std::vector<yavque::Variable> variables(9);

	std::vector<yavque::Hamiltonian> zz_hams;

	for(uint32_t k = 0; k < N; ++k)
	{
		edp::LocalHamiltonian<double> lh(N, 2);
		lh.addTwoSiteTerm({k, (k + 1) % N}, yavque::pauli_zz());
		zz_hams.emplace_back(edp::constructSparseMat<yavque::cx_double>(1 << N, lh));
	}
	auto x_all_ham
		= yavque::SumLocalHam(N, yavque::pauli_x().cast<yavque::cx_double>(), "x all");

	for(uint32_t p = 0; p < 4; ++p)
	{
		for(uint32_t k = 0; k < N; k++)
		{
			circ.add_op_right<yavque::HamEvol>(zz_hams[k], variables[2 * p + 0]);
		}
		circ.add_op_right<yavque::SumLocalHamEvol>(x_all_ham, variables[2 * p + 1]);
	}
	for(uint32_t k = 0; k < N; k++)
	{
		circ.add_op_right<yavque::HamEvol>(zz_hams[k], variables[8]);
	}

	return std::make_pair(std::move(circ), std::move(variables));
}

Eigen::VectorXcd analytic_twoqubit(double theta, double phi)
{
	Eigen::VectorXcd res(4);
	constexpr yavque::cx_double I(0., 1.);

	res(0) = cos(2 * phi) * exp(-I * theta) - I * sin(2 * phi) * exp(I * theta);
	res(1) = cos(2 * phi) * exp(I * theta) - I * sin(2 * phi) * exp(-I * theta);
	res(2) = cos(2 * phi) * exp(I * theta) - I * sin(2 * phi) * exp(-I * theta);
	res(3) = cos(2 * phi) * exp(-I * theta) - I * sin(2 * phi) * exp(I * theta);

	return res / 2;
}

Eigen::MatrixXcd rot_x(double phi)
{
	constexpr yavque::cx_double I(0., 1.);
	Eigen::MatrixXcd rot_x(2, 2);

	rot_x << cos(phi), -I * sin(phi), -I * sin(phi), cos(phi);

	return rot_x;
}

Eigen::MatrixXcd kron_n(const Eigen::MatrixXcd& m, uint32_t n)
{
	Eigen::MatrixXcd res(m);
	for(uint32_t k = 1; k < n; ++k)
	{
		res = Eigen::kroneckerProduct(res, m).eval();
	}
	return res;
}

Eigen::VectorXcd product_fourqubit(double theta1, double phi1, double theta2, double phi2)
{
	Eigen::VectorXcd res(16);
	constexpr yavque::cx_double I(0., 1.);

	Eigen::VectorXd zz(16);
	zz << 4, 0, 0, 0, 0, -4, 0, 0, 0, 0, -4, 0, 0, 0, 0, 4;

	Eigen::VectorXcd v = Eigen::VectorXcd::Ones(16);
	v /= 4.0;

	v.array() *= (-I * theta1 * zz.array()).exp();
	v = kron_n(rot_x(phi1), 4) * v;
	v.array() *= (-I * theta2 * zz.array()).exp();
	v = kron_n(rot_x(phi2), 4) * v;

	return v;
}

TEST_CASE("test two qubit", "[tfi-twoqubit]")
{
	using namespace yavque;
	using namespace Eigen;

	std::random_device rd;
	std::default_random_engine re{rd()};

	std::normal_distribution<> ndist(0., 1.);

	constexpr unsigned int N = 2;
	const double eps = 1e-6;

	Eigen::VectorXcd zz(1 << N);

	for(uint32_t n = 0; n < (1u << N); ++n)
	{
		int z0 = 1 - 2 * ((n >> 0) & 1);
		int z1 = 1 - 2 * ((n >> 1) & 1);
		zz(n) = z0 * z1;
	}

	auto zz_all_ham = yavque::DiagonalOperator(zz, "zz all");
	auto x_all_ham
		= yavque::SumLocalHam(N, yavque::pauli_x().cast<yavque::cx_double>(), "x all");

	auto circ = yavque::Circuit(1 << N);

	for(uint32_t p = 0; p < 1; ++p)
	{
		circ.add_op_right<yavque::DiagonalHamEvol>(zz_all_ham);
		circ.add_op_right<yavque::SumLocalHamEvol>(x_all_ham);
	}

	Eigen::MatrixXd ham(4, 4);
	ham << -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1;

	auto variables = circ.variables();

	Eigen::VectorXcd ini = Eigen::VectorXcd::Ones(4);
	ini /= sqrt(4.0);

	circ.set_input(ini);

	for(uint32_t _instance = 0; _instance < 10; ++_instance)
	{
		double theta = ndist(re);
		double phi = ndist(re);
		variables[0] = theta;
		variables[1] = phi;

		for(uint32_t epoch = 0; epoch < 100; ++epoch)
		{ // learning loop
			theta = variables[0].value();
			phi = variables[1].value();

			circ.clear_evaluated();
			Eigen::VectorXcd output = *circ.output();
			Eigen::VectorXcd analytic = analytic_twoqubit(theta, phi);

			REQUIRE((output - analytic).norm() < 1e-6);

			// test grad
			for(auto& p : variables)
			{
				p.zero_grad();
			}
			circ.derivs();
			Eigen::MatrixXcd grads(1 << N, 2);
			grads.col(0) = *variables[0].grad();
			grads.col(1) = *variables[1].grad();
			Eigen::VectorXd egrad_circ = 2 * (output.adjoint() * ham * grads).real();

			Eigen::VectorXcd v1 = analytic_twoqubit(theta + eps, phi);
			Eigen::VectorXcd v2 = analytic_twoqubit(theta - eps, phi);

			Eigen::VectorXd egrad_num(2);
			egrad_num.coeffRef(0) = real(cx_double(v1.adjoint() * ham * v1)
			                             - cx_double(v2.adjoint() * ham * v2))
			                        / (2 * eps);

			v1 = analytic_twoqubit(theta, phi + eps);
			v2 = analytic_twoqubit(theta, phi - eps);

			egrad_num.coeffRef(1) = real(cx_double(v1.adjoint() * ham * v1)
			                             - cx_double(v2.adjoint() * ham * v2))
			                        / (2 * eps);

			REQUIRE((egrad_circ - egrad_num).norm() < 1e-6);

			for(uint32_t k = 0; k < variables.size(); ++k)
			{
				variables[k] -= 0.02 * egrad_circ(k);
			}

			std::cout << real(cx_double(output.adjoint() * ham * output)) << std::endl;
		}
	}
}

TEST_CASE("test four qubit", "[tfi-fourqubit]")
{
	using namespace yavque;
	using namespace Eigen;

	std::random_device rd;
	std::default_random_engine re{rd()};

	std::normal_distribution<> ndist(0., 1.);

	constexpr unsigned int N = 4;
	const double eps = 1e-6;

	Eigen::VectorXd zz_all(1 << N);

	for(uint32_t n = 0; n < (1u << N); ++n)
	{
		int elt = 0;
		for(uint32_t k = 0; k < N; ++k)
		{
			int z0 = 1 - 2 * ((n >> k) & 1);
			int z1 = 1 - 2 * ((n >> ((k + 1) % N)) & 1);
			elt += z0 * z1;
		}
		zz_all(n) = elt;
	}

	auto zz_all_ham = yavque::DiagonalOperator(zz_all, "zz all");
	auto x_all_ham
		= yavque::SumLocalHam(N, yavque::pauli_x().cast<yavque::cx_double>(), "x all");

	auto circ = yavque::Circuit(1 << N);

	for(uint32_t p = 0; p < 2; ++p)
	{
		circ.add_op_right<yavque::DiagonalHamEvol>(zz_all_ham);
		circ.add_op_right<yavque::SumLocalHamEvol>(x_all_ham);
	}

	Eigen::MatrixXd ham = zz_all.asDiagonal();

	auto variables = circ.variables();

	Eigen::VectorXcd ini = Eigen::VectorXcd::Ones(16);
	ini /= 4.0;

	circ.set_input(ini);

	for(uint32_t _instance = 0; _instance < 10; ++_instance)
	{
		double theta1 = ndist(re);
		double theta2 = ndist(re);
		double phi1 = ndist(re);
		double phi2 = ndist(re);

		variables[0] = theta1;
		variables[1] = phi1;
		variables[2] = theta2;
		variables[3] = phi2;

		for(uint32_t epoch = 0; epoch < 100; ++epoch)
		{ // learning loop
			theta1 = variables[0].value();
			phi1 = variables[1].value();
			theta2 = variables[2].value();
			phi2 = variables[3].value();

			circ.clear_evaluated();
			Eigen::VectorXcd output = *circ.output();
			Eigen::VectorXcd analytic = product_fourqubit(theta1, phi1, theta2, phi2);

			REQUIRE((output - analytic).norm() < 1e-6);

			// test grad
			for(auto& p : variables)
			{
				p.zero_grad();
			}
			circ.derivs();
			Eigen::MatrixXcd grads(1 << N, 4);
			for(uint32_t k = 0; k < 4; k++)
			{
				grads.col(k) = *variables[k].grad();
			}
			Eigen::VectorXd egrad_circ = 2 * (output.adjoint() * ham * grads).real();

			Eigen::VectorXcd v1 = product_fourqubit(theta1 + eps, phi1, theta2, phi2);
			Eigen::VectorXcd v2 = product_fourqubit(theta1 - eps, phi1, theta2, phi2);

			Eigen::VectorXd egrad_num(4);
			egrad_num.coeffRef(0) = real(cx_double(v1.adjoint() * ham * v1)
			                             - cx_double(v2.adjoint() * ham * v2))
			                        / (2 * eps);

			v1 = product_fourqubit(theta1, phi1 + eps, theta2, phi2);
			v2 = product_fourqubit(theta1, phi1 - eps, theta2, phi2);
			egrad_num.coeffRef(1) = real(cx_double(v1.adjoint() * ham * v1)
			                             - cx_double(v2.adjoint() * ham * v2))
			                        / (2 * eps);

			v1 = product_fourqubit(theta1, phi1, theta2 + eps, phi2);
			v2 = product_fourqubit(theta1, phi1, theta2 - eps, phi2);
			egrad_num.coeffRef(2) = real(cx_double(v1.adjoint() * ham * v1)
			                             - cx_double(v2.adjoint() * ham * v2))
			                        / (2 * eps);

			v1 = product_fourqubit(theta1, phi1, theta2, phi2 + eps);
			v2 = product_fourqubit(theta1, phi1, theta2, phi2 - eps);
			egrad_num.coeffRef(3) = real(cx_double(v1.adjoint() * ham * v1)
			                             - cx_double(v2.adjoint() * ham * v2))
			                        / (2 * eps);

			REQUIRE((egrad_circ - egrad_num).norm() < 1e-6);

			for(uint32_t k = 0; k < variables.size(); ++k)
			{
				variables[k] -= 0.02 * egrad_circ(k);
			}

			std::cout << real(cx_double(output.adjoint() * ham * output)) << std::endl;
		}
	}
}

TEST_CASE("test tfi", "[tfi]")
{
	using namespace yavque;
	using namespace Eigen;

	constexpr unsigned int N = 10;
	constexpr cx_double I(0., 1.);

	std::random_device rd;
	std::default_random_engine re{rd()};
	std::normal_distribution<> nd;

	auto circ1 = construct_diagonal_tfi(N);
	auto variables1 = circ1.variables();

	auto [circ2, variables2] = construct_bare_tfi(N);

	Eigen::VectorXcd ini = Eigen::VectorXcd::Ones(1 << N);
	ini /= sqrt(1 << N);
	circ1.set_input(ini);
	circ2.set_input(ini);

	for(uint32_t k = 0; k < 9; ++k)
	{
		double v = nd(re);
		variables1[k] = v;
		variables2[k] = v;
	}

	for(uint32_t _instance = 0; _instance < 100; ++_instance)
	{ // instance loop
		circ1.clear_evaluated();
		circ2.clear_evaluated();

		for(uint32_t k = 0; k < 9; ++k)
		{
			variables1[k].zero_grad();
			variables2[k].zero_grad();
		}

		Eigen::VectorXcd output1 = *circ1.output();
		Eigen::VectorXcd output2 = *circ2.output();

		REQUIRE((output1 - output2).norm() < 1e-6);

		circ1.derivs();
		circ2.derivs();

		for(uint32_t k = 0; k < 9; ++k)
		{
			Eigen::VectorXcd grad1 = *variables1[k].grad();
			Eigen::VectorXcd grad2 = *variables1[k].grad();
			REQUIRE((grad1 - grad2).norm() < 1e-6);
		}

		for(uint32_t k = 0; k < 9; ++k)
		{
			variables1[k] -= 0.01;
			variables2[k] -= 0.01;
		}
	}
}

max_stars_repo_name: chaeyeunpark/Yavque

max_issues_repo_name: chaeyeunpark/Yavque

max_forks_repo_name: chaeyeunpark/Yavque


text:
#pragma once

#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h> // strchr
#include <boost/noncopyable.hpp>
#include <terark/config.hpp>
#include <terark/stdtypes.hpp>
#include <terark/fstring.hpp>
#include <terark/bitmap.hpp>

namespace terark {

// layout compatible to fstring & valvec
struct TERARK_DLL_EXPORT LineBuf : boost::noncopyable {
	char*  p;
	size_t n;
	size_t capacity;

	typedef char* iterator;
	typedef char* const_iterator;

	explicit LineBuf(FILE*, size_t align = 0);
	explicit LineBuf(fstring fname, size_t align = 0);
	LineBuf();
	~LineBuf();

	ptrdiff_t getline(FILE* f); ///<  is thread safe on glibc
	ptrdiff_t getbson(FILE* f); ///< not thread safe

	bool  empty() const { return 0 == n; }
	size_t size() const { return n; }
	char*  data() const { return p; }
	char* begin() const { return p; }
	char*   end() const { return p + n; }

	void swap(LineBuf& y) {
		std::swap(capacity, y.capacity);
		std::swap(n, y.n);
		std::swap(p, y.p);
	}

	void clear();
	void erase_all() { n = 0; }

	void risk_release_ownership() { p = NULL; n = 0; capacity = 0; }
	void risk_swap_valvec(valvec<char>& vv) {
		char*  p1 = p; p = vv.data(); vv.risk_set_data(p1);
		size_t n1 = n; n = vv.size(); vv.risk_set_size(n1);
		size_t c1 = capacity; capacity = vv.capacity(); vv.risk_set_capacity(c1);
	}
	void risk_swap_valvec(valvec<byte_t>& vv) {
		auto   p1 = (byte_t*)p; p = (char*)vv.data(); vv.risk_set_data(p1);
		size_t n1 = n; n = vv.size(); vv.risk_set_size(n1);
		size_t c1 = capacity; capacity = vv.capacity(); vv.risk_set_capacity(c1);
	}
	const fstring& risk_to_fstring_ref() const {
	    return *reinterpret_cast<const fstring*>(this);
	}

	///@{
	///@return removed bytes
	size_t trim();  // remove all trailing spaces, including '\r' and '\n'
	size_t chomp(); // remove all trailing '\r' and '\n', just as chomp in perl
	///@}

	void push_back(char ch) {
		if (n + 1 < capacity) {
			p[n++] = ch;
			p[n] = '\0';
		}
		else {
			push_back_slow_path(ch);
		}
	}
private:
	void push_back_slow_path(char ch);
public:

	unsigned char operator[](size_t i) const {
		assert(nullptr != p);
		TERARK_ASSERT_LT(i, n);
		return p[i];
	}
	const char* c_str() const { assert(!p || '\0' == p[n]); return p; }
	operator fstring() const { return fstring(p, n); }

	/// split into fields
	template<class Vec>
	size_t split(fstring delims, Vec* F, size_t max_fields = ~size_t(0)) {
		F->resize(0);
		return split_append(delims, F, max_fields);
	}
	template<class Vec>
	size_t split_append(fstring delims, Vec* F, size_t max_fields = ~size_t(0)) {
		return split_f(delims, [F](char* col, char* next) {
			F->push_back(typename Vec::value_type(col, next));
		}, max_fields);
	}
	template<class PushFunc>
	size_t split_f(fstring delims, PushFunc push, size_t max_fields = ~size_t(0)) {
		size_t dlen = delims.size();
		if (0 == dlen) // empty delims redirect to blank delim
			return split_f<PushFunc>(' ', push, max_fields);
		if (1 == dlen)
			return split_f<PushFunc>(delims[0], push, max_fields);
		size_t fields = 0;
		char *col = p, *end = p + n;
		while (col < end && fields+1 < max_fields) {
			char* next = (char*)memmem(col, end-col, delims.data(), dlen);
			if (NULL == next) next = end;
			push(col, next), fields++;
			*next = 0;
			col = next + dlen;
		}
		if (col <= end)
			push(col, end), fields++;
		return fields;
	}

	template<class Vec>
	size_t split_by_any(fstring delims, Vec* F, size_t max_fields = ~size_t(0)) {
		F->resize(0);
		return split_by_any_append(delims, F, max_fields);
	}
	template<class Vec>
	size_t split_by_any_append(fstring delims, Vec* F, size_t max_fields = ~size_t(0)) {
		return split_by_any_f(delims, [F](char* col, char* next) {
			F->push_back(typename Vec::value_type(col, next));
		}, max_fields);
	}
	template<class PushFunc>
	size_t split_by_any_f(fstring delims, PushFunc push, size_t max_fields = ~size_t(0)) {
		size_t dlen = delims.size();
		if (0 == dlen) // empty delims redirect to blank delim
			return split_f<PushFunc>(' ', push, max_fields);
		if (1 == dlen)
			return split_f<PushFunc>(delims[0], push, max_fields);
		static_bitmap<256> bits;
		size_t fields = 0;
		for (size_t i = 0; i < delims.size(); ++i) bits.set1(delims[i]);
		char *col = p, *end = p + n;
		while (col < end && fields+1 < max_fields) {
			char* next = col;
			while (next < end && bits.is0((byte_t)*next)) ++next;
			push(col, next), fields++;
			*next = 0;
			col = next + 1;
		}
		if (col <= end)
			push(col, end), fields++;
		return fields;
	}
	template<class Vec>
	size_t split(const char delim, Vec* F, size_t max_fields = ~size_t(0)) {
		F->resize(0);
		return split_append(delim, F, max_fields);
	}
	template<class Vec>
	size_t split_append(const char delim, Vec* F, size_t max_fields = ~size_t(0)) {
		return split_f(delim, [F](char* col, char* next) {
			F->push_back(typename Vec::value_type(col, next));
		}, max_fields);
	}
	template<class PushFunc>
	size_t split_f(const char delim, PushFunc push, size_t max_fields = ~size_t(0)) {
		size_t fields = 0;
		if (' ' == delim) {
		   	// same as awk, skip first blank field, and skip dup blanks
			char *col = p, *end = p + n;
			while (col < end && isspace(*col)) ++col; // skip first blank field
			while (col < end && fields+1 < max_fields) {
				char* next = col;
				while (next < end && !isspace(*next)) ++next;
				push(col, next), fields++;
				while (next < end &&  isspace(*next)) *next++ = 0; // skip blanks
				col = next;
			}
			if (col < end)
				push(col, end), fields++;
		}
		else {
			char *col = p, *end = p + n;
			while (col < end && fields+1 < max_fields) {
				char* next = col;
				while (next < end && delim != *next) ++next;
				push(col, next), fields++;
				*next = 0;
				col = next + 1;
			}
			if (col <= end)
				push(col, end), fields++;
		}
		return fields;
	}

	/// @params[out] offsets: length of offsets must >= arity+1
	///  on return, offsets[arity] saves tuple data length
	bool read_binary_tuple(int32_t* offsets, size_t arity, FILE* f);

	LineBuf& read_all(FILE*, size_t align = 0);
	LineBuf& read_all(fstring fname, size_t align = 0);
};

} // namespace terark

max_stars_repo_name: rockeet/terark-zip

max_issues_repo_name: rockeet/terark-zip

max_forks_repo_name: rockeet/terark-zip


text:
#include <iostream>
#include <cassert>
#include <boost/graph/adjacency_matrix.hpp>
#include <boost/graph/prim_minimum_spanning_tree.hpp>

const int debug_level = 0;

#define DEBUG(min_level, x)      \
  if (debug_level >= min_level)  \
  {                              \
    std::cerr << x << std::endl; \
  }

typedef std::tuple<int, int, int> RawEdgeWeight;
typedef boost::adjacency_matrix<boost::directedS, boost::no_property, boost::property<boost::edge_weight_t, long>> Graph;

struct MstEdge
{
  int cost, from, to;
};

void testcase()
{
  int n, root_i;
  std::cin >> n >> root_i;
  assert(n >= 3 && n <= 1e3 && root_i >= 1 && root_i <= n);
  root_i--;

  Graph G(n);
  std::vector<std::vector<int>> edge_costs(n, std::vector<int>(n));
  for (int i = 0; i < n; i++)
  {
    for (int j = i + 1; j < n; j++)
    {
      int cost;
      std::cin >> cost;
      assert(cost >= 1 && cost <= (1 << 20));

      edge_costs.at(i).at(j) = cost;
      edge_costs.at(j).at(i) = cost;

      boost::add_edge(i, j, long(cost) << 20 | long(n - j) << 10 | long(n - i), G);
      boost::add_edge(j, i, long(cost) << 20 | long(n - i) << 10 | long(n - j), G);
    }
  }

  std::vector<Graph::vertex_descriptor> predecessors(n);
  boost::prim_minimum_spanning_tree(G, predecessors.data(), boost::root_vertex(root_i));

  auto weights = boost::get(boost::edge_weight, G);
  int leia_cost = 0;
  for (int i = 0; i < n; i++)
  {
    const Graph::vertex_descriptor p = predecessors.at(i);
    if (int(p) == i)
    {
      DEBUG(3, "same predecessor " << i);
      assert(i == root_i);
      continue;
    }

    const int cost = edge_costs.at(p).at(i);
    DEBUG(3, "p " << p << " to i " << i << " costs " << cost);
    assert(cost >= 1 && cost <= (1 << 20));
    leia_cost += cost;
  }
  DEBUG(2, "leia_cost " << leia_cost);

  auto max_cost_between_endpoints = [root_i](const std::vector<std::pair<int, int>> &path_a, const std::vector<std::pair<int, int>> &path_b) {
    auto it_a = path_a.rbegin(), it_b = path_b.rbegin();
    while (it_a != path_a.rend() && it_b != path_b.rend() && it_a->first == it_b->first)
    {
      it_a++;
      it_b++;
    }
    int max_cost = 0;
    if (it_a != path_a.rend())
    {
      max_cost = std::max(max_cost, it_a->second);
    }
    if (it_b != path_b.rend())
    {
      max_cost = std::max(max_cost, it_b->second);
    }
    return max_cost;
  };

  std::vector<std::vector<std::pair<int, int>>> paths_to_root(n);
  for (int i = 0; i < n; i++)
  {
    std::vector<std::pair<int, int>> &path = paths_to_root.at(i);
    int j = i;
    int max_cost = 0;
    while (true)
    {
      const int p = predecessors.at(j);
      if (p == j)
      {
        break;
      }
      const int cost = edge_costs.at(p).at(j);
      max_cost = std::max(max_cost, cost);
      path.push_back(std::make_pair(j, max_cost));
      j = p;
    }
  }

  int min_total_cost = std::numeric_limits<int>::max();
  for (int from = 0; from < n; from++)
  {
    for (int to = from + 1; to < n; to++)
    {
      DEBUG(3, "considering adding edge " << from << " " << to);

      if (int(predecessors.at(from)) == to || int(predecessors.at(to)) == from)
      {
        DEBUG(3, "edge already in mst");
        continue;
      }

      const int added_cost = edge_costs.at(from).at(to);
      const int removed_cost = max_cost_between_endpoints(paths_to_root.at(from), paths_to_root.at(to));
      DEBUG(3, "added_cost " << added_cost << " removed_cost " << removed_cost);
      assert(added_cost >= removed_cost);

      const int this_total_cost = leia_cost - removed_cost + added_cost;
      if (this_total_cost < min_total_cost)
      {
        min_total_cost = this_total_cost;
        DEBUG(3, "lowered min_total_cost " << min_total_cost);
      }
    }
  }

  std::cout << min_total_cost << "\n";
}

int main()
{
  std::ios_base::sync_with_stdio(false);

  int t;
  std::cin >> t;
  for (int i = 0; i < t; i++)
  {
    testcase();
    DEBUG(1, "");
  }

  return 0;
}

max_stars_repo_name: tehwalris/algolab

max_issues_repo_name: tehwalris/algolab

max_forks_repo_name: tehwalris/algolab


text:
#include <gtest/gtest.h>
#include <cmath>
#include <vector>
#include <Eigen/Dense>
#include "pid_controller/pid_controller.h"

namespace controls
{

    class PID_Test : public ::testing::Test
    {
        protected:
        /// Pointer for Kalman Filter object
        std::shared_ptr<PID_Controller> pid_ptr;
        double kp, ki, kd;
        double max, min;
        double imax, imin;
        double init_val;
        double fltr_coef;

        virtual void SetUp()
        {
            kp = 0.0F;
            ki = 0.0F;
            kd = 0.0F;
            max = 10.0F;
            min = -max;
            imax = 3.0F;
            imin = -imax;
            init_val = 0.0F;
            fltr_coef = 1.0F;
            pid_ptr = std::make_shared<PID_Controller>(kp, ki, kd, max, min, imax, imin, init_val, fltr_coef);
        }

        virtual void TearDown()
        {
        }
    };

    TEST_F(PID_Test, PTEST)
    {
        double kp = 3.0F;
        double ki = 0.0F;
        double kd = 0.0F;
        double dT = 0.1F;
        bool result = false;

        Eigen::VectorXd error(63);          /// Control Error
        Eigen::VectorXd pid_expected(63);   /// Expected
        Eigen::VectorXd pid_out(63);        /// Controller Output
        double cmp_error = 0.0F;            /// Compare Error
        double mae = 0.0F;                  /// Mean Abs Error

        pid_ptr->Init();
        pid_ptr->Update_Gains(kp, ki, kd);
        pid_ptr->Update_dT(dT);

        /// Run Controler with 5.17 deg/100ms error signal
        for(int i=0; i<63; i++)
        {
            error(i) = sin(i*dT);
            pid_expected(i) = kp*error(i);
            pid_out(i) = pid_ptr->Step(error(i));
            cmp_error = pid_expected(i) - pid_out(i);
            mae += cmp_error;
        }

        /// Mean Absolute Error
        mae /= 63;
        if(fabs(mae) < 1e-6)
        {
            result = true;
        }
        else
        {
            result = false;
            std::cerr << "PTest Mean Absolute Arror: " << mae << std::endl;
        }
        EXPECT_TRUE(result);
    }

    TEST_F(PID_Test, ITEST)
    {
        double kp = 0.0F;
        double ki = 1.0F;
        double kd = 0.0F;
        double dT = 0.01F;
        double imax = 5.0F;
        double imin = -5.0F;
        double initial_val = 0.0F;
        bool result = false;

        Eigen::VectorXd error(630);          /// Control Error
        Eigen::VectorXd pid_expected(630);   /// Expected
        Eigen::VectorXd pid_out(630);        /// Controller Output
        double cmp_error = 0.0F;            /// Compare Error
        double mae = 0.0F;                  /// Mean Abs Error

        /// Initialize Controller
        pid_ptr->Init();
        pid_ptr->Update_I_Sat_Limit(imax, imin);
        pid_ptr->Update_InitVal(initial_val);
        pid_ptr->Update_Gains(kp, ki, kd);
        pid_ptr->Update_dT(dT);

        /// Run Controler with 0.57 deg/10ms error signal
        for(int i=0; i<630; i++)
        {
            error(i) = sin(i*dT);

            pid_expected(i) = ki*1.0F-cos(i*dT);
            pid_out(i) = pid_ptr->Step(error(i));
            cmp_error = pid_expected(i) - pid_out(i);
            mae += cmp_error;
        }

        /// Mean Absolute Error
        mae /= 630;
        if(fabs(mae) < 0.002)
        {
            result = true;
        }
        else
        {
            result = false;
            std::cerr << "ITest Mean Absolute Error: " << mae << std::endl;
        }
        EXPECT_TRUE(result);
    }

    TEST_F(PID_Test, ISAT_TEST)
    {
        double kp = 0.0F;
        double ki = 1.0F;
        double kd = 0.0F;
        double dT = 0.01F;
        double max = 1.0F;
        double min = -1.0F;
        double imax = 0.5F;
        double imin = -0.5F;
        double initial_val = 0.0F;
        bool result = false;

        double pid_out;        /// Controller Output
        double error;          /// Controller Error

        /// Initialize Controller
        pid_ptr->Init();
        pid_ptr->Update_Sat_Limit(max, min);
        pid_ptr->Update_I_Sat_Limit(imax, imin);
        pid_ptr->Update_InitVal(initial_val);
        pid_ptr->Update_Gains(kp, ki, kd);
        pid_ptr->Update_dT(dT);

        /// Run Controler with 0.57 deg/10ms error signal
        for(int i=0; i<1260; i++)
        {
            error = sin(i*dT);
            pid_out = pid_ptr->Step(error);
            if(pid_out > imax || pid_out < imin)
            {
                result = false;
                std::cerr << "PID_OUT: " << pid_out << "   I LIM +/-: "
                          << imax << std::endl;
            }
        }
        EXPECT_TRUE(result);
    }

    TEST_F(PID_Test, PIDSAT_DYN_UPDATE_TEST)
    {
        double kp = 1.0F;
        double ki = 2.0F;
        double kd = 0.0F;
        double dT = 0.01F;
        double max = 1.6F;
        double min = 1.6F;
        double imax = 0.5F;
        double imin = 0.5F;
        double initial_val = 0.0F;
        bool result = false;

        double pid_out;        /// Controller Output
        double error;          /// Controller Error

        /// Initialize Controller
        pid_ptr->Init();
        pid_ptr->Update_Sat_Limit(max, min);
        pid_ptr->Update_I_Sat_Limit(imax, imin);
        pid_ptr->Update_InitVal(initial_val);
        pid_ptr->Update_Gains(kp, ki, kd);
        pid_ptr->Update_dT(dT);

        /// Run Controler with 0.57 deg/10ms error signal
        for(int i=0; i<1260; i++)
        {

            if(i < 315)
            {
                error = 1.0F;
            }
            else if (i == 315)
            {
                /// Dynamically Update P-Gain so that PID Limit is Exercised
                /// At this point, the I term should be saturated at 0.5F
                /// The PID Out should be Saturated at 1.5F (I:0.5F P:1.0F)
                kp = 5.0F;
                pid_ptr->Update_Gains(kp, ki, kd);
            }
            else if(i == 630)
            {
                error = -1.0F;
                kp = 1.0F;
                pid_ptr->Update_Gains(kp, ki, kd);
            }
            else if(i == 945)
            {
                /// Same Strategy as above but Exercising the negative limit
                kp = 5.0F;
                pid_ptr->Update_Gains(kp, ki, kd);
            }

            /// Step PID Controller
            pid_out = pid_ptr->Step(error);

            if(pid_out > max || pid_out < min)
            {
                result = false;
                std::cerr << "PID_OUT: " << pid_out << "   PID LIM +/-: "
                          << max << std::endl;
            }
        }
        EXPECT_TRUE(result);
    }

    TEST_F(PID_Test, DTERM_LPF_TEST)
    {
        double kp = 0.0F;
        double ki = 0.0F;
        double kd = 1.0F;
        double dT = 0.01F;
        double fltr_coef = 0.75F;
        double initial_val = 0.0F;
        bool result = false;

        Eigen::VectorXd error(315);        /// Control Error
        Eigen::VectorXd pid_expected(315); /// Expected
        Eigen::VectorXd pid_out(315);      /// Controller Output
        double cmp_error = 0.0F;            /// Compare Error
        double mae = 0.0F;                  /// Mean Abs Error
        double rmse = 0.0F;                 //RMSE

        /// Initialize Controller
        pid_ptr->Init();
        pid_ptr->Update_InitVal(initial_val);
        pid_ptr->Update_Gains(kp, ki, kd);
        pid_ptr->Update_D_Filter(fltr_coef);
        pid_ptr->Update_dT(dT);

        /// Run Controler with 0.57 deg/10ms error signal
        for(int i=0; i<315; i++)
        {
            error(i) = sin(i*dT);
            pid_expected(i) = kd*cos(i*dT);

            /// Inject Transient
            /// RMSE NO Transient No LPF:           0.0564541
            /// RMSE With Transient No LPF:         0.069098
            /// RMSE No Tranisent With COEF 0.75:   0.0584871
            /// RMSE Transient With COEF 0.75       0.0643062
            if(i == 310)
            {
                error(i) = 0.005F+error(i);
            }

            pid_out(i) = pid_ptr->Step(error(i));
            cmp_error = pid_expected(i) - pid_out(i);
            mae += cmp_error;
            rmse += cmp_error *cmp_error;
        }

        mae /= 315;
        rmse /= 315;
        rmse = sqrt(rmse);

        if(rmse > 0.065F)
        {
            result = false;
            std::cerr << "RMSE: " << rmse << std::endl;
            std::cerr << "MAE: " << mae << std::endl;
        }

        EXPECT_TRUE(result);
    }

    TEST_F(PID_Test, DTEST)
    {
        double kp = 0.0F;
        double ki = 0.0F;
        double kd = 1.3F;
        double dT = 0.01F;
        bool result = false;

        Eigen::VectorXd error(630);          /// Control Error
        Eigen::VectorXd pid_expected(630);   /// Expected
        Eigen::VectorXd pid_out(630);        /// Controller Output
        double cmp_error = 0.0F;            /// Compare Error
        double mae = 0.0F;
        double rmse = 0.0F;                  /// Mean Abs Error

        /// Initialize Controller
        pid_ptr->Init();
        pid_ptr->Update_Gains(kp, ki, kd);
        pid_ptr->Update_dT(dT);

        /// Run Controler with 0.57 deg/10ms error signal
        for(int i=0; i<630; i++)
        {
            error(i) = sin(i*dT);

            pid_expected(i) = kd*cos(i*dT);
            pid_out(i) = pid_ptr->Step(error(i));
            cmp_error = pid_expected(i) - pid_out(i);
            mae += cmp_error;
            cmp_error = cmp_error * cmp_error;
            rmse += cmp_error;
        }

        /// Mean Absolute Error
        mae /= 630;
        rmse /= 630;
        rmse = sqrt(rmse);
        //std::cerr << "DTest RMSE " << rmse << std::endl;
        //std::cerr << "DTest MAE " << mae << std::endl;
        if(fabs(mae) < 0.005)
        {
            result = true;
        }
        else
        {
            result = false;
            std::cerr << "DTest Mean Absolute Error: " << mae << std::endl;
        }
        EXPECT_TRUE(result);
    }
};

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
//
//  objParser1.cpp
// Kuplung
//
//  Created by Sergey Petrov on 11/19/15.
//  Copyright © 2015 supudo.net. All rights reserved.
//

#include "objParser1.hpp"
#include <fstream>
#include <numeric>
#include <sstream>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>

objParser1::~objParser1() {
}

void objParser1::init(const std::function<void(float)>& doProgress) {
    this->models = {};
    this->materials = {};
    this->doProgress = doProgress;
    this->objFileLinesCount = 0;

    this->regex_comment = "^#.*";
    this->regex_whiteSpace = "\\s";

    this->regex_objTitle = "^o.*";
    this->regex_geometricVertices = "^v\\s.*";
    this->regex_textureCoordinates = "^vt\\s.*";
    this->regex_vertexNormals = "^vn\\s.*";
    this->regex_spaceVertices = "^vp\\s.*";
    this->regex_polygonalFaces = "^f\\s.*";
    this->regex_polygonalFacesSingle = "[/\\\\]";
    this->regex_materialFile = "^mtllib\\s.*";
    this->regex_useMaterial = "^usemtl\\s.*";
    this->regex_materialNew = "^newmtl\\s.*";

    this->regex_materialAmbientColor = "^Ka\\s.*";
    this->regex_materialDiffuseColor = "^Kd\\s.*";
    this->regex_materialSpecularColor = "^Ks\\s.*";
    this->regex_materialEmissionColor = "^Ke\\s.*";
    this->regex_materialSpecularExp = "^Ns\\s.*";
    this->regex_materialTransperant1 = "^Tr\\s.*";
    this->regex_materialTransperant2 = "^d\\s.*";
    this->regex_materialOpticalDensity = "^Ni\\s.*";
    this->regex_materialIllumination = "^illum\\s.*";
    this->regex_materialTextureAmbient = "^map_Ka\\s.*";
    this->regex_materialTextureDiffuse = "^map_Kd\\s.*";
    this->regex_materialTextureBump = "^map_Bump\\s.*";
    this->regex_materialTextureDisplacement = "^disp\\s.*";
    this->regex_materialTextureSpecular = "^map_Ks\\s.*";
    this->regex_materialTextureSpecularExp = "^map_Ns\\s.*";
    this->regex_materialTextureDissolve = "^map_d\\s.*";

    this->parserUtils = std::make_unique<ParserUtils>();
}

std::vector<MeshModel> objParser1::parse(const FBEntity& fileToParse, const std::vector<std::string>&) {
    this->file = fileToParse;
    this->geometricVertices = {};
    this->textureCoordinates = {};
    this->vertexNormals = {};
    this->spaceVertices = {};
    this->polygonalFaces = {};
    this->models = {};
    this->materials = {};

    std::FILE *fp = std::fopen(this->file.path.c_str(), "rb");
    if (fp) {
        std::string fileContents;
        std::fseek(fp, 0, SEEK_END);
        fileContents.resize(std::ftell(fp));
        std::rewind(fp);
        std::fread(&fileContents[0], 1, fileContents.size(), fp);
        std::fclose(fp);

        size_t pos = 0;
        std::string singleLine;

        int indexModel = -1;
        int indicesCounter = 0;

        this->objFileLinesCount = this->getLineCount();
        int linesProcessedCounter = 0;

        int modelID = 1;
        while ((pos = fileContents.find(Settings::Instance()->newLineDelimiter)) != std::string::npos) {
            singleLine = fileContents.substr(0, pos);

            if (singleLine.empty() || std::regex_match(singleLine, this->regex_comment)) {
                fileContents.erase(0, pos + Settings::Instance()->newLineDelimiter.length());
                continue;
            }

            std::vector<std::string> lineElements = this->splitString(singleLine, this->regex_whiteSpace);
            lineElements.erase(lineElements.begin());

            if (std::regex_match(singleLine, this->regex_objTitle) || std::regex_match(singleLine, this->regex_materialFile)) {
                if (std::regex_match(singleLine, this->regex_objTitle)) {
                    MeshModel entityModel;
                    entityModel.ID = modelID;
                    entityModel.File = file;
                    entityModel.ModelTitle = std::accumulate(begin(lineElements), end(lineElements), entityModel.ModelTitle);
                    entityModel.countVertices = 0;
                    entityModel.countTextureCoordinates = 0;
                    entityModel.countNormals = 0;
                    entityModel.countIndices = 0;
                    indexModel += 1;
                    modelID += 1;
                    this->models.push_back(entityModel);
                }
            }

            if (std::regex_match(singleLine, this->regex_materialFile))
                this->materials = this->loadMaterial(lineElements[0]);
            else if (std::regex_match(singleLine, this->regex_geometricVertices)) {
                std::vector<float> points = this->string2float(lineElements);
                this->geometricVertices.insert(end(this->geometricVertices), begin(points), end(points));
                //this->vectorsVertices.push_back(glm::vec3(points[0], points[1], points[2]));
            }
            else if (std::regex_match(singleLine, this->regex_textureCoordinates)) {
                std::vector<float> points = this->string2float(lineElements);
                this->textureCoordinates.insert(end(this->textureCoordinates), begin(points), end(points));
            }
            else if (std::regex_match(singleLine, this->regex_vertexNormals)) {
                std::vector<float> points = this->string2float(lineElements);
                this->vertexNormals.insert(end(this->vertexNormals), begin(points), end(points));
            }
            else if (std::regex_match(singleLine, this->regex_spaceVertices)) {
                std::vector<float> points = this->string2float(lineElements);
                this->spaceVertices.insert(end(this->spaceVertices), begin(points), end(points));
            }
            else if (std::regex_match(singleLine, this->regex_useMaterial)) {
                this->models[static_cast<size_t>(indexModel)].MaterialTitle = singleLine;
                boost::replace_all(this->models[static_cast<size_t>(indexModel)].MaterialTitle, "usemtl ", "");
            }
            else if (std::regex_match(singleLine, this->regex_polygonalFaces)) {
                std::vector<std::string> singleFaceElements = this->splitString(singleLine, this->regex_whiteSpace);
                singleFaceElements.erase(singleFaceElements.begin());

                for (size_t i=0; i<singleFaceElements.size(); i++) {
                    std::vector<std::string> face = this->splitString(singleFaceElements[i], this->regex_polygonalFacesSingle);

                    int v_idx = (std::stoi(face[0]) - 1) * 3;
                    glm::vec3 v_v = glm::vec3(this->geometricVertices[static_cast<size_t>(v_idx + 0)],
                            this->geometricVertices[static_cast<size_t>(v_idx + 1)],
                            this->geometricVertices[static_cast<size_t>(v_idx + 2)]);
                    this->models[static_cast<size_t>(indexModel)].vertices.push_back(v_v);
                    this->models[static_cast<size_t>(indexModel)].countVertices += 3;

                    if (this->textureCoordinates.size() > 0 && !face[1].empty()) {
                        int t_idx = (std::stoi(face[1]) - 1) * 2;
                        glm::vec2 v_tc = glm::vec2(this->textureCoordinates[static_cast<size_t>(t_idx + 0)],
                                this->textureCoordinates[static_cast<size_t>(t_idx + 1)]);
                        this->models[static_cast<size_t>(indexModel)].texture_coordinates.push_back(v_tc);
                        this->models[static_cast<size_t>(indexModel)].countTextureCoordinates += 2;
                    }

                    int n_idx = (std::stoi(face[2]) - 1) * 3;
                    glm::vec3 v_n = glm::vec3(this->vertexNormals[static_cast<size_t>(n_idx + 0)],
                            this->vertexNormals[static_cast<size_t>(n_idx + 1)],
                            this->vertexNormals[static_cast<size_t>(n_idx + 2)]);
                    this->models[static_cast<size_t>(indexModel)].normals.push_back(v_n);
                    this->models[static_cast<size_t>(indexModel)].countNormals += 3;

                    this->models[static_cast<size_t>(indexModel)].indices.push_back(static_cast<unsigned int>(indicesCounter));
                    this->models[static_cast<size_t>(indexModel)].countIndices += 1;
                    indicesCounter += 1;
                }
            }

            linesProcessedCounter += 1;
            float progress = (float(linesProcessedCounter) / float(this->objFileLinesCount)) * 100.0f;
            this->doProgress(progress);
            fileContents.erase(0, pos + Settings::Instance()->newLineDelimiter.length());
        }
    }
    for (size_t i=0; i<this->models.size(); i++) {
        this->models[i].ModelMaterial = this->findMaterial(this->models[i].MaterialTitle);
    }

    //Kuplung_printObjModels(this->models, false);

    return this->models;
}

MeshModelMaterial objParser1::findMaterial(std::string const& materialID) {
    for (size_t i=0; i<this->materials.size(); i++) {
        if (materialID == this->materials[i].MaterialTitle)
            return this->materials[i];
    }
    return {};
}

std::vector<MeshModelMaterial> objParser1::loadMaterial(std::string const& materialFile) {
    std::vector<MeshModelMaterial> current_materials;

    std::string materialPath = this->file.path.substr(0, this->file.path.find_last_of("\\/")) + "/" + materialFile;
    std::FILE *fp = std::fopen(materialPath.c_str(), "rb");
    if (fp) {
        std::string fileContents;
        std::fseek(fp, 0, SEEK_END);
        fileContents.resize(std::ftell(fp));
        std::rewind(fp);
        std::fread(&fileContents[0], 1, fileContents.size(), fp);
        std::fclose(fp);

        size_t pos = 0;
        std::string singleLine;

        int indexMaterial = -1;

        while ((pos = fileContents.find(Settings::Instance()->newLineDelimiter)) != std::string::npos) {
            singleLine = fileContents.substr(0, pos);
            std::vector<std::string> lineElements = this->splitString(singleLine, this->regex_whiteSpace);
            lineElements.erase(lineElements.begin());

            std::ostringstream cleanLineOS;
            //copy(lineElements.begin(), lineElements.end(), std::ostream_iterator<std::string>(cleanLineOS, " "));
            copy(lineElements.begin(), lineElements.end(), std::ostream_iterator<std::string>(cleanLineOS, ""));
            std::string cleanLine = cleanLineOS.str();

            if (singleLine.empty() || std::regex_match(singleLine, this->regex_comment)) {
                fileContents.erase(0, pos + Settings::Instance()->newLineDelimiter.length());
                continue;
            }

            if (std::regex_match(singleLine, this->regex_materialNew)) {
                MeshModelMaterial entityMaterial = {};
                entityMaterial.MaterialTitle = std::accumulate(begin(lineElements), end(lineElements), entityMaterial.MaterialTitle);
                entityMaterial.SpecularExp = 1.0;
                entityMaterial.Transparency = 1.0;
                entityMaterial.IlluminationMode = 2;
                entityMaterial.OpticalDensity = 1.0;
                indexMaterial += 1;
				current_materials.push_back(entityMaterial);
            }

            if (std::regex_match(singleLine, this->regex_materialAmbientColor)) {
                std::vector<float> points = this->string2float(lineElements);
				current_materials[static_cast<size_t>(indexMaterial)].AmbientColor.r = points[0];
				current_materials[static_cast<size_t>(indexMaterial)].AmbientColor.g = points[1];
				current_materials[static_cast<size_t>(indexMaterial)].AmbientColor.b = points[2];
            }
            else if (std::regex_match(singleLine, this->regex_materialDiffuseColor)) {
                std::vector<float> points = this->string2float(lineElements);
				current_materials[static_cast<size_t>(indexMaterial)].DiffuseColor.r = points[0];
				current_materials[static_cast<size_t>(indexMaterial)].DiffuseColor.g = points[1];
				current_materials[static_cast<size_t>(indexMaterial)].DiffuseColor.b = points[2];
            }
            else if (std::regex_match(singleLine, this->regex_materialSpecularColor)) {
                std::vector<float> points = this->string2float(lineElements);
				current_materials[static_cast<size_t>(indexMaterial)].SpecularColor.r = points[0];
				current_materials[static_cast<size_t>(indexMaterial)].SpecularColor.g = points[1];
				current_materials[static_cast<size_t>(indexMaterial)].SpecularColor.b = points[2];
            }
            else if (std::regex_match(singleLine, this->regex_materialEmissionColor)) {
                std::vector<float> points = this->string2float(lineElements);
				current_materials[static_cast<size_t>(indexMaterial)].EmissionColor.r = points[0];
				current_materials[static_cast<size_t>(indexMaterial)].EmissionColor.g = points[1];
				current_materials[static_cast<size_t>(indexMaterial)].EmissionColor.b = points[2];
            }
            else if (std::regex_match(singleLine, this->regex_materialSpecularExp))
				current_materials[static_cast<size_t>(indexMaterial)].SpecularExp = std::stof(lineElements[0]);
            else if (std::regex_match(singleLine, this->regex_materialTransperant1) || std::regex_match(singleLine, this->regex_materialTransperant2))
				current_materials[static_cast<size_t>(indexMaterial)].Transparency = std::stof(lineElements[0]);
            else if (std::regex_match(singleLine, this->regex_materialOpticalDensity))
				current_materials[static_cast<size_t>(indexMaterial)].OpticalDensity = std::stof(lineElements[0]);
            else if (std::regex_match(singleLine, this->regex_materialIllumination))
				current_materials[static_cast<size_t>(indexMaterial)].IlluminationMode = static_cast<unsigned int>(std::stof(lineElements[0]));
            else if (std::regex_match(singleLine, this->regex_materialTextureAmbient))
				current_materials[static_cast<size_t>(indexMaterial)].TextureAmbient = this->parseTextureImage(cleanLine);
            else if (std::regex_match(singleLine, this->regex_materialTextureDiffuse))
				current_materials[static_cast<size_t>(indexMaterial)].TextureDiffuse = this->parseTextureImage(cleanLine);
            else if (std::regex_match(singleLine, this->regex_materialTextureSpecular))
				current_materials[static_cast<size_t>(indexMaterial)].TextureSpecular = this->parseTextureImage(cleanLine);
            else if (std::regex_match(singleLine, this->regex_materialTextureSpecularExp))
				current_materials[static_cast<size_t>(indexMaterial)].TextureSpecularExp = this->parseTextureImage(cleanLine);
            else if (std::regex_match(singleLine, this->regex_materialTextureDissolve))
				current_materials[static_cast<size_t>(indexMaterial)].TextureDissolve = this->parseTextureImage(cleanLine);
            else if (std::regex_match(singleLine, this->regex_materialTextureBump))
				current_materials[static_cast<size_t>(indexMaterial)].TextureBump = this->parseTextureImage(cleanLine);
            else if (std::regex_match(singleLine, this->regex_materialTextureDisplacement))
				current_materials[static_cast<size_t>(indexMaterial)].TextureDisplacement = this->parseTextureImage(cleanLine);

            fileContents.erase(0, pos + Settings::Instance()->newLineDelimiter.length());
        }
    }

    return current_materials;
}

MeshMaterialTextureImage objParser1::parseTextureImage(std::string const& textureLine) {
    MeshMaterialTextureImage materialImage;

    materialImage.Height = 0;
    materialImage.Width = 0;
    materialImage.UseTexture = true;

    if (textureLine.find('-') != std::string::npos) {
        std::regex dash("-");
        std::vector<std::string> lineElements = this->splitString(textureLine, dash);

        if (lineElements[0].empty())
            lineElements.erase(lineElements.begin());

        std::vector<std::string> lastElements = this->splitString(lineElements[lineElements.size() - 1], this->regex_whiteSpace);
        materialImage.Image = lastElements[lastElements.size() - 1];
        lastElements.erase(lastElements.end() - 1);

        std::ostringstream lastCommandsOS;
        copy(lastElements.begin(), lastElements.end(), std::ostream_iterator<std::string>(lastCommandsOS, " "));
        std::string lastCommand = lastCommandsOS.str();
        lineElements[lineElements.size() - 1] = lastCommand;

        for (size_t i=0; i<lineElements.size(); i++) {
            materialImage.Commands.push_back("-" + lineElements[i]);
        }
    }
    else
        materialImage.Image = textureLine;

    std::string folderPath = this->file.path;
    boost::replace_all(folderPath, this->file.title, "");
    if (!boost::filesystem::exists(materialImage.Image) && !boost::filesystem::path(materialImage.Image).is_absolute())
        materialImage.Image = folderPath + materialImage.Image;

    std::regex pathSeparator("/");
    std::vector<std::string> fileElements = this->splitString(materialImage.Image, pathSeparator);
    materialImage.Filename = fileElements[fileElements.size() - 1];

    return materialImage;
}

std::vector<std::string> objParser1::splitString(const std::string &s, const std::regex& delimiter) {
    std::vector<std::string> elements;
    std::sregex_token_iterator iter(s.begin(), s.end(), delimiter, -1);
    std::sregex_token_iterator end;
    for ( ; iter != end; ++iter)
        elements.push_back(*iter);
    return elements;
}

std::vector<float> objParser1::string2float(const std::vector<std::string>& strings) {
    std::vector<float> floats;
    try {
        for (size_t i=0; i<strings.size(); i++) {
            floats.push_back(std::stof(strings[i]));
        }
    }
    catch (const std::exception &) { }
    return floats;
}

int objParser1::getLineCount() {
#ifdef _WIN32
    return 0;
#else
    char delim;
#if defined macintosh // OS 9
    delim = '\r';
#else
    delim = '\n';
#endif

    std::ifstream inFile2(this->file.path.c_str());
    int linesCount = int(std::count(std::istreambuf_iterator<char>(inFile2), std::istreambuf_iterator<char>(), delim));
    inFile2.close();
    return linesCount;
#endif
}

max_stars_repo_name: supudo/Kuplung

max_issues_repo_name: supudo/Kuplung

max_forks_repo_name: supudo/Kuplung