<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// Antioch - A Gas Dynamics Thermochemistry Library
//
// Copyright (C) 2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-
//
// $Id$
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------

// C++
#include <limits>
#include <string>
#include <vector>

// Antioch
#include "antioch/vector_utils.h"

#include "antioch/antioch_asserts.h"
#include "antioch/chemical_species.h"
#include "antioch/chemical_mixture.h"
#include "antioch/reaction_set.h"
#include "antioch/read_reaction_set_data_xml.h"
#include "antioch/cea_thermo.h"
#include "antioch/kinetics_evaluator.h"

template <typename Scalar>
int tester(const std::string& input_name)
{
  using std::abs;

  std::vector<std::string> species_str_list;
  const unsigned int n_species = 5;
  species_str_list.reserve(n_species);
  species_str_list.push_back( "N2" );
  species_str_list.push_back( "O2" );
  species_str_list.push_back( "N" );
  species_str_list.push_back( "O" );
  species_str_list.push_back( "NO" );

  Antioch::ChemicalMixture<Scalar> chem_mixture( species_str_list );
  Antioch::ReactionSet<Scalar> reaction_set( chem_mixture );
  Antioch::CEAThermodynamics<Scalar> thermo( chem_mixture );

  Antioch::read_reaction_set_data_xml<Scalar>( input_name, true, reaction_set );

  const Scalar T = 1500.0; // K
  const Scalar P = 1.0e5; // Pa

  // Mass fractions
  std::vector<Scalar> Y(n_species,0.2);

  const Scalar R_mix = chem_mixture.R(Y); // get R_tot in J.kg-1.K-1

  const Scalar rho = P/(R_mix*T); // kg.m-3

  std::vector<Scalar> molar_densities(n_species,0.0);
  chem_mixture.molar_densities(rho,Y,molar_densities);

  std::vector<Scalar> h_RT_minus_s_R(n_species);
  std::vector<Scalar> dh_RT_minus_s_R_dT(n_species);

  typedef typename Antioch::CEAThermodynamics<Scalar>::template Cache<Scalar> Cache;
  thermo.h_RT_minus_s_R(Cache(T),h_RT_minus_s_R);
  thermo.dh_RT_minus_s_R_dT(Cache(T),dh_RT_minus_s_R_dT);

  Antioch::KineticsEvaluator<Scalar> kinetics( reaction_set, 0 );

  std::vector<Scalar> omega_dot(n_species);
  std::vector<Scalar> omega_dot_2(n_species);
  std::vector<Scalar> domega_dot_dT(n_species);

  std::vector<std::vector<Scalar> > domega_dot_drho_s(n_species);
  for( unsigned int s = 0; s < n_species; s++ )
    {
      domega_dot_drho_s[s].resize(n_species);
    }

  kinetics.compute_mass_sources( T, molar_densities, h_RT_minus_s_R, omega_dot);

  kinetics.compute_mass_sources_and_derivs( T, molar_densities, h_RT_minus_s_R, dh_RT_minus_s_R_dT,
                                            omega_dot_2, domega_dot_dT, domega_dot_drho_s );

  for( unsigned int s = 0; s < n_species; s++)
    {
      std::cout << std::scientific << std::setprecision(16)
                << "domega_dot_dT(" << chem_mixture.chemical_species()[s]->species() << ") = "
                << domega_dot_dT[s] << std::endl;
    }

  for( unsigned int s = 0; s < n_species; s++)
    {
      for( unsigned int t = 0; t < n_species; t++)
        {
          std::cout << std::scientific << std::setprecision(16)
                    << "domega_dot_drho_s(" << chem_mixture.chemical_species()[s]->species()
                    << ", " << chem_mixture.chemical_species()[t]->species() << ") = "
                    << domega_dot_drho_s[s][t] << std::endl;
        }
    }

  int return_flag = 0;

  const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 100;

  // Regression values for omega_dot
  std::vector<Scalar> omega_dot_reg(n_species);
  omega_dot_reg[0] =  9.1627505878744108e+04;
  omega_dot_reg[1] = -3.3462516012726480e+05;
  omega_dot_reg[2] = -2.1139750128059302e+05;
  omega_dot_reg[3] =  1.9782333785216609e+05;
  omega_dot_reg[4] =  2.5657181767694763e+05;

  for( unsigned int s = 0; s < n_species; s++)
    {
      const Scalar rel_error = abs( (omega_dot[s] - omega_dot_reg[s])/omega_dot_reg[s]);
      if( rel_error > tol )
        {
          return_flag = 1;
        }
    }

  for( unsigned int s = 0; s < n_species; s++)
    {
      const Scalar rel_error = abs( (omega_dot_2[s] - omega_dot_reg[s])/omega_dot_reg[s]);
      if( rel_error > tol )
        {
          return_flag = 1;
        }
    }

  // Regression values for domega_dot_dT
  std::vector<Scalar> domega_dot_reg_dT(n_species);
  domega_dot_reg_dT[0] =  1.8015258435766250e+02;
  domega_dot_reg_dT[1] = -5.2724938565430807e+02;
  domega_dot_reg_dT[2] = -3.0930274177637205e+02;
  domega_dot_reg_dT[3] =  3.7973350053870610e+02;
  domega_dot_reg_dT[4] =  2.7666604253431154e+02;

  for( unsigned int s = 0; s < n_species; s++)
    {
      const Scalar rel_error = abs( (domega_dot_dT[s] - domega_dot_reg_dT[s])/domega_dot_reg_dT[s]);
      if( rel_error > tol )
        {
          return_flag = 1;
        }
    }

  // Regression values for domega_dot_drho_s
  std::vector<std::vector<Scalar> > domega_dot_reg_drhos(n_species);
  for( unsigned int s = 0; s < n_species; s++)
    {
      domega_dot_reg_drhos[s].resize(n_species);
    }

  domega_dot_reg_drhos[0][0] = 1.9677528466713775e+04;
  domega_dot_reg_drhos[0][1] = 1.7227676257862015e+04;
  domega_dot_reg_drhos[0][2] = 3.2160890543181915e+06;
  domega_dot_reg_drhos[0][3] = 1.4766530417926086e+05;
  domega_dot_reg_drhos[0][4] = 2.3225848421202623e+06;

  domega_dot_reg_drhos[1][0] =  8.8931540715994815e+03;
  domega_dot_reg_drhos[1][1] = -9.9561695971970223e+06;
  domega_dot_reg_drhos[1][2] = -9.8750240128648076e+06;
  domega_dot_reg_drhos[1][3] =  4.6145192628627969e+05;
  domega_dot_reg_drhos[1][4] =  8.3491261619680736e+03;

  domega_dot_reg_drhos[2][0] = -2.2422758857735978e+04;
  domega_dot_reg_drhos[2][1] = -4.3813526690025711e+06;
  domega_dot_reg_drhos[2][2] = -6.8345704383742884e+06;
  domega_dot_reg_drhos[2][3] = -5.4147327282847988e+05;
  domega_dot_reg_drhos[2][4] = -1.2268436930952054e+06;

  domega_dot_reg_drhos[3][0] = -1.2028768453121129e+04;
  domega_dot_reg_drhos[3][1] =  4.9714465900642881e+06;
  domega_dot_reg_drhos[3][2] =  5.7419784571182663e+06;
  domega_dot_reg_drhos[3][3] = -9.1126114233336027e+05;
  domega_dot_reg_drhos[3][4] =  1.2432112953400959e+06;

  domega_dot_reg_drhos[4][0] =  5.8808447725438464e+03;
  domega_dot_reg_drhos[4][1] =  9.3488479998774435e+06;
  domega_dot_reg_drhos[4][2] =  7.7515269398026383e+06;
  domega_dot_reg_drhos[4][3] =  8.4361718469629961e+05;
  domega_dot_reg_drhos[4][4] = -2.3473015705271205e+06;

  for( unsigned int s = 0; s < n_species; s++)
    {
      for( unsigned int t = 0; t < n_species; t++)
        {
          const Scalar rel_error = abs( (domega_dot_drho_s[s][t] - domega_dot_reg_drhos[s][t])/domega_dot_reg_drhos[s][t]);
          if( rel_error > tol )
            {
              return_flag = 1;
            }
        }
    }

  // Print out pretty message if there was a problem.
  if( return_flag == 1 )
    {
      std::cerr << "Error: Mismatch between compute mass source terms and regression values." << std::endl;
      for( unsigned int s = 0; s < n_species; s++)
	{
	  std::cout << std::scientific << std::setprecision(16)
		    << "omega_dot(" << chem_mixture.chemical_species()[s]->species() << ") = " << omega_dot[s]
		    << ", omega_dot_reg(" << chem_mixture.chemical_species()[s]->species() << ") = "
                    << omega_dot_reg[s] << std::endl << std::endl;
	}

      for( unsigned int s = 0; s < n_species; s++)
	{
	  std::cout << std::scientific << std::setprecision(16)
		    << "domega_dot_dT(" << chem_mixture.chemical_species()[s]->species() << ") = " << domega_dot_dT[s]
		    << ", domega_dot_reg_dT(" << chem_mixture.chemical_species()[s]->species() << ") = "
                    << domega_dot_reg_dT[s] << std::endl << std::endl;
	}

      for( unsigned int s = 0; s < n_species; s++)
	{
          for( unsigned int t = 0; t < n_species; t++)
            {
              std::cout << std::scientific << std::setprecision(16)
                        << "domega_dot_drho_s("
                        << chem_mixture.chemical_species()[s]->species()
                        << ", " << chem_mixture.chemical_species()[t]->species()
                        << ") = " << domega_dot_drho_s[s][t]
                        << ", domega_dot_reg_drho_s("
                        << chem_mixture.chemical_species()[s]->species()
                        << ", " << chem_mixture.chemical_species()[t]->species()
                        << ") = " << domega_dot_reg_drhos[s][t] << std::endl << std::endl;
            }
	}

    }

  return return_flag;
}

