<commit_before>#include "libmesh/fparser_ad.hh"

// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#define VECTORMAPOBJECTTEST                     \
  CPPUNIT_TEST( testCreate );                   \

class FParserAutodiffTest : public CppUnit::TestCase
{
public:
  CPPUNIT_TEST_SUITE ( FParserAutodiffTest );

  CPPUNIT_TEST ( runTests );

  CPPUNIT_TEST_SUITE_END ();

private:

  class ADTest {
  public:
    ADTest(const std::string & _func, double _min, double _max, double _dx = 1e-6, double _reltol = 1e-5, int _steps = 20, double _abstol = 1e-10) :
        func(_func),
        min(_min),
        max(_max),
        dx(_dx),
        reltol(_reltol),
        abstol(_abstol),
        steps(_steps)
    {
      CPPUNIT_ASSERT_MESSAGE ("Failed to parse test function", F.Parse(func, "x") == -1);
      dF.Parse(func, "x");
      dFopt.Parse(func, "x");

      CPPUNIT_ASSERT_MESSAGE ("Failed to take derivative of function", dF.AutoDiff("x") == -1);

      dFopt.Optimize();
      CPPUNIT_ASSERT_MESSAGE ("Failed to take derivative of optimized function", dFopt.AutoDiff("x") == -1);
    }

    bool run()
    {
      double x1, x2, vdF, vF1, vF2, fd;
      for (double x = min; x <= max; x += (max-min) / double(steps))
      {
        x1 = x - dx/2.0;
        x2 = x + dx/2.0;

        vF1 = F.Eval(&x1);
        vF2 = F.Eval(&x2);
        fd = (vF2-vF1) / dx;

        // CPPUNIT_ASSERT(std::abs(fd - vdF) > tol)
        // CPPUNIT_ASSERT(std::abs(fd - vdFopt) > tol)
        vdF = dF.Eval(&x);
        if (std::abs(vdF) > abstol && std::abs((fd - vdF)/vdF) > reltol && std::abs(fd - vdF)> abstol)
        {
          std::cout << "Error in " << func << ": " << fd << "!=" << vdF << " at x=" << x << '\n';
          return false;
        }

        vdF = dFopt.Eval(&x);
        if (std::abs(vdF) > abstol && std::abs((fd - vdF)/vdF) > reltol && std::abs(fd - vdF)> abstol)
        {
          std::cout << "Error in opt " << func << ": " << fd << "!=" << vdF << " at x=" << x << '\n';
          return false;
        }
      }

      return true;
    }

  private:
    std::string func;
    double min, max, dx, reltol, abstol;
    int steps;

    FunctionParserAD F, dF, dFopt;
  };

  std::vector<ADTest> tests;

public:
  virtual void setUp()
  {
    tests.push_back(ADTest("log(x) + log2(2*x) + log10(4*x)", 0.1, 3.0));
    tests.push_back(ADTest("sin(x) + cos(2*x) + tan(4*x)", -5.0, 5.0, 1e-7, 1e-5, 100));
    tests.push_back(ADTest("sinh(x) + cosh(x/2) + tanh(x/3)", -4.0, 4.0, 0.0001, 1e-5, 100));
    tests.push_back(ADTest("plog(x,0.01)", 0.001, 0.05, 0.00001, 1e-5, 100));
    tests.push_back(ADTest("2 + 4*x + 8*x^2 + 16*x^3 + 32*x^4", -5.0, 5.0, 1e-5,1e-4));
    tests.push_back(ADTest("1/x^2", 0.01, 2.0, 1e-8));
    tests.push_back(ADTest("sqrt(x)", 0.001, 2.0, 1e-6));
    tests.push_back(ADTest("abs(x)", -1.99, 2.0));
    tests.push_back(ADTest("asin(x)", -0.99, 0.99));
    tests.push_back(ADTest("acos(x)", -0.99, 0.99));
    tests.push_back(ADTest("atan(x)", -99, 99));
    tests.push_back(ADTest("x*sin(x)*log(x)*tanh(x)", 0.001, 5, 1e-8));
    tests.push_back(ADTest("exp(x) + 2*exp2(x)", -1.0, 2.0));
    tests.push_back(ADTest("hypot(2*x,1) - hypot(1,4*x)", -10, 10.0));
    tests.push_back(ADTest("if(x<0, (-x)^3, x^3)", -1.0, 1.0));
    tests.push_back(ADTest("max(x^2-0.5,0)", -1.5, 1.5));
    tests.push_back(ADTest("min(x^2-0.5,0)", -1.5, 1.5));
    tests.push_back(ADTest("atan2(x,1) + atan2(2,x)", -0.99, 0.99));
    tests.push_back(ADTest("0.767^sin(x)", -1.5, 1.5));
    tests.push_back(ADTest("A := sin(x) + tanh(x); A + sqrt(A) - x", -1.5, 1.5));
  }

  void runTests()
  {
    const unsigned int ntests = tests.size();

    unsigned int passed = 0;
    for (unsigned i = 0; i < ntests; ++i)
      passed += tests[i].run() ? 1 : 0;

    CPPUNIT_ASSERT_EQUAL (passed, ntests);
  }
};

CPPUNIT_TEST_SUITE_REGISTRATION ( FParserAutodiffTest );
<commit_msg>Add unit test (#463)<commit_after>#include "libmesh/fparser_ad.hh"

// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

class FParserAutodiffTest : public CppUnit::TestCase
{
public:
  CPPUNIT_TEST_SUITE ( FParserAutodiffTest );

  CPPUNIT_TEST ( runTests );
  CPPUNIT_TEST ( registerDerivativeTest );

  CPPUNIT_TEST_SUITE_END ();

private:

  class ADTest {
  public:
    ADTest(const std::string & _func, double _min, double _max, double _dx = 1e-6, double _reltol = 1e-5, int _steps = 20, double _abstol = 1e-10) :
        func(_func),
        min(_min),
        max(_max),
        dx(_dx),
        reltol(_reltol),
        abstol(_abstol),
        steps(_steps)
    {
      CPPUNIT_ASSERT_MESSAGE ("Failed to parse test function", F.Parse(func, "x") == -1);
      dF.Parse(func, "x");
      dFopt.Parse(func, "x");

      CPPUNIT_ASSERT_MESSAGE ("Failed to take derivative of function", dF.AutoDiff("x") == -1);

      dFopt.Optimize();
      CPPUNIT_ASSERT_MESSAGE ("Failed to take derivative of optimized function", dFopt.AutoDiff("x") == -1);
    }

    bool run()
    {
      double x1, x2, vdF, vF1, vF2, fd;
      for (double x = min; x <= max; x += (max-min) / double(steps))
      {
        x1 = x - dx/2.0;
        x2 = x + dx/2.0;

        vF1 = F.Eval(&x1);
        vF2 = F.Eval(&x2);
        fd = (vF2-vF1) / dx;

        // CPPUNIT_ASSERT(std::abs(fd - vdF) > tol)
        // CPPUNIT_ASSERT(std::abs(fd - vdFopt) > tol)
        vdF = dF.Eval(&x);
        if (std::abs(vdF) > abstol && std::abs((fd - vdF)/vdF) > reltol && std::abs(fd - vdF)> abstol)
        {
          std::cout << "Error in " << func << ": " << fd << "!=" << vdF << " at x=" << x << '\n';
          return false;
        }

        vdF = dFopt.Eval(&x);
        if (std::abs(vdF) > abstol && std::abs((fd - vdF)/vdF) > reltol && std::abs(fd - vdF)> abstol)
        {
          std::cout << "Error in opt " << func << ": " << fd << "!=" << vdF << " at x=" << x << '\n';
          return false;
        }
      }

      return true;
    }

  private:
    std::string func;
    double min, max, dx, reltol, abstol;
    int steps;

    FunctionParserAD F, dF, dFopt;
  };

  std::vector<ADTest> tests;

public:
  virtual void setUp()
  {
    tests.push_back(ADTest("log(x) + log2(2*x) + log10(4*x)", 0.1, 3.0));
    tests.push_back(ADTest("sin(x) + cos(2*x) + tan(4*x)", -5.0, 5.0, 1e-7, 1e-5, 100));
    tests.push_back(ADTest("sinh(x) + cosh(x/2) + tanh(x/3)", -4.0, 4.0, 0.0001, 1e-5, 100));
    tests.push_back(ADTest("plog(x,0.01)", 0.001, 0.05, 0.00001, 1e-5, 100));
    tests.push_back(ADTest("2 + 4*x + 8*x^2 + 16*x^3 + 32*x^4", -5.0, 5.0, 1e-5,1e-4));
    tests.push_back(ADTest("1/x^2", 0.01, 2.0, 1e-8));
    tests.push_back(ADTest("sqrt(x)", 0.001, 2.0, 1e-6));
    tests.push_back(ADTest("abs(x)", -1.99, 2.0));
    tests.push_back(ADTest("asin(x)", -0.99, 0.99));
    tests.push_back(ADTest("acos(x)", -0.99, 0.99));
    tests.push_back(ADTest("atan(x)", -99, 99));
    tests.push_back(ADTest("x*sin(x)*log(x)*tanh(x)", 0.001, 5, 1e-8));
    tests.push_back(ADTest("exp(x) + 2*exp2(x)", -1.0, 2.0));
    tests.push_back(ADTest("hypot(2*x,1) - hypot(1,4*x)", -10, 10.0));
    tests.push_back(ADTest("if(x<0, (-x)^3, x^3)", -1.0, 1.0));
    tests.push_back(ADTest("max(x^2-0.5,0)", -1.5, 1.5));
    tests.push_back(ADTest("min(x^2-0.5,0)", -1.5, 1.5));
    tests.push_back(ADTest("atan2(x,1) + atan2(2,x)", -0.99, 0.99));
    tests.push_back(ADTest("0.767^sin(x)", -1.5, 1.5));
    tests.push_back(ADTest("A := sin(x) + tanh(x); A + sqrt(A) - x", -1.5, 1.5));
  }

  void runTests()
  {
    const unsigned int ntests = tests.size();

    unsigned int passed = 0;
    for (unsigned i = 0; i < ntests; ++i)
      passed += tests[i].run() ? 1 : 0;

    CPPUNIT_ASSERT_EQUAL (passed, ntests);
  }

  void registerDerivativeTest()
  {
    FunctionParserAD R;
    std::string func = "x*a";

    // Parse the input expression into bytecode
    R.Parse(func, "x,a,y");
    R.RegisterDerivative("a", "x", "y");

    // parameter vector
    double p[3];
    double & x = p[0];
    double & a = p[1];
    double & y = p[2];

    FunctionParserAD dR(R);
    CPPUNIT_ASSERT_EQUAL (dR.AutoDiff("x"), -1);
    dR.Optimize();
    // dR = a+x*y

    FunctionParserAD d2R(dR);
    CPPUNIT_ASSERT_EQUAL (d2R.AutoDiff("x"), -1);
    d2R.Optimize();
    // d2R = 2*y

    // we probe the parsers and check if they agree with the reference solution
    for (x = -1.0; x < 1.0; x+=0.3726)
      for (a = -1.0; a < 1.0; a+=0.2642)
        for (y = -1.0; y < 1.0; y+=0.3156)
        {
          CPPUNIT_ASSERT_DOUBLES_EQUAL(R.Eval(p), x*a, 1.e-12);
          CPPUNIT_ASSERT_DOUBLES_EQUAL(dR.Eval(p), a+x*y, 1.e-12);
          CPPUNIT_ASSERT_DOUBLES_EQUAL(d2R.Eval(p), 2*y, 1.e-12);
        }
  }
};

CPPUNIT_TEST_SUITE_REGISTRATION ( FParserAutodiffTest );
<|endoftext|>


<commit_before>/**
 * @file   gtest_brutil.cpp
 * @author Shane Barnes
 * @date   01 Mar 2016
 * @brief  Bottlerocket utility Google unit tests.
 */

#include "manip_string.c"

#include <gtest/gtest.h>

TEST (ManipStringTest, Compare)
{
    // Empty strings or null pointers.
    ASSERT_TRUE(manip_string_compare("", "", false));
    ASSERT_TRUE(manip_string_compare("", "", true));
    ASSERT_FALSE(manip_string_compare(NULL, "", false));
    ASSERT_FALSE(manip_string_compare("", NULL, false));
    ASSERT_FALSE(manip_string_compare(NULL, "", true));
    ASSERT_FALSE(manip_string_compare("", NULL, true));
    ASSERT_FALSE(manip_string_compare(NULL, NULL, false));
    ASSERT_FALSE(manip_string_compare(NULL, NULL, true));

    // Strings containing only alphabetic characters.
    ASSERT_TRUE(manip_string_compare("string", "string", false));
    ASSERT_TRUE(manip_string_compare("string", "string", true));
    ASSERT_FALSE(manip_string_compare("string", "STRING", false));
    ASSERT_TRUE(manip_string_compare("string", "STRING", true));

    // Strings containing only numeric characters.
    ASSERT_TRUE(manip_string_compare("123", "123", false));
    ASSERT_TRUE(manip_string_compare("123", "123", true));

    // String containing alphanumeric characters.
    ASSERT_TRUE(manip_string_compare("string123", "string123", false));
    ASSERT_TRUE(manip_string_compare("string123", "string123", true));
    ASSERT_FALSE(manip_string_compare("string123", "STRING123", false));
    ASSERT_TRUE(manip_string_compare("string123", "STRING123", true));
}

TEST (ManipStringTest, Concat)
{
    char buf[16];
    const size_t bufsize = sizeof(buf);
    const char *str = "string";
    const int32_t strsize = (int32_t)strlen(str);

    // Empty buffer, empty strings, or null pointers.
    ASSERT_EQ(-1, manip_string_concat(buf, 0, NULL, NULL));
    ASSERT_EQ(-1, manip_string_concat(buf, 0, "%s", NULL));
    ASSERT_EQ(-1, manip_string_concat(buf, 0, NULL, ""));
    ASSERT_EQ(-1, manip_string_concat(buf, 0, NULL, str));
    ASSERT_EQ(-1, manip_string_concat(buf, 0, "", ""));
    ASSERT_EQ(-1, manip_string_concat(buf, 0, "%s", str));
    ASSERT_EQ(-1, manip_string_concat(NULL, 0, "%s", str));
    ASSERT_EQ(6, manip_string_concat(buf, bufsize, "%s", NULL)); // ??

    // Single- and multiple-variable concatenations.
    ASSERT_EQ(0, manip_string_concat(buf, bufsize, "%s", ""));
    ASSERT_EQ(1, manip_string_concat(buf, bufsize, "%d", 0));
    ASSERT_EQ(2, manip_string_concat(buf, bufsize, "%d", -1));
    ASSERT_EQ(2, manip_string_concat(buf, bufsize, "%d", 10));
    ASSERT_EQ(strsize, manip_string_concat(buf, bufsize, "%s", str));
    ASSERT_EQ(strsize + 1, manip_string_concat(buf, bufsize, "%s%d", str, 1));

    // Buffer overflow.
    ASSERT_EQ(strsize, manip_string_concat(buf, strsize, "%s", str));
    ASSERT_EQ(strsize, manip_string_concat(buf, strsize - 1, "%s", str));
}

int main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>gtest_brutil: fixed comment block date<commit_after>/**
 * @file   gtest_brutil.cpp
 * @author Shane Barnes
 * @date   18 Mar 2016
 * @brief  Bottlerocket utility Google unit tests.
 */

#include "manip_string.c"

#include <gtest/gtest.h>

TEST (ManipStringTest, Compare)
{
    // Empty strings or null pointers.
    ASSERT_TRUE(manip_string_compare("", "", false));
    ASSERT_TRUE(manip_string_compare("", "", true));
    ASSERT_FALSE(manip_string_compare(NULL, "", false));
    ASSERT_FALSE(manip_string_compare("", NULL, false));
    ASSERT_FALSE(manip_string_compare(NULL, "", true));
    ASSERT_FALSE(manip_string_compare("", NULL, true));
    ASSERT_FALSE(manip_string_compare(NULL, NULL, false));
    ASSERT_FALSE(manip_string_compare(NULL, NULL, true));

    // Strings containing only alphabetic characters.
    ASSERT_TRUE(manip_string_compare("string", "string", false));
    ASSERT_TRUE(manip_string_compare("string", "string", true));
    ASSERT_FALSE(manip_string_compare("string", "STRING", false));
    ASSERT_TRUE(manip_string_compare("string", "STRING", true));

    // Strings containing only numeric characters.
    ASSERT_TRUE(manip_string_compare("123", "123", false));
    ASSERT_TRUE(manip_string_compare("123", "123", true));

    // String containing alphanumeric characters.
    ASSERT_TRUE(manip_string_compare("string123", "string123", false));
    ASSERT_TRUE(manip_string_compare("string123", "string123", true));
    ASSERT_FALSE(manip_string_compare("string123", "STRING123", false));
    ASSERT_TRUE(manip_string_compare("string123", "STRING123", true));
}

TEST (ManipStringTest, Concat)
{
    char buf[16];
    const size_t bufsize = sizeof(buf);
    const char *str = "string";
    const int32_t strsize = (int32_t)strlen(str);

    // Empty buffer, empty strings, or null pointers.
    ASSERT_EQ(-1, manip_string_concat(buf, 0, NULL, NULL));
    ASSERT_EQ(-1, manip_string_concat(buf, 0, "%s", NULL));
    ASSERT_EQ(-1, manip_string_concat(buf, 0, NULL, ""));
    ASSERT_EQ(-1, manip_string_concat(buf, 0, NULL, str));
    ASSERT_EQ(-1, manip_string_concat(buf, 0, "", ""));
    ASSERT_EQ(-1, manip_string_concat(buf, 0, "%s", str));
    ASSERT_EQ(-1, manip_string_concat(NULL, 0, "%s", str));
    ASSERT_EQ(6, manip_string_concat(buf, bufsize, "%s", NULL)); // ??

    // Single- and multiple-variable concatenations.
    ASSERT_EQ(0, manip_string_concat(buf, bufsize, "%s", ""));
    ASSERT_EQ(1, manip_string_concat(buf, bufsize, "%d", 0));
    ASSERT_EQ(2, manip_string_concat(buf, bufsize, "%d", -1));
    ASSERT_EQ(2, manip_string_concat(buf, bufsize, "%d", 10));
    ASSERT_EQ(strsize, manip_string_concat(buf, bufsize, "%s", str));
    ASSERT_EQ(strsize + 1, manip_string_concat(buf, bufsize, "%s%d", str, 1));

    // Buffer overflow.
    ASSERT_EQ(strsize, manip_string_concat(buf, strsize, "%s", str));
    ASSERT_EQ(strsize, manip_string_concat(buf, strsize - 1, "%s", str));
}

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


<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.

HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.

Redistribution and use of HOOMD-blue, in source and binary forms, with or
without modification, are permitted, provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of HOOMD-blue's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.

Disclaimer

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR
ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// $Id$
// $URL$
// Maintainer: joaander

/*! \file ComputeThermo.cc
    \brief Contains code for the ComputeThermo class
*/

#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif

#include "ComputeThermo.h"

#include <boost/python.hpp>
using namespace boost::python;

#include <iostream>
using namespace std;

/*! \param sysdef System for which to compute thermodynamic properties
    \param group Subset of the system over which properties are calculated
    \param suffix Suffix to append to all logged quantity names
*/
ComputeThermo::ComputeThermo(boost::shared_ptr<SystemDefinition> sysdef,
                             boost::shared_ptr<ParticleGroup> group,
                             const std::string& suffix)
    : Compute(sysdef), m_group(group), m_ndof(1)
    {
    assert(m_pdata);
    GPUArray< Scalar > properties(4, exec_conf);
    m_properties.swap(properties);

    m_logname_list.push_back(string("temperature") + suffix);
    m_logname_list.push_back(string("pressure") + suffix);
    m_logname_list.push_back(string("kinetic_energy") + suffix);
    m_logname_list.push_back(string("potential_energy") + suffix);
    m_logname_list.push_back(string("ndof") + suffix);
    m_logname_list.push_back(string("num_particles") + suffix);
    }

/*! \param ndof Number of degrees of freedom to set
*/
void ComputeThermo::setNDOF(unsigned int ndof)
    {
    if (ndof == 0)
        {
        cout << "***Warning! compute.thermo specified for a group with 0 degrees of freedom." << endl
             << "            overriding ndof=1 to avoid divide by 0 errors" << endl;
        ndof = 1;
        }

    m_ndof = ndof;
    }

/*! Calls computeProperties if the properties need updating
    \param timestep Current time step of the simulation
*/
void ComputeThermo::compute(unsigned int timestep)
    {
    if (!shouldCompute(timestep))
        return;

    computeProperties();
    }

std::vector< std::string > ComputeThermo::getProvidedLogQuantities()
    {
    return m_logname_list;
    }

Scalar ComputeThermo::getLogValue(const std::string& quantity, unsigned int timestep)
    {
    compute(timestep);
    if (quantity == m_logname_list[0])
        {
        return getTemperature();
        }
    else if (quantity == m_logname_list[1])
        {
        return getPressure();
        }
    else if (quantity == m_logname_list[2])
        {
        return getKineticEnergy();
        }
    else if (quantity == m_logname_list[3])
        {
        return getPotentialEnergy();
        }
    else if (quantity == m_logname_list[4])
        {
        return Scalar(m_ndof);
        }
    else if (quantity == m_logname_list[5])
        {
        return Scalar(m_group->getNumMembers());
        }
    else
        {
        cerr << endl << "***Error! " << quantity << " is not a valid log quantity for ComputeThermo" << endl << endl;
        throw runtime_error("Error getting log value");
        }
    }

/*! Computes all thermodynamic properties of the system in one fell swoop.
*/
void ComputeThermo::computeProperties()
    {
    unsigned int group_size = m_group->getNumMembers();
    // just drop out if the group is an empty group
    if (group_size == 0)
        return;

    if (m_prof) m_prof->push("Thermo");

    assert(m_pdata);
    assert(m_ndof != 0);

    // access the particle data
    const ParticleDataArraysConst& arrays = m_pdata->acquireReadOnly();

    // access the net force, pe, and virial
    const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce();
    const GPUArray< Scalar >& net_virial = m_pdata->getNetVirial();
    ArrayHandle<Scalar4> h_net_force(net_force, access_location::host, access_mode::read);
    ArrayHandle<Scalar> h_net_virial(net_virial, access_location::host, access_mode::read);

    // total kinetic energy
    double ke_total = 0.0;
    for (unsigned int group_idx = 0; group_idx < group_size; group_idx++)
        {
        unsigned int j = m_group->getMemberIndex(group_idx);
        ke_total += (double)arrays.mass[j]*(  (double)arrays.vx[j] * (double)arrays.vx[j]
                                            + (double)arrays.vy[j] * (double)arrays.vy[j]
                                            + (double)arrays.vz[j] * (double)arrays.vz[j]);
        }
    ke_total *= 0.5;

    // total potential energy
    double pe_total = 0.0;
    for (unsigned int group_idx = 0; group_idx < group_size; group_idx++)
        {
        unsigned int j = m_group->getMemberIndex(group_idx);
        pe_total += (double)h_net_force.data[j].w;
        }

    // total the virial
    double W = 0.0;
    for (unsigned int group_idx = 0; group_idx < group_size; group_idx++)
        {
        unsigned int j = m_group->getMemberIndex(group_idx);
        W += (double)h_net_virial.data[j];
        }

    m_pdata->release();

    // compute the temperature
    Scalar temperature = Scalar(2.0) * Scalar(ke_total) / Scalar(m_ndof);

    // compute the pressure
    // volume/area & other 2D stuff needed
    BoxDim box = m_pdata->getBox();
    Scalar volume;
    unsigned int D = m_sysdef->getNDimensions();
    if (D == 2)
        {
        // "volume" is area in 2D
        volume = (box.xhi - box.xlo)*(box.yhi - box.ylo);
        // W needs to be corrected since the 1/3 factor is built in
        W *= Scalar(3.0/2.0);
        }
    else
        {
        volume = (box.xhi - box.xlo)*(box.yhi - box.ylo)*(box.zhi-box.zlo);
        }

    // pressure: P = (N * K_B * T + W)/V
    Scalar pressure =  (2.0 * ke_total / Scalar(D) + W) / volume;

    // fill out the GPUArray
    ArrayHandle<Scalar> h_properties(m_properties, access_location::host, access_mode::overwrite);
    h_properties.data[thermo_index::temperature] = temperature;
    h_properties.data[thermo_index::pressure] = pressure;
    h_properties.data[thermo_index::kinetic_energy] = Scalar(ke_total);
    h_properties.data[thermo_index::potential_energy] = Scalar(pe_total);

    if (m_prof) m_prof->pop();
    }

void export_ComputeThermo()
    {
    class_<ComputeThermo, boost::shared_ptr<ComputeThermo>, bases<Compute>, boost::noncopyable >
    ("ComputeThermo", init< boost::shared_ptr<SystemDefinition>,
                      boost::shared_ptr<ParticleGroup>,
                      const std::string& >())
    .def("setNDOF", &ComputeThermo::setNDOF)
    .def("getTemperature", &ComputeThermo::getTemperature)
    .def("getPressure", &ComputeThermo::getPressure)
    .def("getKineticEnergy", &ComputeThermo::getKineticEnergy)
    .def("getPotentialEnergy", &ComputeThermo::getPotentialEnergy)
    ;
    }

#ifdef WIN32
#pragma warning( pop )
#endif

<commit_msg>Using mapped memory for compute thermo results<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.

HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.

Redistribution and use of HOOMD-blue, in source and binary forms, with or
without modification, are permitted, provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of HOOMD-blue's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.

Disclaimer

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR
ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// $Id$
// $URL$
// Maintainer: joaander

/*! \file ComputeThermo.cc
    \brief Contains code for the ComputeThermo class
*/

#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif

#include "ComputeThermo.h"

#include <boost/python.hpp>
using namespace boost::python;

#include <iostream>
using namespace std;

/*! \param sysdef System for which to compute thermodynamic properties
    \param group Subset of the system over which properties are calculated
    \param suffix Suffix to append to all logged quantity names
*/
ComputeThermo::ComputeThermo(boost::shared_ptr<SystemDefinition> sysdef,
                             boost::shared_ptr<ParticleGroup> group,
                             const std::string& suffix)
    : Compute(sysdef), m_group(group), m_ndof(1)
    {
    assert(m_pdata);
    GPUArray< Scalar > properties(4, exec_conf, true);
    m_properties.swap(properties);

    m_logname_list.push_back(string("temperature") + suffix);
    m_logname_list.push_back(string("pressure") + suffix);
    m_logname_list.push_back(string("kinetic_energy") + suffix);
    m_logname_list.push_back(string("potential_energy") + suffix);
    m_logname_list.push_back(string("ndof") + suffix);
    m_logname_list.push_back(string("num_particles") + suffix);
    }

/*! \param ndof Number of degrees of freedom to set
*/
void ComputeThermo::setNDOF(unsigned int ndof)
    {
    if (ndof == 0)
        {
        cout << "***Warning! compute.thermo specified for a group with 0 degrees of freedom." << endl
             << "            overriding ndof=1 to avoid divide by 0 errors" << endl;
        ndof = 1;
        }

    m_ndof = ndof;
    }

/*! Calls computeProperties if the properties need updating
    \param timestep Current time step of the simulation
*/
void ComputeThermo::compute(unsigned int timestep)
    {
    if (!shouldCompute(timestep))
        return;

    computeProperties();
    }

std::vector< std::string > ComputeThermo::getProvidedLogQuantities()
    {
    return m_logname_list;
    }

Scalar ComputeThermo::getLogValue(const std::string& quantity, unsigned int timestep)
    {
    compute(timestep);
    if (quantity == m_logname_list[0])
        {
        return getTemperature();
        }
    else if (quantity == m_logname_list[1])
        {
        return getPressure();
        }
    else if (quantity == m_logname_list[2])
        {
        return getKineticEnergy();
        }
    else if (quantity == m_logname_list[3])
        {
        return getPotentialEnergy();
        }
    else if (quantity == m_logname_list[4])
        {
        return Scalar(m_ndof);
        }
    else if (quantity == m_logname_list[5])
        {
        return Scalar(m_group->getNumMembers());
        }
    else
        {
        cerr << endl << "***Error! " << quantity << " is not a valid log quantity for ComputeThermo" << endl << endl;
        throw runtime_error("Error getting log value");
        }
    }

/*! Computes all thermodynamic properties of the system in one fell swoop.
*/
void ComputeThermo::computeProperties()
    {
    unsigned int group_size = m_group->getNumMembers();
    // just drop out if the group is an empty group
    if (group_size == 0)
        return;

    if (m_prof) m_prof->push("Thermo");

    assert(m_pdata);
    assert(m_ndof != 0);

    // access the particle data
    const ParticleDataArraysConst& arrays = m_pdata->acquireReadOnly();

    // access the net force, pe, and virial
    const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce();
    const GPUArray< Scalar >& net_virial = m_pdata->getNetVirial();
    ArrayHandle<Scalar4> h_net_force(net_force, access_location::host, access_mode::read);
    ArrayHandle<Scalar> h_net_virial(net_virial, access_location::host, access_mode::read);

    // total kinetic energy
    double ke_total = 0.0;
    for (unsigned int group_idx = 0; group_idx < group_size; group_idx++)
        {
        unsigned int j = m_group->getMemberIndex(group_idx);
        ke_total += (double)arrays.mass[j]*(  (double)arrays.vx[j] * (double)arrays.vx[j]
                                            + (double)arrays.vy[j] * (double)arrays.vy[j]
                                            + (double)arrays.vz[j] * (double)arrays.vz[j]);
        }
    ke_total *= 0.5;

    // total potential energy
    double pe_total = 0.0;
    for (unsigned int group_idx = 0; group_idx < group_size; group_idx++)
        {
        unsigned int j = m_group->getMemberIndex(group_idx);
        pe_total += (double)h_net_force.data[j].w;
        }

    // total the virial
    double W = 0.0;
    for (unsigned int group_idx = 0; group_idx < group_size; group_idx++)
        {
        unsigned int j = m_group->getMemberIndex(group_idx);
        W += (double)h_net_virial.data[j];
        }

    m_pdata->release();

    // compute the temperature
    Scalar temperature = Scalar(2.0) * Scalar(ke_total) / Scalar(m_ndof);

    // compute the pressure
    // volume/area & other 2D stuff needed
    BoxDim box = m_pdata->getBox();
    Scalar volume;
    unsigned int D = m_sysdef->getNDimensions();
    if (D == 2)
        {
        // "volume" is area in 2D
        volume = (box.xhi - box.xlo)*(box.yhi - box.ylo);
        // W needs to be corrected since the 1/3 factor is built in
        W *= Scalar(3.0/2.0);
        }
    else
        {
        volume = (box.xhi - box.xlo)*(box.yhi - box.ylo)*(box.zhi-box.zlo);
        }

    // pressure: P = (N * K_B * T + W)/V
    Scalar pressure =  (2.0 * ke_total / Scalar(D) + W) / volume;

    // fill out the GPUArray
    ArrayHandle<Scalar> h_properties(m_properties, access_location::host, access_mode::overwrite);
    h_properties.data[thermo_index::temperature] = temperature;
    h_properties.data[thermo_index::pressure] = pressure;
    h_properties.data[thermo_index::kinetic_energy] = Scalar(ke_total);
    h_properties.data[thermo_index::potential_energy] = Scalar(pe_total);

    if (m_prof) m_prof->pop();
    }

void export_ComputeThermo()
    {
    class_<ComputeThermo, boost::shared_ptr<ComputeThermo>, bases<Compute>, boost::noncopyable >
    ("ComputeThermo", init< boost::shared_ptr<SystemDefinition>,
                      boost::shared_ptr<ParticleGroup>,
                      const std::string& >())
    .def("setNDOF", &ComputeThermo::setNDOF)
    .def("getTemperature", &ComputeThermo::getTemperature)
    .def("getPressure", &ComputeThermo::getPressure)
    .def("getKineticEnergy", &ComputeThermo::getKineticEnergy)
    .def("getPotentialEnergy", &ComputeThermo::getPotentialEnergy)
    ;
    }

#ifdef WIN32
#pragma warning( pop )
#endif

<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */
//  TEST    Foundation::Database
#include "Stroika/Foundation/StroikaPreComp.h"

#include "Stroika/Foundation/Characters/Format.h"
#include "Stroika/Foundation/Characters/StringBuilder.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/Database/SQLite.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/IO/FileSystem/FileSystem.h"
#include "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h"
#include "Stroika/Foundation/Time/Duration.h"

#include "../TestHarness/TestHarness.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Database;
using namespace Stroika::Foundation::Debug;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Time;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

#if qHasFeature_sqlite
namespace {
    namespace RegressionTest1_sqlite_ {
        namespace PRIVATE_ {
            using namespace Database::SQLite;
            enum class ScanKindType_ {
                Background,
                Reference,
                Sample,
                Stroika_Define_Enum_Bounds (Background, Sample)
            };
            using ScanIDType_                 = uint64_t;
            using SpectrumType_               = Mapping<double, double>;
            using PersistenceScanAuxDataType_ = Mapping<String, String>;
            struct DB {
            public:
                DB (const filesystem::path& testDBFile)
                {
                    bool created = false;
                    try {
#if __cpp_designated_initializers
                        fDB_ = Connection::New (Options{.fDBPath = testDBFile}, [&created] (Database::SQLite::Connection::Ptr db) { created = true; InitialSetup_ (db); });
#else
                        fDB_ = Connection::New (Options{testDBFile}, [&created] (Database::SQLite::Connection::Ptr db) { created = true; InitialSetup_ (db); });
#endif
                    }
                    catch (...) {
                        DbgTrace (L"Error %s experiment DB: %s: %s", created ? L"creating" : L"opening", Characters::ToString (testDBFile).c_str (), Characters::ToString (current_exception ()).c_str ());
                        Execution::ReThrow ();
                    }
                    if (created) {
                        DbgTrace (L"Initialized new experiment DB: %s", Characters::ToString (testDBFile).c_str ());
                    }
                    else {
                        DbgTrace (L"Opened experiment DB: %s", Characters::ToString (testDBFile).c_str ());
                    }
                }
                DB ()
                {
                    bool created = false;
                    try {
#if __cpp_designated_initializers
                        fDB_ = Connection::New (Options{.fInMemoryDB = L""}, [&created] (Database::SQLite::Connection::Ptr db) { created = true; InitialSetup_(db); });
#else
                        fDB_ = Connection::New (Options{nullopt, true, nullopt, L""}, [&created] (Database::SQLite::Connection::Ptr db) { created = true; InitialSetup_(db); });
#endif
                    }
                    catch (...) {
                        DbgTrace (L"Error %s experiment DB: %s: %s", created ? L"creating" : L"opening", L"MEMORY", Characters::ToString (current_exception ()).c_str ());
                        Execution::ReThrow ();
                    }
                    if (created) {
                        DbgTrace (L"Initialized new experiment DB: %s", L"MEMORY");
                    }
                    else {
                        DbgTrace (L"Opened experiment DB: %s", L"MEMORY");
                    }
                }
                DB (const DB&)                 = delete;
                nonvirtual DB&         operator= (const DB&) = delete;
                nonvirtual ScanIDType_ ScanPersistenceAdd (const DateTime& ScanStart, const DateTime& ScanEnd, const optional<String>& ScanLabel, ScanKindType_ scanKind, const optional<SpectrumType_>& rawSpectrum)
                {
                    String insertSQL = [&] () {
                        StringBuilder sb;
                        sb += L"insert into Scans (StartAt, EndAt, ScanTypeIDRef, RawScanData, ScanLabel)";
                        sb += L"select ";
                        sb += L"'" + ScanStart.AsUTC ().Format (DateTime::kISO8601Format) + L"',";
                        sb += L"'" + ScanEnd.AsUTC ().Format (DateTime::kISO8601Format) + L"',";
                        sb += Characters::Format (L"%d", scanKind) + L",";
                        if (rawSpectrum) {
                            sb += L"'" + Database::SQLite::QuoteStringForDB (L"SomeLongASCIIStringS\r\r\n\t'omeLongASCIIStringSomeLongASCIIStringSomeLongASCIIString") + L"',";
                        }
                        else {
                            sb += L"NULL,";
                        }
                        if (ScanLabel) {
                            sb += L"'" + Database::SQLite::QuoteStringForDB (*ScanLabel) + L"'";
                        }
                        else {
                            sb += L"NULL";
                        }
                        sb += L";";
                        return sb.str ();
                    }();
                    fDB_.Exec (L"%s", insertSQL.c_str ());
                    Statement s{fDB_, L"SELECT MAX(ScanId) FROM Scans;"};
                    DbgTrace (L"Statement: %s", Characters::ToString (s).c_str ());

                    if (optional<Statement::Row> r = s.GetNextRow ()) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
                        DbgTrace (L"ROW: %s", Characters::ToString (*r).c_str ());
#endif
                        return r->Lookup (L"MAX(ScanId)")->As<ScanIDType_> ();
                    }
                    AssertNotReached ();
                    return ScanIDType_{};
                }
                nonvirtual optional<ScanIDType_> GetLastScan (ScanKindType_ scanKind)
                {
                    Statement s{fDB_, L"select MAX(ScanId) from Scans where  ScanTypeIDRef='%d';", scanKind};
                    DbgTrace (L"Statement: %s", Characters::ToString (s).c_str ());
                    if (optional<Statement::Row> r = s.GetNextRow ()) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
                        DbgTrace (L"ROW: %s", Characters::ToString (*r).c_str ());
#endif
                        return r->Lookup (L"MAX(ScanId)")->As<ScanIDType_> ();
                    }
                    return nullopt;
                }
                static void InitialSetup_ (Database::SQLite::Connection::Ptr db)
                {
                    TraceContextBumper ctx{"ScanDB_::DB::InitialSetup_"};
                    auto               tableSetup_ScanTypes = [&db] () {
                        db.Exec (L"create table 'ScanTypes' "
                                 L"("
                                 L"ScanTypeId tinyint Primary Key,"
                                 L"TypeName varchar(255) not null"
                                 L");");
                        db.Exec (L"insert into ScanTypes (ScanTypeId, TypeName) select %d, 'Reference';", ScanKindType_::Reference);
                        db.Exec (L"insert into ScanTypes (ScanTypeId, TypeName) select %d, 'Sample';", ScanKindType_::Sample);
                        db.Exec (L"insert into ScanTypes (ScanTypeId, TypeName) select %d, 'Background';", ScanKindType_::Background);
                    };
                    auto tableSetup_Scans = [&db] () {
                        db.Exec (
                            L"create table 'Scans'"
                            L"("
                            L"ScanId integer Primary Key AUTOINCREMENT,"
                            L"StartAt Datetime not null,"
                            L"EndAt Datetime not null,"
                            L"ScanTypeIDRef tinyint not null,"
                            L"ScanLabel varchar,"
                            L"Foreign key (ScanTypeIDRef) References ScanTypes (ScanTypeId)"
                            L");");
                    };
                    auto tableSetup_ScanSets = [&db] () {
                        db.Exec (
                            L"Create table ScanSet"
                            L"("
                            L"ScanSetID bigint,"
                            L"ScanIDRef integer,"
                            L"Foreign key (ScanIdRef) References Scans(ScanId)"
                            L");");
                    };
                    auto tableSetup_AuxData = [&db] () {
                        db.Exec (
                            L"Create table AuxData"
                            L"("
                            L"ScanSetIDRef bigint Primary Key,"
                            L"Results varchar,"
                            L"Foreign key (ScanSetIDRef) References ScanSet(ScanSetID)"
                            L");");
                    };
                    auto tableSetup_ExtraForeignKeys = [&db] () {
                        db.Exec (L"Alter table Scans add column DependsOnScanSetIdRef bigint references ScanSet(ScanSetID);");
                        db.Exec (L"Alter table Scans add column RawScanData BLOB;");
                    };
                    tableSetup_ScanTypes ();
                    tableSetup_Scans ();
                    tableSetup_ScanSets ();
                    tableSetup_AuxData ();
                    tableSetup_ExtraForeignKeys ();
                }
                Database::SQLite::Connection::Ptr fDB_;
            };
        }
        void DoIt ()
        {
            //static const     DateTime   kScanStartTime4Reference_   = DateTime::Now ();
            static const DateTime kScanStartTime4Reference_ = DateTime{Date{Year{2020}, MonthOfYear::eApril, DayOfMonth::e1}, TimeOfDay{4, 0, 0}}; // hardwired data to be able to ccompare DBs
            using namespace PRIVATE_;
            TraceContextBumper ctx{"ScanDB::DB::RunTest"};
            auto               test = [] (PRIVATE_::DB& db, unsigned nTimesRanBefore) {
                db.fDB_->Exec (L"select * from ScanTypes;");
                {
                    Statement s{db.fDB_, L"select * from ScanTypes;"};
                    DbgTrace (L"Statement: %s", Characters::ToString (s).c_str ());
                    while (optional<Statement::Row> r = s.GetNextRow ()) {
                        DbgTrace (L"ROW: %s", Characters::ToString (*r).c_str ());
                    }
                }
                DbgTrace ("Latest Reference=%d", db.GetLastScan (ScanKindType_::Reference).value_or (static_cast<ScanIDType_> (-1)));
                SpectrumType_      spectrum;
                const unsigned int kNRecordsAddedPerTestCall = 100;
                for (int i = 0; i < kNRecordsAddedPerTestCall; ++i) {
                    DateTime    scanStartTime = kScanStartTime4Reference_ - 100ms;
                    DateTime    scanEndTime   = kScanStartTime4Reference_;
                    ScanIDType_ sid           = db.ScanPersistenceAdd (scanStartTime, scanEndTime, String{L"Hi Mom"}, ScanKindType_::Reference, spectrum);
                    Verify (sid == *db.GetLastScan (ScanKindType_::Reference));
                    Verify (sid == nTimesRanBefore * kNRecordsAddedPerTestCall + i + 1);
#if USE_NOISY_TRACE_IN_THIS_MODULE_
                    DbgTrace ("ScanPersistenceAdd returned id=%d, and laserScan reported=%d", (int)sid, (int)db.GetLastScan (ScanKindType_::Reference).Value (-1));
#endif
                }
            };
            {
                // re-open the file several times and assure right number of records present
                filesystem::path dbFileName = IO::FileSystem::WellKnownLocations::GetTemporary () / "foo.db";
                (void)remove (dbFileName);
                for (unsigned int i = 0; i < 5; ++i) {
                    PRIVATE_::DB db{dbFileName};
                    test (db, i);
                }
            }
            {
                PRIVATE_::DB db{};
                test (db, 0);
            }
        }
    }
}
#endif