int main(int argc, char* argv[])
{
  // Check command line count.
  if( argc < 2 )
    {
      // TODO: Need more consistent error handling.
      std::cerr << "Error: Must specify reaction set XML input file." << std::endl;
      antioch_error();
    }

  return (tester<float>(std::string(argv[1])) ||
          tester<double>(std::string(argv[1])) /*||
          tester<long double>(std::string(argv[1])) || */
          );
}
<commit_msg>Bumping up regression tolerance<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// Antioch - A Gas Dynamics Thermochemistry Library
//
// Copyright (C) 2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-
//
// $Id$
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------

// C++
#include <limits>
#include <string>
#include <vector>

// Antioch
#include "antioch/vector_utils.h"

#include "antioch/antioch_asserts.h"
#include "antioch/chemical_species.h"
#include "antioch/chemical_mixture.h"
#include "antioch/reaction_set.h"
#include "antioch/read_reaction_set_data_xml.h"
#include "antioch/cea_thermo.h"
#include "antioch/kinetics_evaluator.h"

template <typename Scalar>
int tester(const std::string& input_name)
{
  using std::abs;

  std::vector<std::string> species_str_list;
  const unsigned int n_species = 5;
  species_str_list.reserve(n_species);
  species_str_list.push_back( "N2" );
  species_str_list.push_back( "O2" );
  species_str_list.push_back( "N" );
  species_str_list.push_back( "O" );
  species_str_list.push_back( "NO" );

  Antioch::ChemicalMixture<Scalar> chem_mixture( species_str_list );
  Antioch::ReactionSet<Scalar> reaction_set( chem_mixture );
  Antioch::CEAThermodynamics<Scalar> thermo( chem_mixture );

  Antioch::read_reaction_set_data_xml<Scalar>( input_name, true, reaction_set );

  const Scalar T = 1500.0; // K
  const Scalar P = 1.0e5; // Pa

  // Mass fractions
  std::vector<Scalar> Y(n_species,0.2);

  const Scalar R_mix = chem_mixture.R(Y); // get R_tot in J.kg-1.K-1

  const Scalar rho = P/(R_mix*T); // kg.m-3

  std::vector<Scalar> molar_densities(n_species,0.0);
  chem_mixture.molar_densities(rho,Y,molar_densities);

  std::vector<Scalar> h_RT_minus_s_R(n_species);
  std::vector<Scalar> dh_RT_minus_s_R_dT(n_species);

  typedef typename Antioch::CEAThermodynamics<Scalar>::template Cache<Scalar> Cache;
  thermo.h_RT_minus_s_R(Cache(T),h_RT_minus_s_R);
  thermo.dh_RT_minus_s_R_dT(Cache(T),dh_RT_minus_s_R_dT);

  Antioch::KineticsEvaluator<Scalar> kinetics( reaction_set, 0 );

  std::vector<Scalar> omega_dot(n_species);
  std::vector<Scalar> omega_dot_2(n_species);
  std::vector<Scalar> domega_dot_dT(n_species);

  std::vector<std::vector<Scalar> > domega_dot_drho_s(n_species);
  for( unsigned int s = 0; s < n_species; s++ )
    {
      domega_dot_drho_s[s].resize(n_species);
    }

  kinetics.compute_mass_sources( T, molar_densities, h_RT_minus_s_R, omega_dot);

  kinetics.compute_mass_sources_and_derivs( T, molar_densities, h_RT_minus_s_R, dh_RT_minus_s_R_dT,
                                            omega_dot_2, domega_dot_dT, domega_dot_drho_s );

  for( unsigned int s = 0; s < n_species; s++)
    {
      std::cout << std::scientific << std::setprecision(16)
                << "domega_dot_dT(" << chem_mixture.chemical_species()[s]->species() << ") = "
                << domega_dot_dT[s] << std::endl;
    }

  for( unsigned int s = 0; s < n_species; s++)
    {
      for( unsigned int t = 0; t < n_species; t++)
        {
          std::cout << std::scientific << std::setprecision(16)
                    << "domega_dot_drho_s(" << chem_mixture.chemical_species()[s]->species()
                    << ", " << chem_mixture.chemical_species()[t]->species() << ") = "
                    << domega_dot_drho_s[s][t] << std::endl;
        }
    }

  int return_flag = 0;

  const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 500;

  // Regression values for omega_dot
  std::vector<Scalar> omega_dot_reg(n_species);
  omega_dot_reg[0] =  9.1627505878744108e+04;
  omega_dot_reg[1] = -3.3462516012726480e+05;
  omega_dot_reg[2] = -2.1139750128059302e+05;
  omega_dot_reg[3] =  1.9782333785216609e+05;
  omega_dot_reg[4] =  2.5657181767694763e+05;

  for( unsigned int s = 0; s < n_species; s++)
    {
      const Scalar rel_error = abs( (omega_dot[s] - omega_dot_reg[s])/omega_dot_reg[s]);
      if( rel_error > tol )
        {
          return_flag = 1;
        }
    }

  for( unsigned int s = 0; s < n_species; s++)
    {
      const Scalar rel_error = abs( (omega_dot_2[s] - omega_dot_reg[s])/omega_dot_reg[s]);
      if( rel_error > tol )
        {
          return_flag = 1;
        }
    }

  // Regression values for domega_dot_dT
  std::vector<Scalar> domega_dot_reg_dT(n_species);
  domega_dot_reg_dT[0] =  1.8015258435766250e+02;
  domega_dot_reg_dT[1] = -5.2724938565430807e+02;
  domega_dot_reg_dT[2] = -3.0930274177637205e+02;
  domega_dot_reg_dT[3] =  3.7973350053870610e+02;
  domega_dot_reg_dT[4] =  2.7666604253431154e+02;

  for( unsigned int s = 0; s < n_species; s++)
    {
      const Scalar rel_error = abs( (domega_dot_dT[s] - domega_dot_reg_dT[s])/domega_dot_reg_dT[s]);
      if( rel_error > tol )
        {
          return_flag = 1;
        }
    }

  // Regression values for domega_dot_drho_s
  std::vector<std::vector<Scalar> > domega_dot_reg_drhos(n_species);
  for( unsigned int s = 0; s < n_species; s++)
    {
      domega_dot_reg_drhos[s].resize(n_species);
    }

  domega_dot_reg_drhos[0][0] = 1.9677528466713775e+04;
  domega_dot_reg_drhos[0][1] = 1.7227676257862015e+04;
  domega_dot_reg_drhos[0][2] = 3.2160890543181915e+06;
  domega_dot_reg_drhos[0][3] = 1.4766530417926086e+05;
  domega_dot_reg_drhos[0][4] = 2.3225848421202623e+06;

  domega_dot_reg_drhos[1][0] =  8.8931540715994815e+03;
  domega_dot_reg_drhos[1][1] = -9.9561695971970223e+06;
  domega_dot_reg_drhos[1][2] = -9.8750240128648076e+06;
  domega_dot_reg_drhos[1][3] =  4.6145192628627969e+05;
  domega_dot_reg_drhos[1][4] =  8.3491261619680736e+03;

  domega_dot_reg_drhos[2][0] = -2.2422758857735978e+04;
  domega_dot_reg_drhos[2][1] = -4.3813526690025711e+06;
  domega_dot_reg_drhos[2][2] = -6.8345704383742884e+06;
  domega_dot_reg_drhos[2][3] = -5.4147327282847988e+05;
  domega_dot_reg_drhos[2][4] = -1.2268436930952054e+06;

  domega_dot_reg_drhos[3][0] = -1.2028768453121129e+04;
  domega_dot_reg_drhos[3][1] =  4.9714465900642881e+06;
  domega_dot_reg_drhos[3][2] =  5.7419784571182663e+06;
  domega_dot_reg_drhos[3][3] = -9.1126114233336027e+05;
  domega_dot_reg_drhos[3][4] =  1.2432112953400959e+06;

  domega_dot_reg_drhos[4][0] =  5.8808447725438464e+03;
  domega_dot_reg_drhos[4][1] =  9.3488479998774435e+06;
  domega_dot_reg_drhos[4][2] =  7.7515269398026383e+06;
  domega_dot_reg_drhos[4][3] =  8.4361718469629961e+05;
  domega_dot_reg_drhos[4][4] = -2.3473015705271205e+06;

  for( unsigned int s = 0; s < n_species; s++)
    {
      for( unsigned int t = 0; t < n_species; t++)
        {
          const Scalar rel_error = abs( (domega_dot_drho_s[s][t] - domega_dot_reg_drhos[s][t])/domega_dot_reg_drhos[s][t]);
          if( rel_error > tol )
            {
              return_flag = 1;
            }
        }
    }

  // Print out pretty message if there was a problem.
  if( return_flag == 1 )
    {
      std::cerr << "Error: Mismatch between compute mass source terms and regression values." << std::endl;
      for( unsigned int s = 0; s < n_species; s++)
	{
	  std::cout << std::scientific << std::setprecision(16)
		    << "omega_dot(" << chem_mixture.chemical_species()[s]->species() << ") = " << omega_dot[s]
		    << ", omega_dot_reg(" << chem_mixture.chemical_species()[s]->species() << ") = "
                    << omega_dot_reg[s] << std::endl << std::endl;
	}

      for( unsigned int s = 0; s < n_species; s++)
	{
	  std::cout << std::scientific << std::setprecision(16)
		    << "domega_dot_dT(" << chem_mixture.chemical_species()[s]->species() << ") = " << domega_dot_dT[s]
		    << ", domega_dot_reg_dT(" << chem_mixture.chemical_species()[s]->species() << ") = "
                    << domega_dot_reg_dT[s] << std::endl << std::endl;
	}

      for( unsigned int s = 0; s < n_species; s++)
	{
          for( unsigned int t = 0; t < n_species; t++)
            {
              std::cout << std::scientific << std::setprecision(16)
                        << "domega_dot_drho_s("
                        << chem_mixture.chemical_species()[s]->species()
                        << ", " << chem_mixture.chemical_species()[t]->species()
                        << ") = " << domega_dot_drho_s[s][t]
                        << ", domega_dot_reg_drho_s("
                        << chem_mixture.chemical_species()[s]->species()
                        << ", " << chem_mixture.chemical_species()[t]->species()
                        << ") = " << domega_dot_reg_drhos[s][t] << std::endl << std::endl;
            }
	}

    }

  return return_flag;
}