namespace {
    void DoRegressionTests_ ()
    {
#if qHasFeature_sqlite
        RegressionTest1_sqlite_::DoIt ();
#endif
    }
}

int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
    Stroika::TestHarness::Setup ();
    return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>enhanced sqlite regtests to verify Bind() produces same result<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */
//  TEST    Foundation::Database
#include "Stroika/Foundation/StroikaPreComp.h"

#include "Stroika/Foundation/Characters/Format.h"
#include "Stroika/Foundation/Characters/StringBuilder.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/Database/SQLite.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/IO/FileSystem/FileSystem.h"
#include "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h"
#include "Stroika/Foundation/Time/Duration.h"

#include "../TestHarness/TestHarness.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Database;
using namespace Stroika::Foundation::Debug;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Time;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

#if qHasFeature_sqlite
namespace {
    namespace RegressionTest1_sqlite_ {
        namespace PRIVATE_ {
            using namespace Database::SQLite;
            enum class ScanKindType_ {
                Background,
                Reference,
                Sample,
                Stroika_Define_Enum_Bounds (Background, Sample)
            };
            using ScanIDType_                 = uint64_t;
            using SpectrumType_               = Mapping<double, double>;
            using PersistenceScanAuxDataType_ = Mapping<String, String>;
            struct DB {
            public:
                DB (const filesystem::path& testDBFile)
                {
                    bool created = false;
                    try {
#if __cpp_designated_initializers
                        fDB_ = Connection::New (Options{.fDBPath = testDBFile}, [&created] (Database::SQLite::Connection::Ptr db) { created = true; InitialSetup_ (db); });
#else
                        fDB_ = Connection::New (Options{testDBFile}, [&created] (Database::SQLite::Connection::Ptr db) { created = true; InitialSetup_ (db); });
#endif
                    }
                    catch (...) {
                        DbgTrace (L"Error %s experiment DB: %s: %s", created ? L"creating" : L"opening", Characters::ToString (testDBFile).c_str (), Characters::ToString (current_exception ()).c_str ());
                        Execution::ReThrow ();
                    }
                    if (created) {
                        DbgTrace (L"Initialized new experiment DB: %s", Characters::ToString (testDBFile).c_str ());
                    }
                    else {
                        DbgTrace (L"Opened experiment DB: %s", Characters::ToString (testDBFile).c_str ());
                    }
                }
                DB ()
                {
                    bool created = false;
                    try {
#if __cpp_designated_initializers
                        fDB_ = Connection::New (Options{.fInMemoryDB = L""}, [&created] (Database::SQLite::Connection::Ptr db) { created = true; InitialSetup_(db); });
#else
                        fDB_ = Connection::New (Options{nullopt, true, nullopt, L""}, [&created] (Database::SQLite::Connection::Ptr db) { created = true; InitialSetup_(db); });
#endif
                    }
                    catch (...) {
                        DbgTrace (L"Error %s experiment DB: %s: %s", created ? L"creating" : L"opening", L"MEMORY", Characters::ToString (current_exception ()).c_str ());
                        Execution::ReThrow ();
                    }
                    if (created) {
                        DbgTrace (L"Initialized new experiment DB: %s", L"MEMORY");
                    }
                    else {
                        DbgTrace (L"Opened experiment DB: %s", L"MEMORY");
                    }
                }
                DB (const DB&)                 = delete;
                nonvirtual DB&         operator= (const DB&) = delete;
                nonvirtual ScanIDType_ ScanPersistenceAdd (const DateTime& ScanStart, const DateTime& ScanEnd, const optional<String>& ScanLabel, ScanKindType_ scanKind, const optional<SpectrumType_>& rawSpectrum)
                {
                    String insertSQL = [&] () {
                        StringBuilder sb;
                        sb += L"insert into Scans (StartAt, EndAt, ScanTypeIDRef, RawScanData, ScanLabel)";
                        sb += L"select ";
                        sb += L"'" + ScanStart.AsUTC ().Format (DateTime::kISO8601Format) + L"',";
                        sb += L"'" + ScanEnd.AsUTC ().Format (DateTime::kISO8601Format) + L"',";
                        sb += Characters::Format (L"%d", scanKind) + L",";
                        if (rawSpectrum) {
                            sb += L"'" + Database::SQLite::QuoteStringForDB (L"SomeLongASCIIStringS\r\r\n\t'omeLongASCIIStringSomeLongASCIIStringSomeLongASCIIString") + L"',";
                        }
                        else {
                            sb += L"NULL,";
                        }
                        if (ScanLabel) {
                            sb += L"'" + Database::SQLite::QuoteStringForDB (*ScanLabel) + L"'";
                        }
                        else {
                            sb += L"NULL";
                        }
                        sb += L";";
                        return sb.str ();
                    }();
                    fDB_.Exec (L"%s", insertSQL.c_str ());
                    Statement s{fDB_, L"SELECT MAX(ScanId) FROM Scans;"};
                    DbgTrace (L"Statement: %s", Characters::ToString (s).c_str ());
                    return s.GetNextRow ()->Lookup (L"MAX(ScanId)")->As<ScanIDType_> ();
                }
                nonvirtual optional<ScanIDType_> GetLastScan (ScanKindType_ scanKind)
                {
                    auto r1 = GetLastScan_Explicit_ (scanKind);
                    auto r2 = GetLastScan_Bind_ (scanKind);
                    VerifyTestResult (r1 == r2);
                    return r2;
                }
                nonvirtual optional<ScanIDType_> GetLastScan_Explicit_ (ScanKindType_ scanKind)
                {
                    Statement s{fDB_, L"select MAX(ScanId) from Scans where  ScanTypeIDRef='%d';", scanKind};
                    DbgTrace (L"Statement: %s", Characters::ToString (s).c_str ());
                    if (optional<Statement::Row> r = s.GetNextRow ()) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
                        DbgTrace (L"ROW: %s", Characters::ToString (*r).c_str ());
#endif
                        return r->Lookup (L"MAX(ScanId)")->As<ScanIDType_> ();
                    }
                    return nullopt;
                }
                nonvirtual optional<ScanIDType_> GetLastScan_Bind_ (ScanKindType_ scanKind)
                {
                    Statement s{fDB_, L"select MAX(ScanId) from Scans where  ScanTypeIDRef=:ScanKind;"};
                    s.Bind (L":ScanKind", VariantValue{(int)scanKind});
                    DbgTrace (L"Statement: %s", Characters::ToString (s).c_str ());
                    if (optional<Statement::Row> r = s.GetNextRow ()) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
                        DbgTrace (L"ROW: %s", Characters::ToString (*r).c_str ());
#endif
                        return r->Lookup (L"MAX(ScanId)")->As<ScanIDType_> ();
                    }
                    return nullopt;
                }
                static void InitialSetup_ (Database::SQLite::Connection::Ptr db)
                {
                    TraceContextBumper ctx{"ScanDB_::DB::InitialSetup_"};
                    auto               tableSetup_ScanTypes = [&db] () {
                        db.Exec (L"create table 'ScanTypes' "
                                 L"("
                                 L"ScanTypeId tinyint Primary Key,"
                                 L"TypeName varchar(255) not null"
                                 L");");
                        db.Exec (L"insert into ScanTypes (ScanTypeId, TypeName) select %d, 'Reference';", ScanKindType_::Reference);
                        db.Exec (L"insert into ScanTypes (ScanTypeId, TypeName) select %d, 'Sample';", ScanKindType_::Sample);
                        db.Exec (L"insert into ScanTypes (ScanTypeId, TypeName) select %d, 'Background';", ScanKindType_::Background);
                    };
                    auto tableSetup_Scans = [&db] () {
                        db.Exec (
                            L"create table 'Scans'"
                            L"("
                            L"ScanId integer Primary Key AUTOINCREMENT,"
                            L"StartAt Datetime not null,"
                            L"EndAt Datetime not null,"
                            L"ScanTypeIDRef tinyint not null,"
                            L"ScanLabel varchar,"
                            L"Foreign key (ScanTypeIDRef) References ScanTypes (ScanTypeId)"
                            L");");
                    };
                    auto tableSetup_ScanSets = [&db] () {
                        db.Exec (
                            L"Create table ScanSet"
                            L"("
                            L"ScanSetID bigint,"
                            L"ScanIDRef integer,"
                            L"Foreign key (ScanIdRef) References Scans(ScanId)"
                            L");");
                    };
                    auto tableSetup_AuxData = [&db] () {
                        db.Exec (
                            L"Create table AuxData"
                            L"("
                            L"ScanSetIDRef bigint Primary Key,"
                            L"Results varchar,"
                            L"Foreign key (ScanSetIDRef) References ScanSet(ScanSetID)"
                            L");");
                    };
                    auto tableSetup_ExtraForeignKeys = [&db] () {
                        db.Exec (L"Alter table Scans add column DependsOnScanSetIdRef bigint references ScanSet(ScanSetID);");
                        db.Exec (L"Alter table Scans add column RawScanData BLOB;");
                    };
                    tableSetup_ScanTypes ();
                    tableSetup_Scans ();
                    tableSetup_ScanSets ();
                    tableSetup_AuxData ();
                    tableSetup_ExtraForeignKeys ();
                }
                Database::SQLite::Connection::Ptr fDB_;
            };
        }
        void DoIt ()
        {
            //static const     DateTime   kScanStartTime4Reference_   = DateTime::Now ();
            static const DateTime kScanStartTime4Reference_ = DateTime{Date{Year{2020}, MonthOfYear::eApril, DayOfMonth::e1}, TimeOfDay{4, 0, 0}}; // hardwired data to be able to ccompare DBs
            using namespace PRIVATE_;
            TraceContextBumper ctx{"ScanDB::DB::RunTest"};
            auto               test = [] (PRIVATE_::DB& db, unsigned nTimesRanBefore) {
                db.fDB_->Exec (L"select * from ScanTypes;");
                {
                    Statement s{db.fDB_, L"select * from ScanTypes;"};
                    DbgTrace (L"Statement: %s", Characters::ToString (s).c_str ());
                    while (optional<Statement::Row> r = s.GetNextRow ()) {
                        DbgTrace (L"ROW: %s", Characters::ToString (*r).c_str ());
                    }
                }
                DbgTrace ("Latest Reference=%d", db.GetLastScan (ScanKindType_::Reference).value_or (static_cast<ScanIDType_> (-1)));
                SpectrumType_      spectrum;
                const unsigned int kNRecordsAddedPerTestCall = 100;
                for (int i = 0; i < kNRecordsAddedPerTestCall; ++i) {
                    DateTime    scanStartTime = kScanStartTime4Reference_ - 100ms;
                    DateTime    scanEndTime   = kScanStartTime4Reference_;
                    ScanIDType_ sid           = db.ScanPersistenceAdd (scanStartTime, scanEndTime, String{L"Hi Mom"}, ScanKindType_::Reference, spectrum);
                    Verify (sid == *db.GetLastScan (ScanKindType_::Reference));
                    Verify (sid == nTimesRanBefore * kNRecordsAddedPerTestCall + i + 1);
#if USE_NOISY_TRACE_IN_THIS_MODULE_
                    DbgTrace ("ScanPersistenceAdd returned id=%d, and laserScan reported=%d", (int)sid, (int)db.GetLastScan (ScanKindType_::Reference).Value (-1));
#endif
                }
            };
            {
                // re-open the file several times and assure right number of records present
                filesystem::path dbFileName = IO::FileSystem::WellKnownLocations::GetTemporary () / "foo.db";
                (void)remove (dbFileName);
                for (unsigned int i = 0; i < 5; ++i) {
                    PRIVATE_::DB db{dbFileName};
                    test (db, i);
                }
            }
            {
                PRIVATE_::DB db{};
                test (db, 0);
            }
        }
    }
}
#endif

namespace {
    void DoRegressionTests_ ()
    {
#if qHasFeature_sqlite
        RegressionTest1_sqlite_::DoIt ();
#endif
    }
}

int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
    Stroika::TestHarness::Setup ();
    return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|>


<commit_before>#include "GPUSimulator.h"

//void initMTGPU(int seed, int mt_rng_count);
void initMTGPU(unsigned int seed, unsigned int blocks, unsigned int threads, unsigned int nPerRng, unsigned int mt_rng_count);

/**
 *  Constructor
 *  @param  network
 *          pointer to a neural network implementation to be simulated by BrainGrid. (It would be
 *          nice if this was a parameter to #simulate). Note: this reference will not be deleted.
 *  @param  sim_info    parameters for the simulation.
 */
GPUSimulator::GPUSimulator(Network *network, SimulationInfo sim_info) : Simulator(network, sim_info)
{

    //initialize Mersenne Twister
    //assuming neuron_count >= 100 and is a multiple of 100. Note rng_mt_rng_count must be <= MT_RNG_COUNT
    int rng_blocks = 25; //# of blocks the kernel will use
    int rng_nPerRng = 4; //# of iterations per thread (thread granularity, # of rands generated per thread)
    int rng_mt_rng_count = neuron_count/rng_nPerRng; //# of threads to generate for neuron_count rand #s
    int rng_threads = rng_mt_rng_count/rng_blocks; //# threads per block needed
    initMTGPU(777, rng_blocks, rng_threads, rng_nPerRng, rng_mt_rng_count);

}
<commit_msg>added comments about need to investigate RNG creation<commit_after>#include "GPUSimulator.h"