int main(int argc, char* argv[])
{
  // Check command line count.
  if( argc < 2 )
    {
      // TODO: Need more consistent error handling.
      std::cerr << "Error: Must specify reaction set XML input file." << std::endl;
      antioch_error();
    }

  return (tester<float>(std::string(argv[1])) ||
          tester<double>(std::string(argv[1])) /*||
          tester<long double>(std::string(argv[1])) || */
          );
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#define BOOST_TEST_MODULE Bitcoin Test Suite

#include "main.h"
#include "txdb.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "db.h"
#include "wallet.h"
#endif

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

CWallet* pwalletMain;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    CCoinsViewDB *pcoinsdbview;
    boost::filesystem::path pathTemp;
    boost::thread_group threadGroup;

    TestingSetup() {
        fPrintToDebugLog = false; // don't want to write to debug.log file
        noui_connect();
#ifdef ENABLE_WALLET
        bitdb.MakeMock();
#endif
        pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
        boost::filesystem::create_directories(pathTemp);
        mapArgs["-datadir"] = pathTemp.string();
        pblocktree = new CBlockTreeDB(1 << 20, true);
        pcoinsdbview = new CCoinsViewDB(1 << 23, true);
        pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
        InitBlockIndex();
#ifdef ENABLE_WALLET
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
#endif
        nScriptCheckThreads = 3;
        for (int i=0; i < nScriptCheckThreads-1; i++)
            threadGroup.create_thread(&ThreadScriptCheck);
        RegisterNodeSignals(GetNodeSignals());
    }
    ~TestingSetup()
    {
        threadGroup.interrupt_all();
        threadGroup.join_all();
        UnregisterNodeSignals(GetNodeSignals());
#ifdef ENABLE_WALLET
        delete pwalletMain;
        pwalletMain = NULL;
#endif
        delete pcoinsTip;
        delete pcoinsdbview;
        delete pblocktree;
#ifdef ENABLE_WALLET
        bitdb.Flush(true);
#endif
        boost::filesystem::remove_all(pathTemp);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

<commit_msg>Fix test build after d138598<commit_after>// Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#define BOOST_TEST_MODULE Bitcoin Test Suite

#include "main.h"
#include "txdb.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "db.h"
#include "wallet.h"
#endif

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

CWallet* pwalletMain;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    CCoinsViewDB *pcoinsdbview;
    boost::filesystem::path pathTemp;
    boost::thread_group threadGroup;

    TestingSetup() {
        fPrintToDebugLog = false; // don't want to write to debug.log file
        noui_connect();
#ifdef ENABLE_WALLET
        bitdb.MakeMock();
#endif
        pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
        boost::filesystem::create_directories(pathTemp);
        mapArgs["-datadir"] = pathTemp.string();
        pblocktree = new CBlockTreeDB(1 << 20, true);
        pcoinsdbview = new CCoinsViewDB(1 << 23, true);
        pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
        InitBlockIndex();
#ifdef ENABLE_WALLET
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
#endif
        nScriptCheckThreads = 3;
        for (int i=0; i < nScriptCheckThreads-1; i++)
            threadGroup.create_thread(&ThreadScriptCheck);
        RegisterNodeSignals(GetNodeSignals());
    }
    ~TestingSetup()
    {
        threadGroup.interrupt_all();
        threadGroup.join_all();
        UnregisterNodeSignals(GetNodeSignals());
#ifdef ENABLE_WALLET
        delete pwalletMain;
        pwalletMain = NULL;
#endif
        delete pcoinsTip;
        delete pcoinsdbview;
        delete pblocktree;
#ifdef ENABLE_WALLET
        bitdb.Flush(true);
#endif
        boost::filesystem::remove_all(pathTemp);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

bool ShutdownRequested()
{
  return false;
}

<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "FakeCamera.h"
#include "TrackerThread.h"
#include "TrackerConfig.h"
#include "FilterDistortion.h"
#include "../graphics/Filtergrayscale.h"
#include "../graphics/FilterId.h"

#include "../base/TestSuite.h"
#include "../base/Exception.h"

#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#include <sstream>

//#define GENERATE_BASELINE

using namespace avg;
using namespace std;

class DistortionTest: public Test {
    public:
        DistortionTest():Test("DistortionTest",2){}
        void runTests(){
            cerr << "    Identical Transformer" << endl;
            CoordTransformer Transformer(IntRect(0,0,100,100), 0, 0, 1);
            TEST(Transformer.transform_point(DPoint(0,0)) == DPoint(0,0));
            TEST(Transformer.transform_point(DPoint(100,100)) == DPoint(100,100));

            cerr << "    Trapezoid Transformer 1" << endl;
            CoordTransformer TrapT(IntRect(0,0,100,100), 0, 1, 1);
            DPoint TestPt(100,0);
            testNullTransform(TrapT, TestPt);
            TestPt = DPoint(0,0);
            testNullTransform(TrapT, TestPt);
            TestPt = DPoint(100,100);
            testNullTransform(TrapT, TestPt);
            TestPt = DPoint(100,50);
            testNullTransform(TrapT, TestPt);

            cerr << "    Trapezoid Transformer 2" << endl;
            CoordTransformer TrapT1(IntRect(0,0,100,100), 0, 0.1, 1);
            TestPt = DPoint(100,10);
            testNullTransform(TrapT1, TestPt);

            cerr << "    Barrel Transformer" << endl;
            CoordTransformer BarrelT(IntRect(0,0,100,100), 0.1, 0, 1);
            TestPt = DPoint(100,0);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(0,0);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(50,0);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(0,50);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(23,42);
            testNullTransform(BarrelT, TestPt);

            cerr << "    Combined Transformer" << endl;
            CoordTransformer CombinedT(IntRect(0,0,100,100), 0.1, 0.1, 1);
            TestPt = DPoint(100,0);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(0,100);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(0,50);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(23,42);
            testNullTransform(BarrelT, TestPt);
/*
            cerr << TrapezoidT.transform_point(DPoint(100,0)) << endl;
            cerr << TrapezoidT.transform_point(DPoint(100,50)) << endl;
            cerr << TrapezoidT.transform_point(DPoint(100,100)) << endl;
            TEST(TrapezoidT.transform_point(DPoint(100,0)) == DPoint(50,0));
            TEST(TrapezoidT.transform_point(DPoint(100,100)) == DPoint(150,100));
*/

            BitmapPtr in_bmp = FilterGrayscale().apply(BitmapPtr(new Bitmap("testimages/squares.png")));
            FilterDistortion BarrelFilter = FilterDistortion(in_bmp->getSize(),0.3,0);
            BitmapPtr pBarrelBmp = BarrelFilter.apply(in_bmp);
            FilterDistortion TrapezoidFilter = FilterDistortion(in_bmp->getSize(),0,0.3);
            BitmapPtr pTrapezoidBmp = TrapezoidFilter.apply(in_bmp);
            FilterDistortion CombinedFilter = FilterDistortion(in_bmp->getSize(),0.08,0.08);
            BitmapPtr pCombinedBmp = CombinedFilter.apply(in_bmp);
#ifdef GENERATE_BASELINE
            cerr << "    ---- WARNING: Generating new testimages images, not executing tests."
                    << endl;
            pBarrelBmp->save("testimages/barrel.png");
            pTrapezoidBmp->save("testimages/trapezoid.png");
            pCombinedBmp->save("testimages/combined.png");
#else
            BitmapPtr pBarrelBaselineBmp = FilterGrayscale().apply(BitmapPtr(
                    new Bitmap("testimages/barrel.png")));
            TEST(*pBarrelBmp == *pBarrelBaselineBmp);
            BitmapPtr pTrapezoidBaselineBmp = FilterGrayscale().apply(BitmapPtr(
                    new Bitmap("testimages/trapezoid.png")));
            TEST(*pTrapezoidBmp == *pTrapezoidBaselineBmp);
            BitmapPtr pCombinedBaselineBmp = FilterGrayscale().apply(BitmapPtr(
                    new Bitmap("testimages/combined.png")));
            TEST(*pCombinedBmp == *pCombinedBaselineBmp);
#endif
        }

        void testNullTransform(CoordTransformer& T, DPoint& Pt)
        {
            DPoint TempPt = T.transform_point(Pt);
            DPoint SamePt = T.inverse_transform_point(TempPt);
            cerr << "      Pt: " << Pt << ", transformed: " << TempPt << ", back: "
                    << SamePt << endl;
            TEST(SamePt.x - Pt.x < 1 && SamePt.y - Pt.y < 1);
        }
};

class TrackingTest: public Test, public IBlobTarget {
public:
    TrackingTest()
        : Test("TrackingTest", 2)
    {
    }

    void runTests()
    {
        std::vector<std::string> p = std::vector<std::string>();
        for (int i=0; i<6; ++i) {
            stringstream s;
            s << "../imaging/testimages/Blob" << i << ".png";
            p.push_back(s.str());
        }
        CameraPtr pCam = CameraPtr(new FakeCamera(p));
        BitmapPtr pBitmaps[NUM_TRACKER_IMAGES];
        for (int i=0; i<NUM_TRACKER_IMAGES; i++) {
            pBitmaps[i] = BitmapPtr(new Bitmap(pCam->getImgSize(), I8));
        }
        MutexPtr pMutex(new boost::mutex);
        //FilterIdPtr pp = FilterIdPtr(new FilterId());
        m_pCmdQ = TrackerThread::CmdQueuePtr(new TrackerThread::CmdQueue);
        boost::thread Thread(
                TrackerThread(pCam, pBitmaps, pMutex,  *m_pCmdQ, this, true));
        Thread.join();
    }

    virtual void update(BlobListPtr pBlobs, bool) {
        static int BmpIndex = 0;
        switch(BmpIndex) {
            case 0:
                TEST(pBlobs->size() == 0);
                break;
            case 1:
                {
/*
                    TEST(pBlobs->size() == 1);
                    BlobInfoPtr pBlobInfo = (*pBlobs->begin())->getInfo();
                    cerr << pBlobInfo->m_Area << endl;
                    TEST(fabs(pBlobInfo->m_Area-32)<0.001);
                    TEST(fabs(pBlobInfo->m_Orientation)<0.001);
                    TEST(fabs(pBlobInfo->m_Center.x-11.5)<0.0001);
                    TEST(fabs(pBlobInfo->m_Center.y-7.5)<0.0001);
                    cerr << pBlobInfo->m_BoundingBox << endl;
                    TEST(pBlobInfo->m_BoundingBox == IntRect(9,5,15,11));
*/
                }
                break;
            case 2:
//                TEST(pBlobs->size() == 2);
                break;
            case 3:
                break;
            case 4:
/*
                {
                    cerr << pBlobs->size() << endl;
                    TEST(pBlobs->size() == 1);
                    BlobInfoPtr pBlobInfo = (*pBlobs->begin())->getInfo();
                    TEST(fabs(pBlobInfo->m_Area-114)<0.001);
                    TEST(pBlobInfo->m_BoundingBox == IntRect(4,15,31,21));
                }
*/
                break;
            case 5:
                TEST(pBlobs->size() == 0);
                m_pCmdQ->push(Command<TrackerThread>(boost::bind(&TrackerThread::stop, _1)));
                break;
            default:
                break;
        }
        BmpIndex++;
    }

private:
    TrackerThread::CmdQueuePtr m_pCmdQ;
};

class ImagingTestSuite: public TestSuite {
public:
    ImagingTestSuite()
        : TestSuite("ImagingTestSuite")
    {
        addTest(TestPtr(new TrackingTest));
        addTest(TestPtr(new DistortionTest));
    }
};

int main(int nargs, char** args)
{
    ImagingTestSuite Suite;
    Suite.runTests();
    bool bOK = Suite.isOk();

    if (bOK) {
        return 0;
    } else {
        return 1;
    }
}

<commit_msg>Removed console spam<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "FakeCamera.h"
#include "TrackerThread.h"
#include "TrackerConfig.h"
#include "FilterDistortion.h"
#include "../graphics/Filtergrayscale.h"
#include "../graphics/FilterId.h"

#include "../base/TestSuite.h"
#include "../base/Exception.h"

#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#include <sstream>

//#define GENERATE_BASELINE

using namespace avg;
using namespace std;

class DistortionTest: public Test {
    public:
        DistortionTest():Test("DistortionTest",2){}
        void runTests(){
            cerr << "    Identical Transformer" << endl;
            CoordTransformer Transformer(IntRect(0,0,100,100), 0, 0, 1);
            TEST(Transformer.transform_point(DPoint(0,0)) == DPoint(0,0));
            TEST(Transformer.transform_point(DPoint(100,100)) == DPoint(100,100));

            cerr << "    Trapezoid Transformer 1" << endl;
            CoordTransformer TrapT(IntRect(0,0,100,100), 0, 1, 1);
            DPoint TestPt(100,0);
            testNullTransform(TrapT, TestPt);
            TestPt = DPoint(0,0);
            testNullTransform(TrapT, TestPt);
            TestPt = DPoint(100,100);
            testNullTransform(TrapT, TestPt);
            TestPt = DPoint(100,50);
            testNullTransform(TrapT, TestPt);

            cerr << "    Trapezoid Transformer 2" << endl;
            CoordTransformer TrapT1(IntRect(0,0,100,100), 0, 0.1, 1);
            TestPt = DPoint(100,10);
            testNullTransform(TrapT1, TestPt);

            cerr << "    Barrel Transformer" << endl;
            CoordTransformer BarrelT(IntRect(0,0,100,100), 0.1, 0, 1);
            TestPt = DPoint(100,0);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(0,0);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(50,0);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(0,50);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(23,42);
            testNullTransform(BarrelT, TestPt);

            cerr << "    Combined Transformer" << endl;
            CoordTransformer CombinedT(IntRect(0,0,100,100), 0.1, 0.1, 1);
            TestPt = DPoint(100,0);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(0,100);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(0,50);
            testNullTransform(BarrelT, TestPt);
            TestPt = DPoint(23,42);
            testNullTransform(BarrelT, TestPt);
/*
            cerr << TrapezoidT.transform_point(DPoint(100,0)) << endl;
            cerr << TrapezoidT.transform_point(DPoint(100,50)) << endl;
            cerr << TrapezoidT.transform_point(DPoint(100,100)) << endl;
            TEST(TrapezoidT.transform_point(DPoint(100,0)) == DPoint(50,0));
            TEST(TrapezoidT.transform_point(DPoint(100,100)) == DPoint(150,100));
*/

            BitmapPtr in_bmp = FilterGrayscale().apply(BitmapPtr(new Bitmap("testimages/squares.png")));
            FilterDistortion BarrelFilter = FilterDistortion(in_bmp->getSize(),0.3,0);
            BitmapPtr pBarrelBmp = BarrelFilter.apply(in_bmp);
            FilterDistortion TrapezoidFilter = FilterDistortion(in_bmp->getSize(),0,0.3);
            BitmapPtr pTrapezoidBmp = TrapezoidFilter.apply(in_bmp);
            FilterDistortion CombinedFilter = FilterDistortion(in_bmp->getSize(),0.08,0.08);
            BitmapPtr pCombinedBmp = CombinedFilter.apply(in_bmp);
#ifdef GENERATE_BASELINE
            cerr << "    ---- WARNING: Generating new testimages images, not executing tests."
                    << endl;
            pBarrelBmp->save("testimages/barrel.png");
            pTrapezoidBmp->save("testimages/trapezoid.png");
            pCombinedBmp->save("testimages/combined.png");
#else
            BitmapPtr pBarrelBaselineBmp = FilterGrayscale().apply(BitmapPtr(
                    new Bitmap("testimages/barrel.png")));
            TEST(*pBarrelBmp == *pBarrelBaselineBmp);
            BitmapPtr pTrapezoidBaselineBmp = FilterGrayscale().apply(BitmapPtr(
                    new Bitmap("testimages/trapezoid.png")));
            TEST(*pTrapezoidBmp == *pTrapezoidBaselineBmp);
            BitmapPtr pCombinedBaselineBmp = FilterGrayscale().apply(BitmapPtr(
                    new Bitmap("testimages/combined.png")));
            TEST(*pCombinedBmp == *pCombinedBaselineBmp);
#endif
        }

        void testNullTransform(CoordTransformer& T, DPoint& Pt)
        {
            DPoint TempPt = T.transform_point(Pt);
            DPoint SamePt = T.inverse_transform_point(TempPt);
            TEST(SamePt.x - Pt.x < 1 && SamePt.y - Pt.y < 1);
        }
};

class TrackingTest: public Test, public IBlobTarget {
public:
    TrackingTest()
        : Test("TrackingTest", 2)
    {
    }

    void runTests()
    {
        std::vector<std::string> p = std::vector<std::string>();
        for (int i=0; i<6; ++i) {
            stringstream s;
            s << "../imaging/testimages/Blob" << i << ".png";
            p.push_back(s.str());
        }
        CameraPtr pCam = CameraPtr(new FakeCamera(p));
        BitmapPtr pBitmaps[NUM_TRACKER_IMAGES];
        for (int i=0; i<NUM_TRACKER_IMAGES; i++) {
            pBitmaps[i] = BitmapPtr(new Bitmap(pCam->getImgSize(), I8));
        }
        MutexPtr pMutex(new boost::mutex);
        //FilterIdPtr pp = FilterIdPtr(new FilterId());
        m_pCmdQ = TrackerThread::CmdQueuePtr(new TrackerThread::CmdQueue);
        boost::thread Thread(
                TrackerThread(pCam, pBitmaps, pMutex,  *m_pCmdQ, this, true));
        Thread.join();
    }

    virtual void update(BlobListPtr pBlobs, bool) {
        static int BmpIndex = 0;
        switch(BmpIndex) {
            case 0:
                TEST(pBlobs->size() == 0);
                break;
            case 1:
                {
/*
                    TEST(pBlobs->size() == 1);
                    BlobInfoPtr pBlobInfo = (*pBlobs->begin())->getInfo();
                    cerr << pBlobInfo->m_Area << endl;
                    TEST(fabs(pBlobInfo->m_Area-32)<0.001);
                    TEST(fabs(pBlobInfo->m_Orientation)<0.001);
                    TEST(fabs(pBlobInfo->m_Center.x-11.5)<0.0001);
                    TEST(fabs(pBlobInfo->m_Center.y-7.5)<0.0001);
                    cerr << pBlobInfo->m_BoundingBox << endl;
                    TEST(pBlobInfo->m_BoundingBox == IntRect(9,5,15,11));
*/
                }
                break;
            case 2:
//                TEST(pBlobs->size() == 2);
                break;
            case 3:
                break;
            case 4:
/*
                {
                    cerr << pBlobs->size() << endl;
                    TEST(pBlobs->size() == 1);
                    BlobInfoPtr pBlobInfo = (*pBlobs->begin())->getInfo();
                    TEST(fabs(pBlobInfo->m_Area-114)<0.001);
                    TEST(pBlobInfo->m_BoundingBox == IntRect(4,15,31,21));
                }
*/
                break;
            case 5:
                TEST(pBlobs->size() == 0);
                m_pCmdQ->push(Command<TrackerThread>(boost::bind(&TrackerThread::stop, _1)));
                break;
            default:
                break;
        }
        BmpIndex++;
    }

private:
    TrackerThread::CmdQueuePtr m_pCmdQ;
};

class ImagingTestSuite: public TestSuite {
public:
    ImagingTestSuite()
        : TestSuite("ImagingTestSuite")
    {
        addTest(TestPtr(new TrackingTest));
        addTest(TestPtr(new DistortionTest));
    }
};

int main(int nargs, char** args)
{
    ImagingTestSuite Suite;
    Suite.runTests();
    bool bOK = Suite.isOk();

    if (bOK) {
        return 0;
    } else {
        return 1;
    }
}

<|endoftext|>


<commit_before>/* +---------------------------------------------------------------------------+
   |                     Mobile Robot Programming Toolkit (MRPT)               |
   |                          http://www.mrpt.org/                             |
   |                                                                           |
   | Copyright (c) 2005-2016, Individual contributors, see AUTHORS file        |
   | See: http://www.mrpt.org/Authors - All rights reserved.                   |
   | Released under BSD License. See details in http://www.mrpt.org/License    |
   +---------------------------------------------------------------------------+ */

#include "opengl-precomp.h"  // Precompiled header

#define MRPT_NO_WARN_BIG_HDR
#include <mrpt/opengl.h>
#include <mrpt/utils/initializer.h>

using namespace mrpt::opengl;
using namespace mrpt::utils;

void registerAllClasses_mrpt_opengl();

MRPT_INITIALIZER(registerAllClasses_mrpt_opengl)
{
#if !defined(DISABLE_MRPT_AUTO_CLASS_REGISTRATION)
	// Opengl classes:
	registerClass( CLASS_ID( CRenderizable ) );
	registerClass( CLASS_ID( C3DSScene ) );
	registerClass( CLASS_ID( CAssimpModel ) );
	registerClass( CLASS_ID( CAxis ) );
	registerClass( CLASS_ID( CBox ) );
	registerClass( CLASS_ID( CFrustum ) );
	registerClass( CLASS_ID( CDisk ) );
	registerClass( CLASS_ID( CGridPlaneXY ) );
	registerClass( CLASS_ID( CMesh ) );
	registerClass( CLASS_ID( CMesh3D ) );
	registerClass( CLASS_ID( CMeshFast ) );
	registerClass( CLASS_ID( COpenGLViewport ) );
	registerClass( CLASS_ID( CPointCloud ) );
	registerClass( CLASS_ID( CPointCloudColoured ) );
	registerClass( CLASS_ID( CSetOfLines ) );
	registerClass( CLASS_ID( CSetOfTriangles ) );
	registerClass( CLASS_ID( CSphere ) );
	registerClass( CLASS_ID( CCylinder ) );
	registerClass( CLASS_ID( CGeneralizedCylinder ) );
	registerClass( CLASS_ID( CPolyhedron ) );
	registerClass( CLASS_ID( CTexturedPlane ) );
	registerClass( CLASS_ID( CArrow ) );
	registerClass( CLASS_ID( CCamera ) );
	registerClass( CLASS_ID( CEllipsoid  ) );
	registerClass( CLASS_ID( CGridPlaneXZ ) );
	registerClass( CLASS_ID( COpenGLScene ) );
	registerClass( CLASS_ID( CSetOfObjects ) );
	registerClass( CLASS_ID( CSimpleLine ) );
	registerClass( CLASS_ID( CText ) );
	registerClass( CLASS_ID( CText3D ) );
	registerClass( CLASS_ID( CEllipsoidInverseDepth2D ) );
	registerClass( CLASS_ID( CEllipsoidInverseDepth3D ) );
	registerClass( CLASS_ID( CEllipsoidRangeBearing2D ) );
	registerClass( CLASS_ID( COctoMapVoxels ) );
	registerClass( CLASS_ID( CVectorField2D ) );
	registerClass( CLASS_ID( CVectorField3D ) );

	// These ones are in the lib: mrpt-obsmaps
	//registerClass( CLASS_ID( CPlanarLaserScan ) );
	//registerClass( CLASS_ID( CAngularObservationMesh ) );
#endif
}

<commit_msg>Remove decl func<commit_after>/* +---------------------------------------------------------------------------+
   |                     Mobile Robot Programming Toolkit (MRPT)               |
   |                          http://www.mrpt.org/                             |
   |                                                                           |
   | Copyright (c) 2005-2016, Individual contributors, see AUTHORS file        |
   | See: http://www.mrpt.org/Authors - All rights reserved.                   |
   | Released under BSD License. See details in http://www.mrpt.org/License    |
   +---------------------------------------------------------------------------+ */

#include "opengl-precomp.h"  // Precompiled header

#define MRPT_NO_WARN_BIG_HDR
#include <mrpt/opengl.h>
#include <mrpt/utils/initializer.h>

using namespace mrpt::opengl;
using namespace mrpt::utils;

MRPT_INITIALIZER(registerAllClasses_mrpt_opengl)
{
#if !defined(DISABLE_MRPT_AUTO_CLASS_REGISTRATION)
	// Opengl classes:
	registerClass( CLASS_ID( CRenderizable ) );
	registerClass( CLASS_ID( C3DSScene ) );
	registerClass( CLASS_ID( CAssimpModel ) );
	registerClass( CLASS_ID( CAxis ) );
	registerClass( CLASS_ID( CBox ) );
	registerClass( CLASS_ID( CFrustum ) );
	registerClass( CLASS_ID( CDisk ) );
	registerClass( CLASS_ID( CGridPlaneXY ) );
	registerClass( CLASS_ID( CMesh ) );
	registerClass( CLASS_ID( CMesh3D ) );
	registerClass( CLASS_ID( CMeshFast ) );
	registerClass( CLASS_ID( COpenGLViewport ) );
	registerClass( CLASS_ID( CPointCloud ) );
	registerClass( CLASS_ID( CPointCloudColoured ) );
	registerClass( CLASS_ID( CSetOfLines ) );
	registerClass( CLASS_ID( CSetOfTriangles ) );
	registerClass( CLASS_ID( CSphere ) );
	registerClass( CLASS_ID( CCylinder ) );
	registerClass( CLASS_ID( CGeneralizedCylinder ) );
	registerClass( CLASS_ID( CPolyhedron ) );
	registerClass( CLASS_ID( CTexturedPlane ) );
	registerClass( CLASS_ID( CArrow ) );
	registerClass( CLASS_ID( CCamera ) );
	registerClass( CLASS_ID( CEllipsoid  ) );
	registerClass( CLASS_ID( CGridPlaneXZ ) );
	registerClass( CLASS_ID( COpenGLScene ) );
	registerClass( CLASS_ID( CSetOfObjects ) );
	registerClass( CLASS_ID( CSimpleLine ) );
	registerClass( CLASS_ID( CText ) );
	registerClass( CLASS_ID( CText3D ) );
	registerClass( CLASS_ID( CEllipsoidInverseDepth2D ) );
	registerClass( CLASS_ID( CEllipsoidInverseDepth3D ) );
	registerClass( CLASS_ID( CEllipsoidRangeBearing2D ) );
	registerClass( CLASS_ID( COctoMapVoxels ) );
	registerClass( CLASS_ID( CVectorField2D ) );
	registerClass( CLASS_ID( CVectorField3D ) );

	// These ones are in the lib: mrpt-obsmaps
	//registerClass( CLASS_ID( CPlanarLaserScan ) );
	//registerClass( CLASS_ID( CAngularObservationMesh ) );
#endif
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Florian Behrens
 *
 * 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.
 */

#include "client_context.h"

#include "client_write_interface.h"
#include "connection.h"
#include "event.h"
#include "exceptions.h"
#include "object.h"
#include "object_dictionary.h"

namespace decof
{

client_context::client_context(object_dictionary& a_object_dictionary, std::shared_ptr<connection> connection, userlevel_t userlevel)
  : object_dictionary_(a_object_dictionary),
    connection_(connection),
    userlevel_(userlevel)
{}

client_context::~client_context()
{}

userlevel_t client_context::userlevel() const
{
    return userlevel_;
}

void client_context::userlevel(userlevel_t ul)
{
    userlevel_ = ul;
}

std::string client_context::connection_type() const
{
    return std::string("undefined");
}

std::string client_context::remote_endpoint() const
{
    return std::string("undefined");
}

void client_context::preload()
{}

void client_context::set_parameter(const std::string &uri, const boost::any &any_value, char separator)
{
    object_dictionary::context_guard cg(object_dictionary_, this);

    object *te = object_dictionary_.find_object(uri, separator);
    client_write_interface* param = dynamic_cast<client_write_interface*>(te);

    if (param == nullptr)
        throw invalid_parameter_error();
    if (userlevel_ < te->writelevel())
        throw access_denied_error();

    param->value(any_value);
}

boost::any client_context::get_parameter(const std::string &uri, char separator)
{
    boost::any retval;
    object_dictionary::context_guard cg(object_dictionary_, this);

    object *obj = object_dictionary_.find_object(uri, separator);
    client_read_interface* param = dynamic_cast<client_read_interface*>(obj);

    if (param == nullptr)
        throw invalid_parameter_error();
    if (userlevel_ < obj->readlevel())
        throw access_denied_error();

    return param->any_value();
}

void client_context::signal_event(const std::string &uri, char separator)
{
    object_dictionary::context_guard cg(object_dictionary_, this);

    object *te = object_dictionary_.find_object(uri, separator);
    event* ev = dynamic_cast<event*>(te);

    if (ev == nullptr)
        throw invalid_parameter_error();
    if (userlevel_ < te->writelevel())
        throw access_denied_error();

    ev->signal();
}

void client_context::observe(const std::string &uri, client_read_interface::signal_type::slot_type slot, char separator)
{
    object_dictionary::context_guard cg(object_dictionary_, this);

    auto obj = object_dictionary_.find_object(uri, separator);

    if (userlevel_ < obj->readlevel())
        throw access_denied_error();
    if (client_read_interface* param = dynamic_cast<client_read_interface*>(obj)) {
        if (observables_.count(uri) == 0) {
            boost::signals2::connection connection = param->observe(slot);
            observables_.emplace(uri, connection);
        }
    } else
        throw invalid_parameter_error();
}

void client_context::unobserve(const std::string &uri)
{
    try {
        observables_.at(uri).disconnect();
        observables_.erase(uri);
    } catch (std::out_of_range&) {
    }
}

void client_context::browse(object_visitor *visitor, const std::string &root_uri)
{
    object_dictionary::context_guard cg(object_dictionary_, this);

    std::string uri = root_uri;
    if (uri.empty())
        uri = object_dictionary_.name();

    if (object *te = object_dictionary_.find_object(uri)) {
        // Recursively iterate over all objects beginning from root URI
        browse_object(te, visitor);
    } else
        throw invalid_parameter_error();
}

void client_context::tick()
{
    object_dictionary_.tick();
}

void client_context::browse_object(object *te, object_visitor *visitor)
{
    te->accept(visitor);

    // If node browse children
    if (node *n = dynamic_cast<node*>(te)) {
        for (auto &child : *n)
            browse_object(child, visitor);
    }
}

} // namespace decof
<commit_msg>Fixed crash on unknown parameter subscription bug.<commit_after>/*
 * Copyright (c) 2014 Florian Behrens
 *
 * 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.
 */

#include "client_context.h"

#include "client_write_interface.h"
#include "connection.h"
#include "event.h"
#include "exceptions.h"
#include "object.h"
#include "object_dictionary.h"

namespace decof
{

client_context::client_context(object_dictionary& a_object_dictionary, std::shared_ptr<connection> connection, userlevel_t userlevel)
  : object_dictionary_(a_object_dictionary),
    connection_(connection),
    userlevel_(userlevel)
{}

client_context::~client_context()
{}

userlevel_t client_context::userlevel() const
{
    return userlevel_;
}

void client_context::userlevel(userlevel_t ul)
{
    userlevel_ = ul;
}

std::string client_context::connection_type() const
{
    return std::string("undefined");
}

std::string client_context::remote_endpoint() const
{
    return std::string("undefined");
}

void client_context::preload()
{}

void client_context::set_parameter(const std::string &uri, const boost::any &any_value, char separator)
{
    object_dictionary::context_guard cg(object_dictionary_, this);

    object *te = object_dictionary_.find_object(uri, separator);
    client_write_interface* param = dynamic_cast<client_write_interface*>(te);

    if (param == nullptr)
        throw invalid_parameter_error();
    if (userlevel_ < te->writelevel())
        throw access_denied_error();

    param->value(any_value);
}

boost::any client_context::get_parameter(const std::string &uri, char separator)
{
    boost::any retval;
    object_dictionary::context_guard cg(object_dictionary_, this);

    object *obj = object_dictionary_.find_object(uri, separator);
    client_read_interface* param = dynamic_cast<client_read_interface*>(obj);

    if (param == nullptr)
        throw invalid_parameter_error();
    if (userlevel_ < obj->readlevel())
        throw access_denied_error();

    return param->any_value();
}

void client_context::signal_event(const std::string &uri, char separator)
{
    object_dictionary::context_guard cg(object_dictionary_, this);

    object *te = object_dictionary_.find_object(uri, separator);
    event* ev = dynamic_cast<event*>(te);

    if (ev == nullptr)
        throw invalid_parameter_error();
    if (userlevel_ < te->writelevel())
        throw access_denied_error();

    ev->signal();
}

void client_context::observe(const std::string &uri, client_read_interface::signal_type::slot_type slot, char separator)
{
    object_dictionary::context_guard cg(object_dictionary_, this);

    auto obj = object_dictionary_.find_object(uri, separator);

    if (client_read_interface* param = dynamic_cast<client_read_interface*>(obj)) {
        if (userlevel_ < obj->readlevel())
            throw access_denied_error();

        if (observables_.count(uri) == 0) {
            boost::signals2::connection connection = param->observe(slot);
            observables_.emplace(uri, connection);
        }
    } else
        throw invalid_parameter_error();
}

void client_context::unobserve(const std::string &uri)
{
    try {
        observables_.at(uri).disconnect();
        observables_.erase(uri);
    } catch (std::out_of_range&) {
    }
}

void client_context::browse(object_visitor *visitor, const std::string &root_uri)
{
    object_dictionary::context_guard cg(object_dictionary_, this);

    std::string uri = root_uri;
    if (uri.empty())
        uri = object_dictionary_.name();

    if (object *te = object_dictionary_.find_object(uri)) {
        // Recursively iterate over all objects beginning from root URI
        browse_object(te, visitor);
    } else
        throw invalid_parameter_error();
}

void client_context::tick()
{
    object_dictionary_.tick();
}

void client_context::browse_object(object *te, object_visitor *visitor)
{
    te->accept(visitor);

    // If node browse children
    if (node *n = dynamic_cast<node*>(te)) {
        for (auto &child : *n)
            browse_object(child, visitor);
    }
}

} // namespace decof
<|endoftext|>


<commit_before>#include <CL/cl.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <fstream>

using namespace std;

#define NWITEMS 6

#pragma comment (lib,"OpenCL.lib")

//把文本文件读入一个 string 中
int convertToString(const char *filename, std::string& s)
{
	size_t size;
	char* str;
	std::fstream f(filename, (std::fstream::in | std::fstream::binary));
	if (f.is_open())
	{
		size_t fileSize;
		f.seekg(0, std::fstream::end);
		size = fileSize = (size_t)f.tellg();
		f.seekg(0, std::fstream::beg);
		str = new char[size + 1];
		if (!str)
		{
			f.close();
			return NULL;
		}
		f.read(str, fileSize);
		f.close();
		str[size] = '\0';
		s = str;
		delete[] str;
		return 0;
	}
	printf("Error: Failed to open file %s\n", filename);
	return 1;
}

int main()
{
	cl_uint status;
	cl_platform_id platform;

	//创建平台对象
	status = clGetPlatformIDs(1, &platform, NULL);
	cl_device_id device;
	//创建 GPU 设备
	clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU,
		1,
		&device,
		NULL);
	//创建context
	cl_context context = clCreateContext(NULL,
		1,
		&device,
		NULL, NULL, NULL);
	//创建命令队列
	cl_command_queue commandQueue = clCreateCommandQueue(context,
		device,
		CL_QUEUE_PROFILING_ENABLE, NULL);

	if (commandQueue == NULL)
		perror("Failed to create commandQueue for device 0.");

	//建立要传入从机的数据
	/********  创建内核和内存对象 ********/

	const int Ndim = 4;
	const int Mdim = 5;
	const int Pdim = 2;
	int szA = Ndim * Pdim;
	int szB = Pdim * Mdim;
	int szC = Ndim * Mdim;

	float *A;
	float *B;
	float *C;

	A = (float *)malloc(szA * sizeof(float));
	B = (float *)malloc(szB * sizeof(float));
	C = (float *)malloc(szC * sizeof(float));
	int i, j;
	for (i = 0; i < szA; i++)
		A[i] = (float)((float)i + 1.0);
	for (i = 0; i < szB; i++)
		B[i] = (float)((float)i + 1.0);

	//创建三个 OpenCL 内存对象，并把buf1 的内容通过隐式拷贝的方式
	//拷贝到clbuf1, buf2 的内容通过显示拷贝的方式拷贝到clbuf2
	cl_mem memObjects[3] = { 0, 0, 0 };
	memObjects[0] = clCreateBuffer(context, CL_MEM_READ_ONLY |  CL_MEM_COPY_HOST_PTR,
		sizeof(float)* szA, A, NULL);
	memObjects[1] = clCreateBuffer(context, CL_MEM_READ_ONLY |  CL_MEM_COPY_HOST_PTR,
		sizeof(float)* szB, B, NULL);
	memObjects[2] = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
		sizeof(float)* szC, C, NULL);
	if (memObjects[0] == NULL || memObjects[1] == NULL ||memObjects[2] == NULL)
		perror("Error in clCreateBuffer.\n");

	const char * filename = "matrix_mult.cl";
	std::string sourceStr;
	status = convertToString(filename, sourceStr);
	if (status)
		cout << status << "  !!!!!!!!" << endl;
	const char * source = sourceStr.c_str();
	size_t sourceSize[] = { strlen(source) };
	//创建程序对象
	cl_program program = clCreateProgramWithSource(
		context,
		1,
		&source,
		sourceSize,
		NULL);
	//编译程序对象
	status = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
	if (status)
		cout << status << "  !!!!!!!!" <<endl;
	if (status != 0)
	{
		printf("clBuild failed:%d\n", status);
		char tbuf[0x10000];
		clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0x10000, tbuf,
			NULL);
		printf("\n%s\n", tbuf);
		//return −1;
	}

	//创建 Kernel 对象
	cl_kernel kernel = clCreateKernel(program, "matrix_mult", NULL);

	//设置 Kernel 参数
	cl_int clnum = NWITEMS;
	status = clSetKernelArg(kernel, 0, sizeof(int), &Ndim);
	status = clSetKernelArg(kernel, 1, sizeof(int), &Mdim);
	status = clSetKernelArg(kernel, 2, sizeof(int), &Pdim);
	status = clSetKernelArg(kernel, 3, sizeof(cl_mem), &memObjects[0]);
	status = clSetKernelArg(kernel, 4, sizeof(cl_mem), &memObjects[1]);
	status = clSetKernelArg(kernel, 5, sizeof(cl_mem), &memObjects[2]);
	if (status)
		cout << "参数设置错误" << endl;

	//执行 kernel
	size_t global[2];
	cl_event prof_event;
	cl_ulong ev_start_time = (cl_ulong)0;
	cl_ulong ev_end_time = (cl_ulong)0;
	double rum_time;
	global[0] = (size_t)Ndim;
	global[1] = (size_t)Mdim;
	status = clEnqueueNDRangeKernel(commandQueue, kernel, 2, NULL,
		global, NULL, 0, NULL, &prof_event);
	if (status)
		cout << "执行内核时错误" << endl;
	clFinish(commandQueue);

	//读取时间
	status = clGetEventProfilingInfo(prof_event,CL_PROFILING_COMMAND_QUEUED,
		sizeof(cl_ulong),&ev_start_time,NULL);
	status = clGetEventProfilingInfo(prof_event,CL_PROFILING_COMMAND_END,
		sizeof(cl_ulong),&ev_end_time,NULL);
	if (status)
		perror("读取时间的时候发生错误\n");
	rum_time = (double)(ev_end_time - ev_start_time);
	cout << "执行时间为:" << rum_time << endl;

	//数据拷回 host 内存
	status = clEnqueueReadBuffer(commandQueue, memObjects[2],CL_TRUE, 0,
		sizeof(float)* szC, C,0, NULL, NULL);
	if (status)
		perror("读回数据的时候发生错误\n");

	//结果显示
	printf("\nArray A:\n");
	for (i = 0; i < Ndim; i++) {
		for (j = 0; j < Pdim; j++)
			printf("%.3f\t", A[i*Pdim + j]);
		printf("\n");
	}
	printf("\nArray B:\n");
	for (i = 0; i < Pdim; i++) {
		for (j = 0; j < Mdim; j++)
			printf("%.3f\t", B[i*Mdim + j]);
		printf("\n");
	}
	printf("\nArray C:\n");
	for (i = 0; i < Ndim; i++) {
		for (j = 0; j < Mdim; j++)
			printf("%.3f\t", C[i*Mdim + j]);
		printf("\n");
	}

	cout << endl;

	if (A)
		free(A);
	if (B)
		free(B);
	if (C)
		free(C);

	//删除 OpenCL 资源对象
	clReleaseMemObject(memObjects[2]);
	clReleaseMemObject(memObjects[1]);
	clReleaseMemObject(memObjects[0]);
	clReleaseProgram(program);
	clReleaseCommandQueue(commandQueue);
	clReleaseContext(context);
	system("pause");

	return 0;
}<commit_msg>[add C sequential implement<commit_after>#if(1)
//matrix multiply sequential implement
#include <iostream>
#include <stdio.h>

using namespace std;

//C sequential implement
void mat_fuc(int Ndim,int Mdim,int Pdim,float* A,float* B,float* C)
{
	int i,j,k;
	float temp;

	for(i = 0; i < Ndim; ++i){
		for(j = 0; j < Mdim; ++j){
			temp = 0.0;
			for(k = 0; k < Pdim; ++k){
				temp = temp + A[i * Pdim + k] * B[k * Mdim + j];
				C[i * Mdim + j] = temp;
			}
		}
	}
}

int main()
{
	const int Ndim = 2;
	const int Pdim = 3;
	const int Mdim = 4;
	int szA = Ndim * Pdim;
	int szB = Pdim * Mdim;
	int szC = Ndim * Mdim;

	float* A;
	float* B;
	float* C;

	A = (float *)malloc(szA * sizeof(float));
	B = (float *)malloc(szB * sizeof(float));
	C = (float *)malloc(szC * sizeof(float));

	for (int i = 0; i < szA; ++i)
		A[i] = (float)((float)i + 1.0);
	for (int j = 0; j < szB; ++j)
		B[j] = (float)((float)j + 1.0);

	mat_fuc(Ndim,Mdim,Pdim,A,B,C);

	for(int i = 0; i < Ndim; ++i)
	{
		for(int j = 0; j< Pdim; ++j)
			printf("%.3f\t",A[i * Pdim + j]);
		printf("\n");
	}

	cout<<endl;

	for(int i = 0; i < Pdim; ++i)
	{
		for(int j = 0; j< Mdim; ++j)
			printf("%.3f\t",B[i * Mdim + j]);
		printf("\n");
	}

	cout<<endl;

	for(int i = 0; i < Ndim; ++i)
	{
		for(int j = 0; j< Mdim; ++j)
			printf("%.3f\t",C[i * Mdim + j]);
		printf("\n");
	}

	system("pause");
}

#endif

#if(0)

#include <CL/cl.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <fstream>

using namespace std;

#define NWITEMS 6

#pragma comment (lib,"OpenCL.lib")

//把文本文件读入一个 string 中
int convertToString(const char *filename, std::string& s)
{
	size_t size;
	char* str;
	std::fstream f(filename, (std::fstream::in | std::fstream::binary));
	if (f.is_open())
	{
		size_t fileSize;
		f.seekg(0, std::fstream::end);
		size = fileSize = (size_t)f.tellg();
		f.seekg(0, std::fstream::beg);
		str = new char[size + 1];
		if (!str)
		{
			f.close();
			return NULL;
		}
		f.read(str, fileSize);
		f.close();
		str[size] = '\0';
		s = str;
		delete[] str;
		return 0;
	}
	printf("Error: Failed to open file %s\n", filename);
	return 1;
}

int main()
{
	cl_uint status;
	cl_platform_id platform;

	//创建平台对象
	status = clGetPlatformIDs(1, &platform, NULL);
	cl_device_id device;
	//创建 GPU 设备
	clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU,
		1,
		&device,
		NULL);
	//创建context
	cl_context context = clCreateContext(NULL,
		1,
		&device,
		NULL, NULL, NULL);
	//创建命令队列
	cl_command_queue commandQueue = clCreateCommandQueue(context,
		device,
		CL_QUEUE_PROFILING_ENABLE, NULL);

	if (commandQueue == NULL)
		perror("Failed to create commandQueue for device 0.");

	//建立要传入从机的数据
	/********  创建内核和内存对象 ********/

	const int Ndim = 4;
	const int Mdim = 5;
	const int Pdim = 2;
	int szA = Ndim * Pdim;
	int szB = Pdim * Mdim;
	int szC = Ndim * Mdim;

	float *A;
	float *B;
	float *C;

	A = (float *)malloc(szA * sizeof(float));
	B = (float *)malloc(szB * sizeof(float));
	C = (float *)malloc(szC * sizeof(float));
	int i, j;
	for (i = 0; i < szA; i++)
		A[i] = (float)((float)i + 1.0);
	for (i = 0; i < szB; i++)
		B[i] = (float)((float)i + 1.0);

	//创建三个 OpenCL 内存对象，并把buf1 的内容通过隐式拷贝的方式
	//拷贝到clbuf1, buf2 的内容通过显示拷贝的方式拷贝到clbuf2
	cl_mem memObjects[3] = { 0, 0, 0 };
	memObjects[0] = clCreateBuffer(context, CL_MEM_READ_ONLY |  CL_MEM_COPY_HOST_PTR,
		sizeof(float)* szA, A, NULL);
	memObjects[1] = clCreateBuffer(context, CL_MEM_READ_ONLY |  CL_MEM_COPY_HOST_PTR,
		sizeof(float)* szB, B, NULL);
	memObjects[2] = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
		sizeof(float)* szC, C, NULL);
	if (memObjects[0] == NULL || memObjects[1] == NULL ||memObjects[2] == NULL)
		perror("Error in clCreateBuffer.\n");

	const char * filename = "matrix_mult.cl";
	std::string sourceStr;
	status = convertToString(filename, sourceStr);
	if (status)
		cout << status << "  !!!!!!!!" << endl;
	const char * source = sourceStr.c_str();
	size_t sourceSize[] = { strlen(source) };
	//创建程序对象
	cl_program program = clCreateProgramWithSource(
		context,
		1,
		&source,
		sourceSize,
		NULL);
	//编译程序对象
	status = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
	if (status)
		cout << status << "  !!!!!!!!" <<endl;
	if (status != 0)
	{
		printf("clBuild failed:%d\n", status);
		char tbuf[0x10000];
		clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0x10000, tbuf,
			NULL);
		printf("\n%s\n", tbuf);
		//return −1;
	}

	//创建 Kernel 对象
	cl_kernel kernel = clCreateKernel(program, "matrix_mult", NULL);

	//设置 Kernel 参数
	cl_int clnum = NWITEMS;
	status = clSetKernelArg(kernel, 0, sizeof(int), &Ndim);
	status = clSetKernelArg(kernel, 1, sizeof(int), &Mdim);
	status = clSetKernelArg(kernel, 2, sizeof(int), &Pdim);
	status = clSetKernelArg(kernel, 3, sizeof(cl_mem), &memObjects[0]);
	status = clSetKernelArg(kernel, 4, sizeof(cl_mem), &memObjects[1]);
	status = clSetKernelArg(kernel, 5, sizeof(cl_mem), &memObjects[2]);
	if (status)
		cout << "参数设置错误" << endl;

	//执行 kernel
	size_t global[2];
	cl_event prof_event;
	cl_ulong ev_start_time = (cl_ulong)0;
	cl_ulong ev_end_time = (cl_ulong)0;
	double rum_time;
	global[0] = (size_t)Ndim;
	global[1] = (size_t)Mdim;
	status = clEnqueueNDRangeKernel(commandQueue, kernel, 2, NULL,
		global, NULL, 0, NULL, &prof_event);
	if (status)
		cout << "执行内核时错误" << endl;
	clFinish(commandQueue);

	//读取时间
	status = clGetEventProfilingInfo(prof_event,CL_PROFILING_COMMAND_QUEUED,
		sizeof(cl_ulong),&ev_start_time,NULL);
	status = clGetEventProfilingInfo(prof_event,CL_PROFILING_COMMAND_END,
		sizeof(cl_ulong),&ev_end_time,NULL);
	if (status)
		perror("读取时间的时候发生错误\n");
	rum_time = (double)(ev_end_time - ev_start_time);
	cout << "执行时间为:" << rum_time << endl;

	//数据拷回 host 内存
	status = clEnqueueReadBuffer(commandQueue, memObjects[2],CL_TRUE, 0,
		sizeof(float)* szC, C,0, NULL, NULL);
	if (status)
		perror("读回数据的时候发生错误\n");

	//结果显示
	printf("\nArray A:\n");
	for (i = 0; i < Ndim; i++) {
		for (j = 0; j < Pdim; j++)
			printf("%.3f\t", A[i*Pdim + j]);
		printf("\n");
	}
	printf("\nArray B:\n");
	for (i = 0; i < Pdim; i++) {
		for (j = 0; j < Mdim; j++)
			printf("%.3f\t", B[i*Mdim + j]);
		printf("\n");
	}
	printf("\nArray C:\n");
	for (i = 0; i < Ndim; i++) {
		for (j = 0; j < Mdim; j++)
			printf("%.3f\t", C[i*Mdim + j]);
		printf("\n");
	}

	cout << endl;
	printf("C语言中数组按行读取数组元素 A[3] = %.3f\n",A[3]);

	if (A)
		free(A);
	if (B)
		free(B);
	if (C)
		free(C);

	//删除 OpenCL 资源对象
	clReleaseMemObject(memObjects[2]);
	clReleaseMemObject(memObjects[1]);
	clReleaseMemObject(memObjects[0]);
	clReleaseProgram(program);
	clReleaseCommandQueue(commandQueue);
	clReleaseContext(context);

	system("pause");
	return 0;
}