//void initMTGPU(int seed, int mt_rng_count);
void initMTGPU(unsigned int seed, unsigned int blocks, unsigned int threads, unsigned int nPerRng, unsigned int mt_rng_count);

/**
 *  Constructor
 *  @param  network
 *          pointer to a neural network implementation to be simulated by BrainGrid. (It would be
 *          nice if this was a parameter to #simulate). Note: this reference will not be deleted.
 *  @param  sim_info    parameters for the simulation.
 */
GPUSimulator::GPUSimulator(Network *network, SimulationInfo sim_info) : Simulator(network, sim_info)
{
    /*
	This was copied over from GPUSim.cpp's constructor. Investigation needs to be done on
	whether or not this is the proper way to intialize the RNG with the new design. Also,
	I was unable to find a definition for initMTGPU anywhere in the old branch.
    */

    //initialize Mersenne Twister
    //assuming neuron_count >= 100 and is a multiple of 100. Note rng_mt_rng_count must be <= MT_RNG_COUNT
    int rng_blocks = 25; //# of blocks the kernel will use
    int rng_nPerRng = 4; //# of iterations per thread (thread granularity, # of rands generated per thread)
    int rng_mt_rng_count = neuron_count/rng_nPerRng; //# of threads to generate for neuron_count rand #s
    int rng_threads = rng_mt_rng_count/rng_blocks; //# threads per block needed
    initMTGPU(777, rng_blocks, rng_threads, rng_nPerRng, rng_mt_rng_count);

}
<|endoftext|>


<commit_before>#include <string>
#include <fstream>
#include <streambuf>
#include <iostream>

#define BOOST_TEST_MODULE JSONTest
#include <boost/test/included/unit_test.hpp>
#include <boost/smart_ptr.hpp>

#include "json.hpp"