#endif<|endoftext|>


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include <string>
#include <type_traits>
#include <utility>

#include <caf/config_value.hpp>
#include <caf/io/middleman.hpp>

#include "vast/command.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/endpoint.hpp"
#include "vast/concept/parseable/vast/schema.hpp"
#include "vast/defaults.hpp"
#include "vast/detail/make_io_stream.hpp"
#include "vast/endpoint.hpp"
#include "vast/error.hpp"
#include "vast/format/reader.hpp"
#include "vast/logger.hpp"
#include "vast/schema.hpp"
#include "vast/system/datagram_source.hpp"
#include "vast/system/source.hpp"
#include "vast/system/source_command.hpp"
#include "vast/table_slice_builder.hpp"

namespace vast::system {

/// Default implementation for import sub-commands. Compatible with Bro and MRT
/// formats.
/// @relates application
template <class Reader, class Defaults>
caf::message
reader_command(const command::invocation& invocation, caf::actor_system& sys) {
  VAST_TRACE(invocation);
  auto& options = invocation.options;
  std::string category = Defaults::category;
  auto max_events = caf::get_if<size_t>(&options, "import.max-events");
  auto slice_type = defaults::import::table_slice_type(sys, options);
  auto slice_size = get_or(options, "system.table-slice-size",
                           defaults::system::table_slice_size);
  // Discern the input source (file, stream, or socket).
  auto uri = caf::get_if<std::string>(&options, category + ".listen");
  auto file = caf::get_if<std::string>(&options, category + ".read");
  if (uri && file)
    return caf::make_message(make_error(ec::invalid_configuration,
                                        "only one source possible (-r or -l)"));
  if (!uri && !file) {
    using inputs = vast::format::reader::inputs;
    if constexpr (Reader::defaults::input == inputs::inet)
      uri = std::string{Reader::defaults::uri};
    else
      file = std::string{Reader::defaults::path};
  }
  auto schema = get_schema(options, category);
  if (!schema)
    return caf::make_message(schema.error());
  if (auto type = caf::get_if<std::string>(&options, category + ".type")) {
    auto p = schema->find(*type);
    if (p == nullptr)
      return caf::make_message(
        make_error(ec::unrecognized_option, "type not found", *type));
    auto selected_type = *p;
    schema->clear();
    schema->add(selected_type);
  }
  caf::actor src;
  if (uri) {
    endpoint ep;
    if (!vast::parsers::endpoint(*uri, ep))
      return caf::make_message(
        make_error(vast::ec::parse_error, "unable to parse endpoint", *uri));
    if (ep.port.type() == port::unknown) {
      using inputs = vast::format::reader::inputs;
      if constexpr (Reader::defaults::input == inputs::inet) {
        endpoint default_ep;
        vast::parsers::endpoint(Reader::defaults::uri, default_ep);
        ep.port = port{ep.port.number(), default_ep.port.type()};
      } else {
        // Fall back to tcp if we don't know anything else.
        ep.port = port{ep.port.number(), port::tcp};
      }
    }
    Reader reader{slice_type, options};
    if (schema)
      reader.schema(*schema);
    auto run = [&](auto&& source) {
      auto& mm = sys.middleman();
      return mm.spawn_broker(std::forward<decltype(source)>(source),
                             ep.port.number(), std::move(reader), slice_size,
                             max_events);
    };
    VAST_INFO(reader, "listens for data on", ep.host, ", port", ep.port);
    switch (ep.port.type()) {
      default:
        return caf::make_message(
          make_error(vast::ec::unimplemented,
                     "port type not supported:", ep.port.type()));
      case port::udp:
        src = run(datagram_source<Reader>);
    }
  } else {
    auto uds = get_or(options, category + ".uds", false);
    auto in = detail::make_input_stream(*file, uds);
    if (!in)
      return caf::make_message(std::move(in.error()));
    Reader reader{slice_type, options, std::move(*in)};
    if (schema)
      reader.schema(*schema);
    VAST_INFO(reader, "reads data from", *file);
    src = sys.spawn(source<Reader>, std::move(reader), slice_size, max_events);
  }
  return source_command(invocation, sys, std::move(src));
}

} // namespace vast::system
<commit_msg>Use a more precise error code for type selection<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include <string>
#include <type_traits>
#include <utility>