using boost::shared_ptr;
using std::cout;
using std::endl;
using std::string;
using std::map;
using std::list;
using std::set;

using nlohmann::json;

BOOST_AUTO_TEST_CASE( JSON1 )
{
  json j = "{}"_json ;
  BOOST_CHECK( j.empty() );
  BOOST_CHECK( !j.is_null() );
  BOOST_CHECK( j.is_object() );
}

BOOST_AUTO_TEST_CASE( JSON2 )
{
  json j;
  BOOST_CHECK( j.empty() );
  BOOST_CHECK( j.is_null() );
  BOOST_CHECK( !j.is_object() );
}

BOOST_AUTO_TEST_CASE( JSON3 )
{
  json j = std::vector<int>{} ;
  BOOST_CHECK( j.empty() );
  BOOST_CHECK( !j.is_null() );
  BOOST_CHECK( j.is_array() );
  BOOST_CHECK( j.size() == 0 );
}

BOOST_AUTO_TEST_CASE( JSON4 )
{
  json j = "[]"_json ;
  BOOST_CHECK( j.empty() );
  BOOST_CHECK( !j.is_null() );
  BOOST_CHECK( j.is_array() );
  BOOST_CHECK( j.size() == 0 );
}

BOOST_AUTO_TEST_CASE( JSON5 )
{
  json j = R"foo(
{ "a": 10,
  "b": "bar"
}
)foo"_json ;

  json j2 = { { "a", 10 }, { "b", "bar" } } ;
  BOOST_CHECK( j == j2) ;
}
<commit_msg>json maps must have string keys -- ints won't do<commit_after>#include <string>
#include <fstream>
#include <streambuf>
#include <iostream>

#define BOOST_TEST_MODULE JSONTest
#include <boost/test/included/unit_test.hpp>
#include <boost/smart_ptr.hpp>

#include "json.hpp"

using boost::shared_ptr;
using std::cout;
using std::endl;
using std::string;
using std::map;
using std::list;
using std::set;

using nlohmann::json;

BOOST_AUTO_TEST_CASE( JSON1 )
{
  json j = "{}"_json ;
  BOOST_CHECK( j.empty() );
  BOOST_CHECK( !j.is_null() );
  BOOST_CHECK( j.is_object() );
}

BOOST_AUTO_TEST_CASE( JSON2 )
{
  json j;
  BOOST_CHECK( j.empty() );
  BOOST_CHECK( j.is_null() );
  BOOST_CHECK( !j.is_object() );
}

BOOST_AUTO_TEST_CASE( JSON3 )
{
  json j = std::vector<int>{} ;
  BOOST_CHECK( j.empty() );
  BOOST_CHECK( !j.is_null() );
  BOOST_CHECK( j.is_array() );
  BOOST_CHECK( j.size() == 0 );
}

BOOST_AUTO_TEST_CASE( JSON4 )
{
  json j = "[]"_json ;
  BOOST_CHECK( j.empty() );
  BOOST_CHECK( !j.is_null() );
  BOOST_CHECK( j.is_array() );
  BOOST_CHECK( j.size() == 0 );
}

BOOST_AUTO_TEST_CASE( JSON5 )
{
  json j = R"foo(
{ "a": 10,
  "b": "bar"
}
)foo"_json ;

  json j2 = { { "a", 10 }, { "b", "bar" } } ;
  BOOST_CHECK( j == j2) ;
}

BOOST_AUTO_TEST_CASE( JSON6 )
{
  json j = R"foo(
{ "1": 10,
  "2": "bar"
}
)foo"_json ;

  BOOST_CHECK( j.is_object()) ;
}
<|endoftext|>


<commit_before>#include "Pythia8/Pythia.h"
#include "Pythia8Plugins/FastJet3.h"
#include <stdio.h>
#include <stdlib.h>

using namespace Pythia8;

void JetAnalysis( Event& event, const char* fname,
                  double R, double JpTMin, double etaMax, double TR, double TJpTMin ) {
  // Find leading pT jet in event with anti-kt algorithm (params R, JpTMin, etaMax).
  // Find subjets by re-cluster jet using kt algorith (params TR, TJpTMin).
  // Write jet properties, constituents to fname_jets.csv, fname_csts.csv.

  // Set up FastJet jet finder.
  fastjet::JetDefinition jetDef( fastjet::genkt_algorithm, R, -1 );
  std::vector <fastjet::PseudoJet> fjInputs;
  fjInputs.resize(0);

  // Begin FastJet analysis: extract particles from event record.
  Vec4 pTemp;
  for ( int i = 0; i < event.size(); ++i ) if ( event[i].isFinal() ) {
    // Require visible particles inside detector.
    if ( !event[i].isVisible() ) continue;
    if ( etaMax < 20. && abs(event[i].eta()) > etaMax ) continue;

    // Create a PseudoJet from the complete Pythia particle.
    fastjet::PseudoJet particleTemp = event[i];

    // Store acceptable particles as input to Fastjet.
    // Conversion to PseudoJet is performed automatically
    // with the help of the code in FastJet3.h.
    fjInputs.push_back( particleTemp );
  }

  // Run Fastjet algorithm and sort jets in pT order.
  vector <fastjet::PseudoJet> inclusiveJets, sortedJets;
  fastjet::ClusterSequence clustSeq( fjInputs, jetDef ); // Segmentation fault here sometimes.
  inclusiveJets = clustSeq.inclusive_jets( JpTMin );
  sortedJets    = sorted_by_pt(inclusiveJets);

  // Get details and constituents from leading jet.
  vector <fastjet::PseudoJet> Jconstits = sortedJets[0].constituents();
  double JpT  = sortedJets[0].perp();
  double Jeta = sortedJets[0].eta();
  double Jphi = sortedJets[0].phi_std();
  int Jsize   = Jconstits.size();

  // Open output files.
  char fjetsName[10+strlen(fname)];
  strcpy( fjetsName, fname );
  strcat( fjetsName, "_jets.csv" );
  FILE *f_jets = fopen(fjetsName, "w");
  char fcstsName[10+strlen(fname)];
  strcpy( fcstsName, fname );
  strcat( fcstsName, "_csts.csv" );
  FILE *f_csts = fopen(fcstsName, "w");

  // Output leading jet details.
  fprintf( f_jets, "%g, %g, %g, %i\n", JpT, Jeta, Jphi, Jsize );

  // Set up FastJet jet trimmer.
  fastjet::JetDefinition TjetDef( fastjet::genkt_algorithm, TR, 1 );
  std::vector <fastjet::PseudoJet> TfjInputs;
  TfjInputs.resize(0);
  for ( int i = 0; i < Jsize; ++i ) {
    // Store constituents from leading jet.
    TfjInputs.push_back( Jconstits[i] );
  }

  // Run Fastjet trimmer on leading jet.
  vector <fastjet::PseudoJet> TinclusiveJets, TsortedJets;
  fastjet::ClusterSequence TclustSeq( TfjInputs, TjetDef );
  TinclusiveJets = TclustSeq.inclusive_jets( JpT*TJpTMin );
  TsortedJets    = sorted_by_pt(TinclusiveJets);

  // Get details and constituents from subjets.
  for ( int j = 0; j < int( TsortedJets.size() ); ++j ) {
    Jconstits = TsortedJets[j].constituents();
    JpT       = TsortedJets[j].perp();
    Jeta      = TsortedJets[j].eta();
    Jphi      = TsortedJets[j].phi_std();
    Jsize     = Jconstits.size();
    // Output subjet details.
    fprintf( f_jets, "%g, %g, %g, %i\n", JpT, Jeta, Jphi, Jsize );
    for (int i = 0; i < Jsize; ++i) {
      double cE   = Jconstits[i].E();
      double cEt  = Jconstits[i].Et();
      double ceta = Jconstits[i].eta();
      double cphi = Jconstits[i].phi_std();
      // Output constituent details.
      fprintf( f_csts, "%g, %g, %g, %g\n", cE, cEt, ceta, cphi );
    }
    fprintf( f_csts, "\n" );
  }

  // Close output files.
  fclose( f_jets );
  fclose( f_csts );
}

int main() {
  // Generates W' events:
  // W' -> W Z; W -> q q', Z -> nu nu.
  // Performs jet analysis required to form jet images.
  // *** Need to specify location of Pythia xmldoc directory (xmldocDir)! ***

  // Main program settings.
  double eCM            = 14000.0;
  int nEvent            = 1;
  int nAbort            = 3;
  const char* xmldocDir = "/Users/barney800/Tools/Pythia8/share/Pythia8/xmldoc";
  // Parameters for FastJet analyses.
  double R          = 0.6;    // Jet size
  double JpTMin     = 12.5;   // Min jet pT
  double etaMax     = 5.0;    // Pseudorapidity range of detector
  double TR         = 0.3;    // Subjet size
  double TJpTMin    = 0.05;   // Min subjet pT (fraction of jet pT)
  const char* fname = "test"; // Filename for outputs.
  // Other parameters.
  double WpTMin  = 250.0;  // Min W pT
  double WpTMax  = 300.0;  // Max W pT

  // Generator. Shorthand for the event.
  Pythia pythia( xmldocDir );
  Event& event = pythia.event;

  // Use variable random seed: -1 = default, 0 = clock.
  pythia.settings.flag("Random:setSeed", "on");
  pythia.settings.mode("Random:seed", 0);

  // Set up beams: p p is default so only need set energy.
  pythia.settings.parm("Beams:eCM", eCM);

  // W' pair production.
  pythia.readString("NewGaugeBoson:ffbar2Wprime = on");
  pythia.readString("34:m0 = 700.0");

  // W' decays.
  pythia.readString("Wprime:coup2WZ = 1.0");
  pythia.readString("34:onMode = off");
  pythia.readString("34:onIfAny = 24");

  // W and Z decays.
  pythia.readString("24:onMode = off");
  pythia.readString("24:onIfAny = 1 2 3 4 5 6");
  pythia.readString("23:onMode = off");
  pythia.readString("23:onIfAny = 12 14 16");

  // Switch on/off particle data and event listings.
  pythia.readString("Init:showChangedSettings = off");
  pythia.readString("Init:showChangedParticleData = off");
  pythia.readString("Next:numberShowInfo = 1");
  pythia.readString("Next:numberShowProcess = 1");
  pythia.readString("Next:numberShowEvent = 0");

  // Initialize.
  pythia.init();

  // Begin event loop.
  int iAbort = 0;
  int iEvent = 0;
  while ( iEvent < nEvent ) {
    // Generate event. Quit if failure.
    if ( !pythia.next() ) {
      if ( ++iAbort < nAbort ) continue;
      cout << " Event generation aborted prematurely, owing to error.\n";
      break;
    }

    // Check W pT.
    int checkWpT = 0;
    for ( int i = 0; i < event.size(); ++i ) {
      if ( event[i].id() == 24 || event[i].id() == -24 ) {
        double WpT = event[i].pT();
        if ( WpT < WpTMin || WpT > WpTMax ) {
          break;
        }
        else {
          checkWpT = 1;
          break;
        }
      }
    }
    if ( checkWpT == 0 ) continue;
    ++iEvent;

    // Perform jet analysis.
    JetAnalysis( event, fname, R, JpTMin, etaMax, TR, TJpTMin );

    // End of event loop.
  }

  // Done.
  return 0;
}
<commit_msg>rm old WprimeJetGen.cc<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/cros/update_library.h"

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/observer_list.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "content/browser/browser_thread.h"

namespace chromeos {

class UpdateLibraryImpl : public UpdateLibrary {
 public:
  UpdateLibraryImpl() : status_connection_(NULL) {}

  virtual ~UpdateLibraryImpl() {
    if (status_connection_) {
      chromeos::DisconnectUpdateProgress(status_connection_);
      status_connection_ = NULL;
    }
  }

  // Begin UpdateLibrary implementation.
  virtual void Init() OVERRIDE {
    DCHECK(CrosLibrary::Get()->libcros_loaded());
    CHECK(!status_connection_) << "Already initialized";
    status_connection_ =
        chromeos::MonitorUpdateStatus(&UpdateStatusHandler, this);
    // Asynchronously load the initial state.
    chromeos::RequestUpdateStatus(&UpdateStatusHandler, this);
  }

  virtual void AddObserver(Observer* observer) OVERRIDE {
    observers_.AddObserver(observer);
  }

  virtual void RemoveObserver(Observer* observer) OVERRIDE {
    observers_.RemoveObserver(observer);
  }

  virtual bool HasObserver(Observer* observer) OVERRIDE {
    return observers_.HasObserver(observer);
  }

  virtual void RequestUpdateCheck(chromeos::UpdateCallback callback,
                                  void* user_data) OVERRIDE {
    chromeos::RequestUpdateCheck(callback, user_data);
  }

  virtual void RebootAfterUpdate() OVERRIDE {
    chromeos::RebootIfUpdated();
  }

  virtual void SetReleaseTrack(const std::string& track) OVERRIDE {
    chromeos::SetUpdateTrack(track);
  }

  virtual void GetReleaseTrack(chromeos::UpdateTrackCallback callback,
                               void* user_data) OVERRIDE {
    chromeos::RequestUpdateTrack(callback, user_data);
  }
  // End UpdateLibrary implementation.

  const UpdateLibrary::Status& status() OVERRIDE const{
    return status_;
  }

 private:
  static void UpdateStatusHandler(void* object, const UpdateProgress& status) {
    UpdateLibraryImpl* impl = static_cast<UpdateLibraryImpl*>(object);
    impl->UpdateStatus(Status(status));
  }

  void UpdateStatus(const Status& status) {
    // Called from UpdateStatusHandler, a libcros callback which should
    // always run on UI thread.
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

    status_ = status;
    FOR_EACH_OBSERVER(Observer, observers_, UpdateStatusChanged(status));
  }

  ObserverList<Observer> observers_;

  // A reference to the update api, to allow callbacks when the update
  // status changes.
  UpdateStatusConnection status_connection_;

  // The latest power status.
  Status status_;

  DISALLOW_COPY_AND_ASSIGN(UpdateLibraryImpl);
};

class UpdateLibraryStubImpl : public UpdateLibrary {
 public:
  UpdateLibraryStubImpl() {}
  virtual ~UpdateLibraryStubImpl() {}

  // Begin UpdateLibrary implementation.
  virtual void Init() OVERRIDE {}
  virtual void AddObserver(Observer* observer) OVERRIDE {}
  virtual void RemoveObserver(Observer* observer) OVERRIDE {}
  virtual bool HasObserver(Observer* observer) OVERRIDE { return false; }
  virtual void RequestUpdateCheck(chromeos::UpdateCallback callback,
                                  void* user_data) OVERRIDE {
    if (callback)
      callback(user_data, UPDATE_RESULT_FAILED, "stub update");
  }
  virtual void RebootAfterUpdate() OVERRIDE {}
  virtual void SetReleaseTrack(const std::string& track) OVERRIDE {}
  virtual void GetReleaseTrack(chromeos::UpdateTrackCallback callback,
                               void* user_data) OVERRIDE {
    if (callback)
      callback(user_data, "beta-channel");
  }
  // End UpdateLibrary implementation.

  const UpdateLibrary::Status& status() OVERRIDE const {
    return status_;
  }

 private:
  Status status_;

  DISALLOW_COPY_AND_ASSIGN(UpdateLibraryStubImpl);
};

// static
UpdateLibrary* UpdateLibrary::GetImpl(bool stub) {
  UpdateLibrary* impl;
  if (stub)
    impl = new UpdateLibraryStubImpl();
  else
    impl = new UpdateLibraryImpl();
  impl->Init();
  return impl;
}

}  // namespace chromeos
<commit_msg>chromeos: Fix build error on linux_chromeos_clang.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/cros/update_library.h"

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/observer_list.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "content/browser/browser_thread.h"

namespace chromeos {

class UpdateLibraryImpl : public UpdateLibrary {
 public:
  UpdateLibraryImpl() : status_connection_(NULL) {}

  virtual ~UpdateLibraryImpl() {
    if (status_connection_) {
      chromeos::DisconnectUpdateProgress(status_connection_);
      status_connection_ = NULL;
    }
  }

  // Begin UpdateLibrary implementation.
  virtual void Init() OVERRIDE {
    DCHECK(CrosLibrary::Get()->libcros_loaded());
    CHECK(!status_connection_) << "Already initialized";
    status_connection_ =
        chromeos::MonitorUpdateStatus(&UpdateStatusHandler, this);
    // Asynchronously load the initial state.
    chromeos::RequestUpdateStatus(&UpdateStatusHandler, this);
  }

  virtual void AddObserver(Observer* observer) OVERRIDE {
    observers_.AddObserver(observer);
  }

  virtual void RemoveObserver(Observer* observer) OVERRIDE {
    observers_.RemoveObserver(observer);
  }

  virtual bool HasObserver(Observer* observer) OVERRIDE {
    return observers_.HasObserver(observer);
  }

  virtual void RequestUpdateCheck(chromeos::UpdateCallback callback,
                                  void* user_data) OVERRIDE {
    chromeos::RequestUpdateCheck(callback, user_data);
  }

  virtual void RebootAfterUpdate() OVERRIDE {
    chromeos::RebootIfUpdated();
  }

  virtual void SetReleaseTrack(const std::string& track) OVERRIDE {
    chromeos::SetUpdateTrack(track);
  }

  virtual void GetReleaseTrack(chromeos::UpdateTrackCallback callback,
                               void* user_data) OVERRIDE {
    chromeos::RequestUpdateTrack(callback, user_data);
  }
  // End UpdateLibrary implementation.

  virtual const UpdateLibrary::Status& status() const OVERRIDE{
    return status_;
  }

 private:
  static void UpdateStatusHandler(void* object, const UpdateProgress& status) {
    UpdateLibraryImpl* impl = static_cast<UpdateLibraryImpl*>(object);
    impl->UpdateStatus(Status(status));
  }

  void UpdateStatus(const Status& status) {
    // Called from UpdateStatusHandler, a libcros callback which should
    // always run on UI thread.
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

    status_ = status;
    FOR_EACH_OBSERVER(Observer, observers_, UpdateStatusChanged(status));
  }

  ObserverList<Observer> observers_;

  // A reference to the update api, to allow callbacks when the update
  // status changes.
  UpdateStatusConnection status_connection_;

  // The latest power status.
  Status status_;

  DISALLOW_COPY_AND_ASSIGN(UpdateLibraryImpl);
};

class UpdateLibraryStubImpl : public UpdateLibrary {
 public:
  UpdateLibraryStubImpl() {}
  virtual ~UpdateLibraryStubImpl() {}

  // Begin UpdateLibrary implementation.
  virtual void Init() OVERRIDE {}
  virtual void AddObserver(Observer* observer) OVERRIDE {}
  virtual void RemoveObserver(Observer* observer) OVERRIDE {}
  virtual bool HasObserver(Observer* observer) OVERRIDE { return false; }
  virtual void RequestUpdateCheck(chromeos::UpdateCallback callback,
                                  void* user_data) OVERRIDE {
    if (callback)
      callback(user_data, UPDATE_RESULT_FAILED, "stub update");
  }
  virtual void RebootAfterUpdate() OVERRIDE {}
  virtual void SetReleaseTrack(const std::string& track) OVERRIDE {}
  virtual void GetReleaseTrack(chromeos::UpdateTrackCallback callback,
                               void* user_data) OVERRIDE {
    if (callback)
      callback(user_data, "beta-channel");
  }
  // End UpdateLibrary implementation.

  virtual const UpdateLibrary::Status& status() const OVERRIDE {
    return status_;
  }

 private:
  Status status_;

  DISALLOW_COPY_AND_ASSIGN(UpdateLibraryStubImpl);
};

// static
UpdateLibrary* UpdateLibrary::GetImpl(bool stub) {
  UpdateLibrary* impl;
  if (stub)
    impl = new UpdateLibraryStubImpl();
  else
    impl = new UpdateLibraryImpl();
  impl->Init();
  return impl;
}

}  // namespace chromeos
<|endoftext|>


<commit_before>/*
**
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2011 Aldebaran Robotics
*/

#include <qimessaging/signature.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

static int _qi_signature_find_end(qi_signature_t *sig, char **pcurrent, const char **psignature, char copen, char close)
{
  int         opencount  = 1;
  int         closecount = 0;
  char       *current    = *pcurrent;
  const char *signature  = *psignature;

  *current = *signature;
  signature++;
  current++;
  while ((*signature != 0) && (opencount != closecount))
  {
    if (*signature == copen)
      opencount++;
    if (*signature == close)
      closecount++;
    *current = *signature;
    signature++;
    current++;
  }
  *pcurrent   = current;
  *psignature = signature;
}

// go forward, add a 0, go forward, add a 0, bouhhh a 1! AHHHHHH scary!
static int _qi_signature_split(qi_signature_t *sig, const char *signature, const char *end)
{
  char *current = sig->_signature;
  int   i       = 0;

  while(*signature) {
    if (end && signature >= end)
      break;
    //verify that the current signature is correct
    switch(*signature) {
    case QI_VOID   :
    case QI_BOOL   :
    case QI_CHAR   :
    case QI_INT    :
    case QI_FLOAT  :
    case QI_DOUBLE :
    case QI_STRING :
    case QI_MESSAGE:
    //case QI_POINTER:
      *current = *signature;
      current++;
      signature++;
      break;
    case QI_LIST   :
      _qi_signature_find_end(sig, &current, &signature, QI_LIST, QI_LIST_END);
      break;
    case QI_MAP    :
      _qi_signature_find_end(sig, &current, &signature, QI_MAP, QI_MAP_END);
      break;
    case QI_TUPPLE :
      _qi_signature_find_end(sig, &current, &signature, QI_TUPPLE, QI_TUPPLE_END);
      break;
    default:
      return 2;
    }

    if (*signature == QI_POINTER) {
      *current = *signature;
      current++;
      signature++;
    }

    *current = 0;
    current++;
  }
  sig->_end = current - 1;
  return 0;
}

//return 0 on success
//qi_signature_t *qi_signature_create(const char *signature)
qi_signature_t *qi_signature_create(const char *signature)
{
  int             size;
  qi_signature_t *sig;

  if (!signature)
    return 0;

  size = strlen(signature) * 2;
  sig  = new qi_signature_t();

  sig->_signature               = (char *)malloc(size);
  sig->current                  = 0;
  sig->_end                     = sig->_signature + size;
  sig->_status                  = _qi_signature_split(sig, signature, 0);
  return sig;
}

qi_signature_t *qi_signature_create_subsignature(const char *signature)
{
  int             size;
  qi_signature_t *sig;

  if (!signature)
    return 0;
  size = strlen(signature);
  if (size < 3)
    return 0;
  sig  = new qi_signature_t();

  if (signature[size - 1] == QI_POINTER)
    size--;
  size -= 2;

  sig->_signature               = (char *)malloc(size);
  sig->current                  = 0;
  sig->_end                     = sig->_signature + size;
  sig->_status                  = _qi_signature_split(sig, signature + 1, signature + 1 + size);
  return sig;
}

void qi_signature_destroy(qi_signature_t *sig)
{
  if (!sig)
    return;
  free(sig->_signature);
  delete sig;
}