#include <caf/config_value.hpp>
#include <caf/io/middleman.hpp>

#include "vast/command.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/endpoint.hpp"
#include "vast/concept/parseable/vast/schema.hpp"
#include "vast/defaults.hpp"
#include "vast/detail/make_io_stream.hpp"
#include "vast/endpoint.hpp"
#include "vast/error.hpp"
#include "vast/format/reader.hpp"
#include "vast/logger.hpp"
#include "vast/schema.hpp"
#include "vast/system/datagram_source.hpp"
#include "vast/system/source.hpp"
#include "vast/system/source_command.hpp"
#include "vast/table_slice_builder.hpp"

namespace vast::system {

/// Default implementation for import sub-commands. Compatible with Bro and MRT
/// formats.
/// @relates application
template <class Reader, class Defaults>
caf::message
reader_command(const command::invocation& invocation, caf::actor_system& sys) {
  VAST_TRACE(invocation);
  auto& options = invocation.options;
  std::string category = Defaults::category;
  auto max_events = caf::get_if<size_t>(&options, "import.max-events");
  auto slice_type = defaults::import::table_slice_type(sys, options);
  auto slice_size = get_or(options, "system.table-slice-size",
                           defaults::system::table_slice_size);
  // Discern the input source (file, stream, or socket).
  auto uri = caf::get_if<std::string>(&options, category + ".listen");
  auto file = caf::get_if<std::string>(&options, category + ".read");
  if (uri && file)
    return caf::make_message(make_error(ec::invalid_configuration,
                                        "only one source possible (-r or -l)"));
  if (!uri && !file) {
    using inputs = vast::format::reader::inputs;
    if constexpr (Reader::defaults::input == inputs::inet)
      uri = std::string{Reader::defaults::uri};
    else
      file = std::string{Reader::defaults::path};
  }
  auto schema = get_schema(options, category);
  if (!schema)
    return caf::make_message(schema.error());
  if (auto type = caf::get_if<std::string>(&options, category + ".type")) {
    auto p = schema->find(*type);
    if (p == nullptr)
      return caf::make_message(
        make_error(ec::lookup_error, "type not found", *type));
    auto selected_type = *p;
    schema->clear();
    schema->add(selected_type);
  }
  caf::actor src;
  if (uri) {
    endpoint ep;
    if (!vast::parsers::endpoint(*uri, ep))
      return caf::make_message(
        make_error(vast::ec::parse_error, "unable to parse endpoint", *uri));
    if (ep.port.type() == port::unknown) {
      using inputs = vast::format::reader::inputs;
      if constexpr (Reader::defaults::input == inputs::inet) {
        endpoint default_ep;
        vast::parsers::endpoint(Reader::defaults::uri, default_ep);
        ep.port = port{ep.port.number(), default_ep.port.type()};
      } else {
        // Fall back to tcp if we don't know anything else.
        ep.port = port{ep.port.number(), port::tcp};
      }
    }
    Reader reader{slice_type, options};
    if (schema)
      reader.schema(*schema);
    auto run = [&](auto&& source) {
      auto& mm = sys.middleman();
      return mm.spawn_broker(std::forward<decltype(source)>(source),
                             ep.port.number(), std::move(reader), slice_size,
                             max_events);
    };
    VAST_INFO(reader, "listens for data on", ep.host, ", port", ep.port);
    switch (ep.port.type()) {
      default:
        return caf::make_message(
          make_error(vast::ec::unimplemented,
                     "port type not supported:", ep.port.type()));
      case port::udp:
        src = run(datagram_source<Reader>);
    }
  } else {
    auto uds = get_or(options, category + ".uds", false);
    auto in = detail::make_input_stream(*file, uds);
    if (!in)
      return caf::make_message(std::move(in.error()));
    Reader reader{slice_type, options, std::move(*in)};
    if (schema)
      reader.schema(*schema);
    VAST_INFO(reader, "reads data from", *file);
    src = sys.spawn(source<Reader>, std::move(reader), slice_size, max_events);
  }
  return source_command(invocation, sys, std::move(src));
}

} // namespace vast::system
<|endoftext|>