int qi_signature_is_pointer(const qi_signature_t *sig)
{
  if (sig && sig->current && sig->_status != 2 && sig->current != sig->_end)
    return sig->current[strlen(sig->current) - 1] == QI_POINTER;
  return 0;
}

//return
// 0 on success
// 1 on EOL
// 2 on error
int qi_signature_next(qi_signature_t *sig) {
  if (!sig)
    return 2;

  if (sig->_status == 2)
    return 2;

  if (sig->current >= sig->_end)
    return 1;

  if (sig->_status == 0) {
    sig->current = sig->_signature;
    sig->_status = 1;
    return 0;
  }

  sig->current += strlen(sig->current) + 1;
  if (sig->current >= sig->_end)
  {
    sig->current = sig->_end;
    return 1;
  }
  return 0;
}

//return the number of first level element in the signature
int qi_signature_count(qi_signature_t *sig)
{
  char *it;
  int   count = 0;

  if (!sig || !sig->_signature)
    return -1;

  it = sig->_signature;
  while(it <= sig->_end) {
    if (*it == 0)
      count++;
    ++it;
  }
  return count;
}

// copy the name to buffer
// return the size copied
// -1 on error
int qi_signature_get_name(const char *complete_sig, char *buffer, int size) {
  const char *ret;
  int   len;
  ret = strstr(complete_sig, "::");

  if (!ret) {
    buffer[0] = 0;
    return 0;
  }

  len = ret - complete_sig;
  if (len > size)
    return -1;

  strncpy(buffer, complete_sig, len + 1);
  buffer[len] = 0;
  return len;
}

// copy the name to buffer
// return the size copied
// -1 on error
int qi_signature_get_return(const char *complete_sig, char *buffer, int size) {
  const char *start, *ret;
  int   len;
  start = strstr(complete_sig, (const char *)"::");

  if (!start)
    start = complete_sig;
  else
    start += 2;

  ret = strstr(start, ":");
  if (!ret) {
    buffer[0] = 0;
    return 0;
  }
  len = ret - start;
  if (len > size)
    return -1;

  strncpy(buffer, start, len);
  buffer[len] = 0;
  return len;
}

// copy the name to buffer
// return the size copied
// -1 on error
int qi_signature_get_params(const char *complete_sig, char *buffer, int size) {
  const char *start, *ret;
  int   len;
  start = strstr(complete_sig, "::");

  if (!start)
    start = complete_sig;
  else
    start += 2;

  ret = strstr(start, ":");
  if (!ret)
    ret = start;
  else
    ret += 1;
  len = strlen(ret);
  if (len > size)
    return -1;

  strncpy(buffer, ret, len + 1);
  buffer[len] = 0;
  return len;
}

<commit_msg>An int method should return something<commit_after>/*
**
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2011 Aldebaran Robotics
*/

#include <qimessaging/signature.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

static int _qi_signature_find_end(qi_signature_t *sig, char **pcurrent, const char **psignature, char copen, char close)
{
  int         opencount  = 1;
  int         closecount = 0;
  char       *current    = *pcurrent;
  const char *signature  = *psignature;

  *current = *signature;
  signature++;
  current++;
  while ((*signature != 0) && (opencount != closecount))
  {
    if (*signature == copen)
      opencount++;
    if (*signature == close)
      closecount++;
    *current = *signature;
    signature++;
    current++;
  }
  *pcurrent   = current;
  *psignature = signature;

  return 0;
}

// go forward, add a 0, go forward, add a 0, bouhhh a 1! AHHHHHH scary!
static int _qi_signature_split(qi_signature_t *sig, const char *signature, const char *end)
{
  char *current = sig->_signature;
  int   i       = 0;

  while(*signature) {
    if (end && signature >= end)
      break;
    //verify that the current signature is correct
    switch(*signature) {
    case QI_VOID   :
    case QI_BOOL   :
    case QI_CHAR   :
    case QI_INT    :
    case QI_FLOAT  :
    case QI_DOUBLE :
    case QI_STRING :
    case QI_MESSAGE:
    //case QI_POINTER:
      *current = *signature;
      current++;
      signature++;
      break;
    case QI_LIST   :
      _qi_signature_find_end(sig, &current, &signature, QI_LIST, QI_LIST_END);
      break;
    case QI_MAP    :
      _qi_signature_find_end(sig, &current, &signature, QI_MAP, QI_MAP_END);
      break;
    case QI_TUPPLE :
      _qi_signature_find_end(sig, &current, &signature, QI_TUPPLE, QI_TUPPLE_END);
      break;
    default:
      return 2;
    }

    if (*signature == QI_POINTER) {
      *current = *signature;
      current++;
      signature++;
    }

    *current = 0;
    current++;
  }
  sig->_end = current - 1;
  return 0;
}

//return 0 on success
//qi_signature_t *qi_signature_create(const char *signature)
qi_signature_t *qi_signature_create(const char *signature)
{
  int             size;
  qi_signature_t *sig;

  if (!signature)
    return 0;

  size = strlen(signature) * 2;
  sig  = new qi_signature_t();

  sig->_signature               = (char *)malloc(size);
  sig->current                  = 0;
  sig->_end                     = sig->_signature + size;
  sig->_status                  = _qi_signature_split(sig, signature, 0);
  return sig;
}

qi_signature_t *qi_signature_create_subsignature(const char *signature)
{
  int             size;
  qi_signature_t *sig;

  if (!signature)
    return 0;
  size = strlen(signature);
  if (size < 3)
    return 0;
  sig  = new qi_signature_t();

  if (signature[size - 1] == QI_POINTER)
    size--;
  size -= 2;

  sig->_signature               = (char *)malloc(size);
  sig->current                  = 0;
  sig->_end                     = sig->_signature + size;
  sig->_status                  = _qi_signature_split(sig, signature + 1, signature + 1 + size);
  return sig;
}

void qi_signature_destroy(qi_signature_t *sig)
{
  if (!sig)
    return;
  free(sig->_signature);
  delete sig;
}

int qi_signature_is_pointer(const qi_signature_t *sig)
{
  if (sig && sig->current && sig->_status != 2 && sig->current != sig->_end)
    return sig->current[strlen(sig->current) - 1] == QI_POINTER;
  return 0;
}

//return
// 0 on success
// 1 on EOL
// 2 on error
int qi_signature_next(qi_signature_t *sig) {
  if (!sig)
    return 2;

  if (sig->_status == 2)
    return 2;

  if (sig->current >= sig->_end)
    return 1;

  if (sig->_status == 0) {
    sig->current = sig->_signature;
    sig->_status = 1;
    return 0;
  }

  sig->current += strlen(sig->current) + 1;
  if (sig->current >= sig->_end)
  {
    sig->current = sig->_end;
    return 1;
  }
  return 0;
}

//return the number of first level element in the signature
int qi_signature_count(qi_signature_t *sig)
{
  char *it;
  int   count = 0;

  if (!sig || !sig->_signature)
    return -1;

  it = sig->_signature;
  while(it <= sig->_end) {
    if (*it == 0)
      count++;
    ++it;
  }
  return count;
}

// copy the name to buffer
// return the size copied
// -1 on error
int qi_signature_get_name(const char *complete_sig, char *buffer, int size) {
  const char *ret;
  int   len;
  ret = strstr(complete_sig, "::");

  if (!ret) {
    buffer[0] = 0;
    return 0;
  }

  len = ret - complete_sig;
  if (len > size)
    return -1;

  strncpy(buffer, complete_sig, len + 1);
  buffer[len] = 0;
  return len;
}

// copy the name to buffer
// return the size copied
// -1 on error
int qi_signature_get_return(const char *complete_sig, char *buffer, int size) {
  const char *start, *ret;
  int   len;
  start = strstr(complete_sig, (const char *)"::");

  if (!start)
    start = complete_sig;
  else
    start += 2;

  ret = strstr(start, ":");
  if (!ret) {
    buffer[0] = 0;
    return 0;
  }
  len = ret - start;
  if (len > size)
    return -1;

  strncpy(buffer, start, len);
  buffer[len] = 0;
  return len;
}

// copy the name to buffer
// return the size copied
// -1 on error
int qi_signature_get_params(const char *complete_sig, char *buffer, int size) {
  const char *start, *ret;
  int   len;
  start = strstr(complete_sig, "::");

  if (!start)
    start = complete_sig;
  else
    start += 2;

  ret = strstr(start, ":");
  if (!ret)
    ret = start;
  else
    ret += 1;
  len = strlen(ret);
  if (len > size)
    return -1;

  strncpy(buffer, ret, len + 1);
  buffer[len] = 0;
  return len;
}

<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/gtk/view_id_util.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"

class ViewIDTest : public InProcessBrowserTest {
 public:
  ViewIDTest() : root_window_(NULL) {}

  void CheckViewID(ViewID id, bool should_have) {
    if (!root_window_)
      root_window_ = GTK_WIDGET(browser()->window()->GetNativeHandle());

    ASSERT_TRUE(root_window_);
    EXPECT_EQ(should_have, !!ViewIDUtil::GetWidget(root_window_, id));
  }

 private:
  GtkWidget* root_window_;
};

IN_PROC_BROWSER_TEST_F(ViewIDTest, DISABLED_Basic) {
  for (int i = VIEW_ID_TOOLBAR; i < VIEW_ID_PREDEFINED_COUNT; ++i) {
    // http://crbug.com/21152
    if (i == VIEW_ID_BOOKMARK_MENU)
      continue;

    // Extension shelf is being removed, http://crbug.com/25106.
    if (i == VIEW_ID_DEV_EXTENSION_SHELF)
      continue;

    CheckViewID(static_cast<ViewID>(i), true);
  }

  CheckViewID(VIEW_ID_PREDEFINED_COUNT, false);
}

IN_PROC_BROWSER_TEST_F(ViewIDTest, Delegate) {
  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, false);

  browser()->OpenURL(GURL(chrome::kAboutBlankURL), GURL(),
                     NEW_BACKGROUND_TAB, PageTransition::TYPED);

  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, true);
}
<commit_msg>ViewIDTest.Basic fix  FindBar has to be created before the test.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/gtk/view_id_util.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"

class ViewIDTest : public InProcessBrowserTest {
 public:
  ViewIDTest() : root_window_(NULL) {}

  void CheckViewID(ViewID id, bool should_have) {
    if (!root_window_)
      root_window_ = GTK_WIDGET(browser()->window()->GetNativeHandle());

    ASSERT_TRUE(root_window_);
    EXPECT_EQ(should_have, !!ViewIDUtil::GetWidget(root_window_, id))
        << " Failed id=" << id;
  }

 private:
  GtkWidget* root_window_;
};

IN_PROC_BROWSER_TEST_F(ViewIDTest, Basic) {
  // Make sure FindBar is created to test
  // VIEW_ID_FIND_IN_PAGE_TEXT_FIELD and VIEW_ID_FIND_IN_PAGE.
  browser()->ShowFindBar();

  for (int i = VIEW_ID_TOOLBAR; i < VIEW_ID_PREDEFINED_COUNT; ++i) {
    // http://crbug.com/21152
    if (i == VIEW_ID_BOOKMARK_MENU)
      continue;

    // Extension shelf is being removed, http://crbug.com/25106.
    if (i == VIEW_ID_DEV_EXTENSION_SHELF)
      continue;

    CheckViewID(static_cast<ViewID>(i), true);
  }

  CheckViewID(VIEW_ID_PREDEFINED_COUNT, false);
}

IN_PROC_BROWSER_TEST_F(ViewIDTest, Delegate) {
  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, false);

  browser()->OpenURL(GURL(chrome::kAboutBlankURL), GURL(),
                     NEW_BACKGROUND_TAB, PageTransition::TYPED);

  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, true);
}
<|endoftext|>