<commit_before>// Copyright (c) Google LLC 2019
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

#include "./ans_encode.h"

#include <vector>

#include <brunsli/types.h>
#include "./histogram_encode.h"
#include "./write_bits.h"

namespace brunsli {

namespace {

void ANSBuildInfoTable(const int* counts, int alphabet_size,
                       ANSEncSymbolInfo info[BRUNSLI_ANS_MAX_SYMBOLS]) {
  int total = 0;
  for (int s = 0; s < alphabet_size; ++s) {
    const uint32_t freq = counts[s];
    info[s].freq_ = counts[s];
    info[s].start_ = total;
    total += freq;
#ifdef USE_MULT_BY_RECIPROCAL
    if (freq != 0) {
      info[s].ifreq_ =
          ((1ull << RECIPROCAL_PRECISION) + info[s].freq_ - 1) / info[s].freq_;
    } else {
      // Shouldn't matter for valid streams (symbol shouldn't occur).
      // Initialization allows to avoid undefined behavior on corrupted streams.
      info[s].ifreq_ = 1;
    }
#endif
  }
}

}  // namespace

void BuildAndStoreANSEncodingData(const int* histogram, ANSTable* table,
                                  Storage* storage) {
  int num_symbols;
  int symbols[kMaxNumSymbolsForSmallCode] = {0};
  std::vector<int> counts(histogram, histogram + BRUNSLI_ANS_MAX_SYMBOLS);
  int omit_pos;
  NormalizeCounts(&counts[0], &omit_pos, BRUNSLI_ANS_MAX_SYMBOLS,
                  BRUNSLI_ANS_LOG_TAB_SIZE, &num_symbols, symbols);
  ANSBuildInfoTable(&counts[0], BRUNSLI_ANS_MAX_SYMBOLS, table->info_);
  EncodeCounts(&counts[0], omit_pos, num_symbols, symbols, storage);
}

}  // namespace brunsli
<commit_msg>Internal change<commit_after>// Copyright (c) Google LLC 2019
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

#include "./ans_encode.h"

#include <vector>

#include <brunsli/types.h>
#include "./histogram_encode.h"
#include "./write_bits.h"

namespace brunsli {

namespace {

void ANSBuildInfoTable(const int* counts, int alphabet_size,
                       ANSEncSymbolInfo info[BRUNSLI_ANS_MAX_SYMBOLS]) {
  int total = 0;
  for (int s = 0; s < alphabet_size; ++s) {
    const uint32_t freq = counts[s];
    info[s].freq_ = counts[s];
    info[s].start_ = total;
    total += freq;
#ifdef USE_MULT_BY_RECIPROCAL
    if (freq != 0) {
      info[s].ifreq_ =
          ((1ull << RECIPROCAL_PRECISION) + info[s].freq_ - 1) / info[s].freq_;
    } else {
      // Shouldn't matter for valid streams (symbol shouldn't occur).
      // Initialization allows to avoid undefined behavior on corrupted streams.
      info[s].ifreq_ = 1;
    }
#endif
  }
}

}  // namespace

void BuildAndStoreANSEncodingData(const int* histogram, ANSTable* table,
                                  Storage* storage) {
  int num_symbols;
  int symbols[kMaxNumSymbolsForSmallCode] = {0};
  std::vector<int> counts(histogram, histogram + BRUNSLI_ANS_MAX_SYMBOLS);
  int omit_pos = 0;  // Initialization is not necessary, but makes MSAN happy.
  NormalizeCounts(&counts[0], &omit_pos, BRUNSLI_ANS_MAX_SYMBOLS,
                  BRUNSLI_ANS_LOG_TAB_SIZE, &num_symbols, symbols);
  ANSBuildInfoTable(&counts[0], BRUNSLI_ANS_MAX_SYMBOLS, table->info_);
  EncodeCounts(&counts[0], omit_pos, num_symbols, symbols, storage);
}

}  // namespace brunsli
<|endoftext|>


<commit_before>/** @file gsFunctionExpr.hpp

    @brief Provides implementation of FunctionExpr class.

    This file is part of the G+Smo library.

    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this
    file, You can obtain one at http://mozilla.org/MPL/2.0/.

    Author(s): A. Mantzaflaris
*/

#pragma once

#include <gsCore/gsLinearAlgebra.h>

#include <exprtk.hpp>// External file

namespace gismo
{

template<typename T> class gsFunctionExprPrivate
{
public:
    T vars[6];
    exprtk::symbol_table<T> symbol_table;
    exprtk::expression<T> expression;
    exprtk::expression<T> der_exp[6];
    bool der_flag[6];
    std::string  string;
    int dim;
};

/* / /AM: under construction
template<typename T> class gsSymbolListPrivate
{
public:
    exprtk::symbol_table<T> symbol_table;
    std::vector<T> vars  ;
    std::vector<T> params;
};

template<typename T>
gsSymbolList<T>::gsSymbolList() : my(new gsSymbolListPrivate<T>) {}

template<typename T>
gsSymbolList<T>::~gsSymbolList()
{
delete my;
}

template<typename T>
void gsSymbolList<T>::setDefault()
{
    my->symbol_table.clear();

    // Identify symbol table
    my->symbol_table.add_variable("x",my->vars[0]);
    my->symbol_table.add_variable("y",my->vars[1]);
    my->symbol_table.add_variable("z",my->vars[2]);
    my->symbol_table.add_variable("w",my->vars[3]);
    my->symbol_table.add_variable("u",my->vars[4]);
    my->symbol_table.add_variable("v",my->vars[5]);
    //my->symbol_table.remove_variable("w",my->vars[3]);
    my->symbol_table.add_pi();
    //my->symbol_table.add_constant("C", 1);
}

template<typename T>
bool gsSymbolList<T>::addConstant(const std::string & constant_name, const T& value)
{
return my->symbol_table.add_constant(constant_name, value);
}

template<typename T>
bool gsSymbolList<T>::addVariable(const std::string & variable_name)
{
    my->vars.push_back(0.0);
    return my->symbol_table.add_variable(variable_name, my->vars.back() );
}

template<typename T>
bool gsSymbolList<T>::addParameter(const std::string & variable_name)
{
    my->params.push_back(0.0);
    return my->symbol_table.add_variable(variable_name, my->params.back() );
}

template<typename T>
bool gsSymbolList<T>::hasSymbol(const std::string& symbol_name)
{
return true;
}
//*/

template<typename T>
gsFunctionExpr<T>::gsFunctionExpr() : my(new gsFunctionExprPrivate<T>) {}

template<typename T>
gsFunctionExpr<T>::gsFunctionExpr(const std::string & expression_string, int ddim)
: my(new gsFunctionExprPrivate<T>)
{
    // Keep string data
    my->string = expression_string;
    my->string.erase(std::remove(my->string.begin(),my->string.end(),' '),my->string.end());
    stringReplace(my->string, "**", "^");
    my->dim = ddim;
    init();
}

template<typename T>
gsFunctionExpr<T>::gsFunctionExpr(const gsFunctionExpr& other)
{
    my = new gsFunctionExprPrivate<T>;
    my->string = other.my->string;
    my->dim = other.my->dim;
    init();
}

template<typename T>
gsFunctionExpr<T>& gsFunctionExpr<T>::operator=(const gsFunctionExpr& other)
{
    if (this != &other)
    {
        my->string = other.my->string;
        my->dim = other.my->dim;
        init();
    }
    return *this;
}

template<typename T>
gsFunctionExpr<T>::~gsFunctionExpr()
{
    delete my;
}

// template<typename T>
// void gsFunctionExpr<T>::init(variables,constants)

template<typename T>
void gsFunctionExpr<T>::init()
{
    my->symbol_table.clear();
    my->expression.release();

    // Identify symbol table
    my->symbol_table.add_variable("x",my->vars[0]);
    my->symbol_table.add_variable("y",my->vars[1]);
    my->symbol_table.add_variable("z",my->vars[2]);
    my->symbol_table.add_variable("w",my->vars[3]);
    my->symbol_table.add_variable("u",my->vars[4]);
    my->symbol_table.add_variable("v",my->vars[5]);
    //my->symbol_table.remove_variable("w",my->vars[3]);
    my->symbol_table.add_pi();
    //my->symbol_table.add_constant("C", 1);
    my->expression.register_symbol_table(my->symbol_table);

    exprtk::parser<T> parser;
    //parser.cache_symbols() = true;
    bool success = parser.compile(my->string, my->expression);
    if ( ! success )
        std::cout<<"gsFunctionExpr error: " <<parser.error() <<std::endl;

/*
    AM: Changed in recent versions.
    std::vector<std::string> varlist;
    parser.expression_symbols(varlist);
    varlist.erase(std::remove(varlist.begin(), varlist.end(), "pi"), varlist.end());
    my->dim = varlist.size();
*/

    my->der_flag[0]=false;
    my->der_flag[1]=false;
    my->der_flag[2]=false;
    my->der_flag[3]=false;
    my->der_flag[4]=false;
    my->der_flag[5]=false;
}

template<typename T>
int gsFunctionExpr<T>::domainDim() const
{
    return my->dim;
}

template<typename T>
void gsFunctionExpr<T>::set_x (T const & v) const { my->vars[0]= v; }

template<typename T>
void gsFunctionExpr<T>::set_y (T const & v) const { my->vars[1]= v; }

template<typename T>
void gsFunctionExpr<T>::set_z (T const & v) const { my->vars[2]= v; }

template<typename T>
void gsFunctionExpr<T>::set_w (T const & v) const { my->vars[3]= v; }

template<typename T>
void gsFunctionExpr<T>::set_u (T const & v) const { my->vars[4]= v; }

template<typename T>
void gsFunctionExpr<T>::set_v (T const & v) const { my->vars[5]= v; }

template<typename T>
void gsFunctionExpr<T>::set_x_der (std::string expression_string)
{
    my->der_exp[0].register_symbol_table(my->symbol_table);
    exprtk::parser<T> parser;
    bool success = parser.compile(expression_string, my->der_exp[0] );
    if ( ! success )
        std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl;
    else
        my->der_flag[0]=true;
}

template<typename T>
void gsFunctionExpr<T>::set_y_der (std::string expression_string)
{
    my->der_exp[1].register_symbol_table(my->symbol_table);
    exprtk::parser<T> parser;
    bool success = parser.compile(expression_string, my->der_exp[1] );
    if ( ! success )
        std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl;
    else
        my->der_flag[1]=true;
}

template<typename T>
void gsFunctionExpr<T>::eval_into(const gsMatrix<T>& u, gsMatrix<T>& result) const
{
    GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );

    result.resize(1, u.cols());
    for ( int i = 0; i<u.cols(); i++ )
    {
        for ( int j = 0; j<u.rows(); j++ )
        {
            my->vars[j] =u(j,i);
        }
        result(0,i) = my->expression.value();
    }
}

template<typename T>
void gsFunctionExpr<T>::eval_component_into(const gsMatrix<T>& u, const index_t comp, gsMatrix<T>& result) const
{
    GISMO_ASSERT (comp == 0, "Given component number is too high. Only one component");
    result.resize(1, u.cols());
    for ( int i = 0; i<u.cols(); i++ )
    {
        for ( int j = 0; j<u.rows(); j++ )
        {
            my->vars[j] =u(j,i);
        }
        result(0,i) = my->expression.value();
    }
}

template<typename T>
void gsFunctionExpr<T>::deriv_into(const gsMatrix<T>& u, gsMatrix<T>& result) const
{
    int n = u.rows();
    GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );

    result.resize(1, n * u.cols());

    for( int i=0; i < u.cols(); ++i )
    {
        for ( int j = 0; j<n; j++ )
            my->vars[j] =u(j,i);
        for( int j=0; j< n; ++j )
            if ( my->der_flag[j] )
                result(n*i+j) = my->der_exp[j].value();
            else
                result(n*i+j) = exprtk::derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
    }
}

template<typename T>
typename gsFunction<T>::uMatrixPtr
gsFunctionExpr<T>::hess(const gsMatrix<T>& u, unsigned coord) const
{
    GISMO_ENSURE(coord == 0, "Error, function is real");
    // one column only..
    int n = u.rows();
    GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );

    gsMatrix<T> * res= new gsMatrix<T>(n,n) ;

    for ( int j = 0; j<n; j++ )
        my->vars[j] =u(j,0);
    for( int j=0; j< n; ++j )
    {
        (*res)(j,j) = exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
        for( int k=0; k<j; ++k )
            (*res)(k,j) = (*res)(j,k) =
                exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ;
    }
    return typename gsFunction<T>::uMatrixPtr(res);
} ;
template<typename T>
gsMatrix<T> * gsFunctionExpr<T>::mderiv(const gsMatrix<T>& u, const index_t &k, const index_t &j ) const
{
    gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ;

    for( index_t i=0; i< res->cols(); ++i )
    {
      	for ( int t = 0; t<u.rows(); t++ )
            my->vars[t] =u(t,i);
        (*res)(0,i) =
            exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ;
    }
    return  res;
} ;

template<typename T>
gsMatrix<T> * gsFunctionExpr<T>::laplacian(const gsMatrix<T>& u) const
{
    gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ;
    res->setZero();
    int n = u.rows();

    for( index_t i=0; i< res->cols(); ++i )
        for ( int j = 0; j<n; j++ )
        {
            my->vars[j] =u(j,i);
            (*res)(0,i) +=
                exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
        }
    return  res;
}

template<typename T>
T gsFunctionExpr<T>::value() const
{
    return my->expression.value() ;
}

template<typename T>
std::ostream & gsFunctionExpr<T>::print(std::ostream &os) const
{ os << my->string ; return os; }

}; // namespace gismo
<commit_msg>another fix for the format change in format<commit_after>/** @file gsFunctionExpr.hpp

    @brief Provides implementation of FunctionExpr class.

    This file is part of the G+Smo library.

    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this
    file, You can obtain one at http://mozilla.org/MPL/2.0/.

    Author(s): A. Mantzaflaris
*/

#pragma once

#include <gsCore/gsLinearAlgebra.h>

#include <exprtk.hpp>// External file

namespace gismo
{

template<typename T> class gsFunctionExprPrivate
{
public:
    T vars[6];
    exprtk::symbol_table<T> symbol_table;
    exprtk::expression<T> expression;
    exprtk::expression<T> der_exp[6];
    bool der_flag[6];
    std::string  string;
    int dim;
};

/* / /AM: under construction
template<typename T> class gsSymbolListPrivate
{
public:
    exprtk::symbol_table<T> symbol_table;
    std::vector<T> vars  ;
    std::vector<T> params;
};

template<typename T>
gsSymbolList<T>::gsSymbolList() : my(new gsSymbolListPrivate<T>) {}

template<typename T>
gsSymbolList<T>::~gsSymbolList()
{
delete my;
}

template<typename T>
void gsSymbolList<T>::setDefault()
{
    my->symbol_table.clear();

    // Identify symbol table
    my->symbol_table.add_variable("x",my->vars[0]);
    my->symbol_table.add_variable("y",my->vars[1]);
    my->symbol_table.add_variable("z",my->vars[2]);
    my->symbol_table.add_variable("w",my->vars[3]);
    my->symbol_table.add_variable("u",my->vars[4]);
    my->symbol_table.add_variable("v",my->vars[5]);
    //my->symbol_table.remove_variable("w",my->vars[3]);
    my->symbol_table.add_pi();
    //my->symbol_table.add_constant("C", 1);
}

template<typename T>
bool gsSymbolList<T>::addConstant(const std::string & constant_name, const T& value)
{
return my->symbol_table.add_constant(constant_name, value);
}

template<typename T>
bool gsSymbolList<T>::addVariable(const std::string & variable_name)
{
    my->vars.push_back(0.0);
    return my->symbol_table.add_variable(variable_name, my->vars.back() );
}

template<typename T>
bool gsSymbolList<T>::addParameter(const std::string & variable_name)
{
    my->params.push_back(0.0);
    return my->symbol_table.add_variable(variable_name, my->params.back() );
}

template<typename T>
bool gsSymbolList<T>::hasSymbol(const std::string& symbol_name)
{
return true;
}
//*/

template<typename T>
gsFunctionExpr<T>::gsFunctionExpr() : my(new gsFunctionExprPrivate<T>) {}

template<typename T>
gsFunctionExpr<T>::gsFunctionExpr(const std::string & expression_string, int ddim)
: my(new gsFunctionExprPrivate<T>)
{
    // Keep string data
    my->string = expression_string;
    my->string.erase(std::remove(my->string.begin(),my->string.end(),' '),my->string.end());
    stringReplace(my->string, "**", "^");
    my->dim = ddim;
    init();
}

template<typename T>
gsFunctionExpr<T>::gsFunctionExpr(const gsFunctionExpr& other)
{
    my = new gsFunctionExprPrivate<T>;
    my->string = other.my->string;
    my->dim = other.my->dim;
    init();
}

template<typename T>
gsFunctionExpr<T>& gsFunctionExpr<T>::operator=(const gsFunctionExpr& other)
{
    if (this != &other)
    {
        my->string = other.my->string;
        my->dim = other.my->dim;
        init();
    }
    return *this;
}

template<typename T>
gsFunctionExpr<T>::~gsFunctionExpr()
{
    delete my;
}

// template<typename T>
// void gsFunctionExpr<T>::init(variables,constants)

template<typename T>
void gsFunctionExpr<T>::init()
{
    my->symbol_table.clear();
    my->expression.release();

    // Identify symbol table
    my->symbol_table.add_variable("x",my->vars[0]);
    my->symbol_table.add_variable("y",my->vars[1]);
    my->symbol_table.add_variable("z",my->vars[2]);
    my->symbol_table.add_variable("w",my->vars[3]);
    my->symbol_table.add_variable("u",my->vars[4]);
    my->symbol_table.add_variable("v",my->vars[5]);
    //my->symbol_table.remove_variable("w",my->vars[3]);
    my->symbol_table.add_pi();
    //my->symbol_table.add_constant("C", 1);
    my->expression.register_symbol_table(my->symbol_table);

    exprtk::parser<T> parser;
    //parser.cache_symbols() = true;
    bool success = parser.compile(my->string, my->expression);
    if ( ! success )
        std::cout<<"gsFunctionExpr error: " <<parser.error() <<std::endl;

/*
    AM: Changed in recent versions.
    std::vector<std::string> varlist;
    parser.expression_symbols(varlist);
    varlist.erase(std::remove(varlist.begin(), varlist.end(), "pi"), varlist.end());
    my->dim = varlist.size();
*/

    my->der_flag[0]=false;
    my->der_flag[1]=false;
    my->der_flag[2]=false;
    my->der_flag[3]=false;
    my->der_flag[4]=false;
    my->der_flag[5]=false;
}

template<typename T>
int gsFunctionExpr<T>::domainDim() const
{
    return my->dim;
}

template<typename T>
void gsFunctionExpr<T>::set_x (T const & v) const { my->vars[0]= v; }

template<typename T>
void gsFunctionExpr<T>::set_y (T const & v) const { my->vars[1]= v; }

template<typename T>
void gsFunctionExpr<T>::set_z (T const & v) const { my->vars[2]= v; }

template<typename T>
void gsFunctionExpr<T>::set_w (T const & v) const { my->vars[3]= v; }

template<typename T>
void gsFunctionExpr<T>::set_u (T const & v) const { my->vars[4]= v; }

template<typename T>
void gsFunctionExpr<T>::set_v (T const & v) const { my->vars[5]= v; }

template<typename T>
void gsFunctionExpr<T>::set_x_der (std::string expression_string)
{
    my->der_exp[0].register_symbol_table(my->symbol_table);
    exprtk::parser<T> parser;
    bool success = parser.compile(expression_string, my->der_exp[0] );
    if ( ! success )
        std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl;
    else
        my->der_flag[0]=true;
}

template<typename T>
void gsFunctionExpr<T>::set_y_der (std::string expression_string)
{
    my->der_exp[1].register_symbol_table(my->symbol_table);
    exprtk::parser<T> parser;
    bool success = parser.compile(expression_string, my->der_exp[1] );
    if ( ! success )
        std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl;
    else
        my->der_flag[1]=true;
}

template<typename T>
void gsFunctionExpr<T>::eval_into(const gsMatrix<T>& u, gsMatrix<T>& result) const
{
    GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );

    result.resize(1, u.cols());
    for ( int i = 0; i<u.cols(); i++ )
    {
        for ( int j = 0; j<u.rows(); j++ )
        {
            my->vars[j] =u(j,i);
        }
        result(0,i) = my->expression.value();
    }
}

template<typename T>
void gsFunctionExpr<T>::eval_component_into(const gsMatrix<T>& u, const index_t comp, gsMatrix<T>& result) const
{
    GISMO_ASSERT (comp == 0, "Given component number is too high. Only one component");
    result.resize(1, u.cols());
    for ( int i = 0; i<u.cols(); i++ )
    {
        for ( int j = 0; j<u.rows(); j++ )
        {
            my->vars[j] =u(j,i);
        }
        result(0,i) = my->expression.value();
    }
}

template<typename T>
void gsFunctionExpr<T>::deriv_into(const gsMatrix<T>& u, gsMatrix<T>& result) const
{
    int n = u.rows();
    GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );

    result.resize(1, n * u.cols());

    for( int i=0; i < u.cols(); ++i )
    {
        for ( int j = 0; j<n; j++ )
            my->vars[j] =u(j,i);
        for( int j=0; j< n; ++j )
            if ( my->der_flag[j] )
                result(n*i+j) = my->der_exp[j].value();
            else
                result(n*i+j) = exprtk::derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
    }
    result.resize(n, u.cols());
}

template<typename T>
typename gsFunction<T>::uMatrixPtr
gsFunctionExpr<T>::hess(const gsMatrix<T>& u, unsigned coord) const
{
    GISMO_ENSURE(coord == 0, "Error, function is real");
    // one column only..
    int n = u.rows();
    GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );

    gsMatrix<T> * res= new gsMatrix<T>(n,n) ;

    for ( int j = 0; j<n; j++ )
        my->vars[j] =u(j,0);
    for( int j=0; j< n; ++j )
    {
        (*res)(j,j) = exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
        for( int k=0; k<j; ++k )
            (*res)(k,j) = (*res)(j,k) =
                exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ;
    }
    return typename gsFunction<T>::uMatrixPtr(res);
} ;
template<typename T>
gsMatrix<T> * gsFunctionExpr<T>::mderiv(const gsMatrix<T>& u, const index_t &k, const index_t &j ) const
{
    gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ;

    for( index_t i=0; i< res->cols(); ++i )
    {
      	for ( int t = 0; t<u.rows(); t++ )
            my->vars[t] =u(t,i);
        (*res)(0,i) =
            exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ;
    }
    return  res;
} ;

template<typename T>
gsMatrix<T> * gsFunctionExpr<T>::laplacian(const gsMatrix<T>& u) const
{
    gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ;
    res->setZero();
    int n = u.rows();

    for( index_t i=0; i< res->cols(); ++i )
        for ( int j = 0; j<n; j++ )
        {
            my->vars[j] =u(j,i);
            (*res)(0,i) +=
                exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
        }
    return  res;
}

template<typename T>
T gsFunctionExpr<T>::value() const
{
    return my->expression.value() ;
}

template<typename T>
std::ostream & gsFunctionExpr<T>::print(std::ostream &os) const
{ os << my->string ; return os; }

}; // namespace gismo
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015-2018, Technische Universität Dresden, Germany
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted
 * provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions
 *    and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE 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.
 */

#include <nitro/env/process.hpp>

extern "C"
{
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#include <windows.h>

#include <tlhelp32.h>
#else
#include <unistd.h>
#endif
}

namespace nitro
{
namespace env
{
    int get_pid()
    {
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
        return GetCurrentProcessId();
#else
        return getpid();
#endif
    }

    int get_parent_pid()
    {
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
        HANDLE hSnapshot;
        PROCESSENTRY32 pe32;
        DWORD ppid = 0, pid = nitro::env::get_pid();

        hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        __try
        {
            if (hSnapshot == INVALID_HANDLE_VALUE)
                __leave;

            ZeroMemory(&pe32, sizeof(pe32));
            pe32.dwSize = sizeof(pe32);
            if (!Process32First(hSnapshot, &pe32))
                __leave;

            do
            {
                if (pe32.th32ProcessID == pid)
                {
                    ppid = pe32.th32ParentProcessID;
                    break;
                }
            } while (Process32Next(hSnapshot, &pe32));
        }
        __finally
        {
            if (hSnapshot != INVALID_HANDLE_VALUE)
                CloseHandle(hSnapshot);
        }
        return ppid;
#else
        return getppid();
#endif
    }

    int get_tid()
    {
        return nitro::env::get_pid();
    }

} // namespace env
} // namespace nitro
<commit_msg>Actually implement gettid for linux using syscall<commit_after>/*
 * Copyright (c) 2015-2018, Technische Universität Dresden, Germany
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted
 * provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions
 *    and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE 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.
 */

#include <nitro/env/process.hpp>

extern "C"
{
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#include <windows.h>

#include <tlhelp32.h>
#else
#include <unistd.h>
#endif

#ifdef __linux__
#include <sys/syscall.h>
#include <sys/types.h>
#endif
}

namespace nitro
{
namespace env
{
    int get_pid()
    {
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
        return GetCurrentProcessId();
#else
        return getpid();
#endif
    }

    int get_parent_pid()
    {
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
        HANDLE hSnapshot;
        PROCESSENTRY32 pe32;
        DWORD ppid = 0, pid = nitro::env::get_pid();

        hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        __try
        {
            if (hSnapshot == INVALID_HANDLE_VALUE)
                __leave;

            ZeroMemory(&pe32, sizeof(pe32));
            pe32.dwSize = sizeof(pe32);
            if (!Process32First(hSnapshot, &pe32))
                __leave;

            do
            {
                if (pe32.th32ProcessID == pid)
                {
                    ppid = pe32.th32ParentProcessID;
                    break;
                }
            } while (Process32Next(hSnapshot, &pe32));
        }
        __finally
        {
            if (hSnapshot != INVALID_HANDLE_VALUE)
                CloseHandle(hSnapshot);
        }
        return ppid;
#else
        return getppid();
#endif
    }

    int get_tid()
    {
#if __linux__
        return syscall(SYS_gettid);
#else
        return nitro::env::get_pid();
#endif
    }

} // namespace env
} // namespace nitro
<|endoftext|>


<commit_before>/*******************************************************************************
 * c7a/api/context.hpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef C7A_API_CONTEXT_HEADER
#define C7A_API_CONTEXT_HEADER

#include <cassert>
#include <fstream>
#include <string>
#include <vector>

#include "c7a/data/data_manager.hpp"
#include "c7a/core/job_manager.hpp"

#include <stdio.h>
#include <unistd.h>
#define GetCurrentDir getcwd

namespace c7a {

class Context
{
public:
    Context() : job_manager_() { }
    virtual ~Context() { }

    data::DataManager & get_data_manager() {
        return job_manager_.get_data_manager();
    }

    int number_worker() {
        return number_worker_;
    }

    core::JobManager & job_manager() {
        return job_manager_;
    }

    std::string get_current_dir() {
        char cCurrentPath[FILENAME_MAX];

        if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) {
            throw "unable to retrieve current directory";
        }

        return GetCurrentDir(cCurrentPath, sizeof(cCurrentPath));
    }

private:
    core::JobManager job_manager_;
    //stub
    int number_worker_ = 1;
};

} // namespace c7a

#endif // !C7A_API_CONTEXT_HEADER

/******************************************************************************/
<commit_msg>removed unnecessary define<commit_after>/*******************************************************************************
 * c7a/api/context.hpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef C7A_API_CONTEXT_HEADER
#define C7A_API_CONTEXT_HEADER

#include <cassert>
#include <fstream>
#include <string>
#include <vector>

#include "c7a/data/data_manager.hpp"
#include "c7a/core/job_manager.hpp"

#include <stdio.h>
#include <unistd.h>

namespace c7a {

class Context
{
public:
    Context() : job_manager_() { }
    virtual ~Context() { }

    data::DataManager & get_data_manager() {
        return job_manager_.get_data_manager();
    }

    int number_worker() {
        return number_worker_;
    }

    core::JobManager & job_manager() {
        return job_manager_;
    }

    std::string get_current_dir() {
        char cCurrentPath[FILENAME_MAX];

        if (!getcwd(cCurrentPath, sizeof(cCurrentPath))) {
            throw "unable to retrieve current directory";
        }

        return getcwd(cCurrentPath, sizeof(cCurrentPath));
    }

private:
    core::JobManager job_manager_;
    //stub
    int number_worker_ = 1;
};

} // namespace c7a

#endif // !C7A_API_CONTEXT_HEADER

/******************************************************************************/
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * X testing environment - Google Test environment feat. dummy x server
 *
 * Copyright (C) 2011, 2012 Canonical Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 ******************************************************************************/

#include "xorg/gtest/xorg-gtest_environment.h"
#include "xorg/gtest/xorg-gtest_process.h"
#include "defines.h"

#include <sys/types.h>
#include <unistd.h>

#include <cerrno>
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <stdexcept>

#include <X11/Xlib.h>

struct xorg::testing::Environment::Private {
  Private()
      : path_to_conf(DUMMY_CONF_PATH), path_to_log_file(DEFAULT_XORG_LOGFILE),
        path_to_server(DEFAULT_XORG_SERVER), display(DEFAULT_DISPLAY) {
  }

  std::string path_to_conf;
  std::string path_to_log_file;
  std::string path_to_server;
  int display;
  Process process;
};

xorg::testing::Environment::Environment()
    : d_(new Private) {
}

xorg::testing::Environment::~Environment() {}

void xorg::testing::Environment::set_log_file(const std::string& path_to_log_file)
{
  d_->path_to_log_file = path_to_log_file;
}

const std::string& xorg::testing::Environment::log_file() const
{
  return d_->path_to_log_file;
}

void xorg::testing::Environment::set_conf_file(const std::string& path_conf_file)
{
  d_->path_to_conf = path_conf_file;
}

const std::string& xorg::testing::Environment::conf_file() const
{
  return d_->path_to_conf;
}

void xorg::testing::Environment::set_server(const std::string& path_to_server)
{
  d_->path_to_server = path_to_server;
}

const std::string& xorg::testing::Environment::server() const
{
  return d_->path_to_server;
}

void xorg::testing::Environment::set_display(int display_num)
{
  d_->display = display_num;
}

int xorg::testing::Environment::display() const
{
  return d_->display;
}

void xorg::testing::Environment::SetUp() {
  static char display_string[6];
  snprintf(display_string, 6, ":%d", d_->display);

  d_->process.Start(d_->path_to_server, d_->path_to_server.c_str(),
                    display_string,
                    "-logfile", d_->path_to_log_file.c_str(),
                    "-config", d_->path_to_conf.c_str(),
                    NULL);

  Process::SetEnv("DISPLAY", display_string, true);

  for (int i = 0; i < 10; ++i) {
    Display* test_display = XOpenDisplay(NULL);

    if (test_display) {
      XCloseDisplay(test_display);
      return;
    }

    int status;
    int pid = waitpid(d_->process.Pid(), &status, WNOHANG);
    if (pid == d_->process.Pid()) {
      std::string message;
      message += "X server failed to start on display ";
      message += display_string;
      message += ". Ensure that the \"dummy\" video driver is installed. "
                 "If the X.org server is older than 1.12, "
                 "tests will need to be run as root. Check ";
      message += d_->path_to_log_file;
      message += " for any errors";
      throw std::runtime_error(message);
    } else if (pid == 0) {
      sleep(1); /* Give the dummy X server some time to start */
    } else if (pid == -1) {
      throw std::runtime_error("Could not get status of dummy X server "
                               "process");
    } else {
      throw std::runtime_error("Invalid child PID returned by Process::Wait()");
    }
  }

  throw std::runtime_error("Unable to open connection to dummy X server");
}

void xorg::testing::Environment::TearDown() {
  if (d_->process.Terminate()) {
    for (int i = 0; i < 10; i++) {
      int status;
      int pid = waitpid(d_->process.Pid(), &status, WNOHANG);

      if (pid == d_->process.Pid())
        return;

      sleep(1); /* Give the dummy X server more time to shut down */
    }
  }

  Kill();
}

void xorg::testing::Environment::Kill() {
  if (!d_->process.Kill())
    std::cerr << "Warning: Failed to kill dummy Xorg server: "
              << std::strerror(errno) << "\n";

  for (int i = 0; i < 10; i++) {
    int status;
    int pid = waitpid(d_->process.Pid(), &status, WNOHANG);

    if (pid == d_->process.Pid())
      return;

      sleep(1); /* Give the dummy X server more time to shut down */
  }

  std::cerr << "Warning: Dummy X server did not shut down\n";
}
<commit_msg>Check if a server is already running on the chosen display name<commit_after>/*******************************************************************************
 *
 * X testing environment - Google Test environment feat. dummy x server
 *
 * Copyright (C) 2011, 2012 Canonical Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 ******************************************************************************/

#include "xorg/gtest/xorg-gtest_environment.h"
#include "xorg/gtest/xorg-gtest_process.h"
#include "defines.h"

#include <sys/types.h>
#include <unistd.h>

#include <cerrno>
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <stdexcept>

#include <X11/Xlib.h>

struct xorg::testing::Environment::Private {
  Private()
      : path_to_conf(DUMMY_CONF_PATH), path_to_log_file(DEFAULT_XORG_LOGFILE),
        path_to_server(DEFAULT_XORG_SERVER), display(DEFAULT_DISPLAY) {
  }

  std::string path_to_conf;
  std::string path_to_log_file;
  std::string path_to_server;
  int display;
  Process process;
};

xorg::testing::Environment::Environment()
    : d_(new Private) {
}

xorg::testing::Environment::~Environment() {}

void xorg::testing::Environment::set_log_file(const std::string& path_to_log_file)
{
  d_->path_to_log_file = path_to_log_file;
}

const std::string& xorg::testing::Environment::log_file() const
{
  return d_->path_to_log_file;
}

void xorg::testing::Environment::set_conf_file(const std::string& path_conf_file)
{
  d_->path_to_conf = path_conf_file;
}

const std::string& xorg::testing::Environment::conf_file() const
{
  return d_->path_to_conf;
}

void xorg::testing::Environment::set_server(const std::string& path_to_server)
{
  d_->path_to_server = path_to_server;
}

const std::string& xorg::testing::Environment::server() const
{
  return d_->path_to_server;
}

void xorg::testing::Environment::set_display(int display_num)
{
  d_->display = display_num;
}

int xorg::testing::Environment::display() const
{
  return d_->display;
}

void xorg::testing::Environment::SetUp() {
  static char display_string[6];
  snprintf(display_string, 6, ":%d", d_->display);

  Display* test_display = XOpenDisplay(display_string);
  if (test_display) {
    XCloseDisplay(test_display);
    std::string message;
    message += "A server is already running on ";
    message += display_string;
    message += ".";
    throw std::runtime_error(message);
  }

  d_->process.Start(d_->path_to_server, d_->path_to_server.c_str(),
                    display_string,
                    "-logfile", d_->path_to_log_file.c_str(),
                    "-config", d_->path_to_conf.c_str(),
                    NULL);

  Process::SetEnv("DISPLAY", display_string, true);

  for (int i = 0; i < 10; ++i) {
    test_display = XOpenDisplay(NULL);

    if (test_display) {
      XCloseDisplay(test_display);
      return;
    }

    int status;
    int pid = waitpid(d_->process.Pid(), &status, WNOHANG);
    if (pid == d_->process.Pid()) {
      std::string message;
      message += "X server failed to start on display ";
      message += display_string;
      message += ". Ensure that the \"dummy\" video driver is installed. "
                 "If the X.org server is older than 1.12, "
                 "tests will need to be run as root. Check ";
      message += d_->path_to_log_file;
      message += " for any errors";
      throw std::runtime_error(message);
    } else if (pid == 0) {
      sleep(1); /* Give the dummy X server some time to start */
    } else if (pid == -1) {
      throw std::runtime_error("Could not get status of dummy X server "
                               "process");
    } else {
      throw std::runtime_error("Invalid child PID returned by Process::Wait()");
    }
  }

  throw std::runtime_error("Unable to open connection to dummy X server");
}

void xorg::testing::Environment::TearDown() {
  if (d_->process.Terminate()) {
    for (int i = 0; i < 10; i++) {
      int status;
      int pid = waitpid(d_->process.Pid(), &status, WNOHANG);

      if (pid == d_->process.Pid())
        return;

      sleep(1); /* Give the dummy X server more time to shut down */
    }
  }

  Kill();
}

void xorg::testing::Environment::Kill() {
  if (!d_->process.Kill())
    std::cerr << "Warning: Failed to kill dummy Xorg server: "
              << std::strerror(errno) << "\n";

  for (int i = 0; i < 10; i++) {
    int status;
    int pid = waitpid(d_->process.Pid(), &status, WNOHANG);

    if (pid == d_->process.Pid())
      return;

      sleep(1); /* Give the dummy X server more time to shut down */
  }

  std::cerr << "Warning: Dummy X server did not shut down\n";
}
<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/searchlib/attribute/attribute.h>
#include <vespa/searchlib/attribute/attributefactory.h>
#include <vespa/searchlib/attribute/attributevector.hpp>
#include <vespa/searchlib/attribute/integerbase.h>

#include <vespa/log/log.h>
LOG_SETUP("attribute_compaction_test");

using search::IntegerAttribute;
using search::AttributeVector;
using search::attribute::Config;
using search::attribute::BasicType;
using search::attribute::CollectionType;

using AttributePtr = AttributeVector::SP;
using AttributeStatus = search::attribute::Status;

namespace
{

template <typename VectorType>
bool is(AttributePtr &v)
{
    return dynamic_cast<VectorType *>(v.get());
}

template <typename VectorType>
VectorType &as(AttributePtr &v)
{
    return dynamic_cast<VectorType &>(*v);
}

void populateAttribute(IntegerAttribute &v, uint32_t docIdLimit)
{
    for(uint32_t docId = 0; docId < docIdLimit; ++docId) {
        uint32_t checkDocId = 0;
        EXPECT_TRUE(v.addDoc(checkDocId));
        EXPECT_EQUAL(docId, checkDocId);
        v.clearDoc(docId);
        for (size_t vi = 0; vi <= 40; ++vi) {
            EXPECT_TRUE(v.append(docId, 42, 1) );
        }
    }
    v.commit(true);
    v.incGeneration();
}

void populateAttribute(AttributePtr &v, uint32_t docIdLimit)
{
    if (is<IntegerAttribute>(v)) {
        populateAttribute(as<IntegerAttribute>(v), docIdLimit);
    }
}

void cleanAttribute(AttributeVector &v, uint32_t docIdLimit)
{
    for (uint32_t docId = 0; docId < docIdLimit; ++docId) {
        v.clearDoc(docId);
    }
    v.commit(true);
    v.incGeneration();
}

}

class Fixture {
public:
    AttributePtr _v;

    Fixture(Config cfg)
        : _v()
    { _v = search::AttributeFactory::createAttribute("test", cfg); }
    ~Fixture() { }
    void populate(uint32_t docIdLimit) { populateAttribute(_v, docIdLimit); }
    void clean(uint32_t docIdLimit) { cleanAttribute(*_v, docIdLimit); }
    AttributeStatus getStatus() { _v->commit(true); return _v->getStatus(); }
    AttributeStatus getStatus(const vespalib::string &prefix) {
        AttributeStatus status(getStatus());
        LOG(info, "status %s: used=%zu, dead=%zu, onHold=%zu",
            prefix.c_str(), status.getUsed(), status.getDead(), status.getOnHold());
        return status;
    }
};

TEST_F("Test that compaction of integer array attribute reduces memory usage", Fixture({ BasicType::INT64, CollectionType::ARRAY }))
{
    f.populate(3000);
    AttributeStatus beforeStatus = f.getStatus("before");
    f.clean(2000);
    AttributeStatus afterStatus = f.getStatus("after");
    EXPECT_LESS(afterStatus.getUsed(), beforeStatus.getUsed());
}

TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>Unit test compaction triggered by address space usage.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/searchlib/attribute/attribute.h>
#include <vespa/searchlib/attribute/attributefactory.h>
#include <vespa/searchlib/attribute/attributevector.hpp>
#include <vespa/searchlib/attribute/integerbase.h>
#include <vespa/searchlib/attribute/address_space_usage.h>

#include <vespa/log/log.h>
LOG_SETUP("attribute_compaction_test");

using search::IntegerAttribute;
using search::AttributeVector;
using search::attribute::Config;
using search::attribute::BasicType;
using search::attribute::CollectionType;
using search::AddressSpace;

using AttributePtr = AttributeVector::SP;
using AttributeStatus = search::attribute::Status;

namespace
{

struct DocIdRange {
    uint32_t docIdStart;
    uint32_t docIdLimit;
    DocIdRange(uint32_t docIdStart_, uint32_t docIdLimit_)
        : docIdStart(docIdStart_),
          docIdLimit(docIdLimit_)
    {
    }
    uint32_t begin() { return docIdStart; }
    uint32_t end() { return docIdLimit; }
    uint32_t size() { return end() - begin(); }
};

template <typename VectorType>
bool is(AttributePtr &v)
{
    return dynamic_cast<VectorType *>(v.get());
}

template <typename VectorType>
VectorType &as(AttributePtr &v)
{
    return dynamic_cast<VectorType &>(*v);
}

void cleanAttribute(AttributeVector &v, DocIdRange range)
{
    for (uint32_t docId = range.begin(); docId < range.end(); ++docId) {
        v.clearDoc(docId);
    }
    v.commit(true);
    v.incGeneration();
}

DocIdRange addAttributeDocs(AttributePtr &v, uint32_t numDocs)
{
    uint32_t startDoc = 0;
    uint32_t lastDoc = 0;
    EXPECT_TRUE(v->addDocs(startDoc, lastDoc, numDocs));
    EXPECT_EQUAL(startDoc + numDocs - 1, lastDoc);
    DocIdRange range(startDoc, startDoc + numDocs);
    cleanAttribute(*v, range);
    return range;
}

void populateAttribute(IntegerAttribute &v, DocIdRange range, uint32_t values)
{
    for(uint32_t docId = range.begin(); docId < range.end(); ++docId) {
        v.clearDoc(docId);
        for (uint32_t vi = 0; vi <= values; ++vi) {
            EXPECT_TRUE(v.append(docId, 42, 1) );
        }
        if ((docId % 100) == 0) {
            v.commit();
        }
    }
    v.commit(true);
    v.incGeneration();
}

void populateAttribute(AttributePtr &v, DocIdRange range, uint32_t values)
{
    if (is<IntegerAttribute>(v)) {
        populateAttribute(as<IntegerAttribute>(v), range, values);
    }
}

void hammerAttribute(IntegerAttribute &v, DocIdRange range, uint32_t count)
{
    uint32_t work = 0;
    for (uint32_t i = 0; i < count; ++i) {
        for (uint32_t docId = range.begin(); docId < range.end(); ++docId) {
            v.clearDoc(docId);
            EXPECT_TRUE(v.append(docId, 42, 1));
        }
        work += range.size();
        if (work >= 100000) {
            v.commit(true);
            work = 0;
        } else {
            v.commit();
        }
    }
    v.commit(true);
    v.incGeneration();
}

void hammerAttribute(AttributePtr &v, DocIdRange range, uint32_t count)
{
    if (is<IntegerAttribute>(v)) {
        hammerAttribute(as<IntegerAttribute>(v), range, count);
    }
}

Config compactAddressSpaceAttributeConfig(bool enableAddressSpaceCompact)
{
    Config cfg(BasicType::INT8, CollectionType::ARRAY);
    cfg.setCompactionStrategy({ 1.0, (enableAddressSpaceCompact ? 0.2 : 1.0) });
    return cfg;
}

}

class Fixture {
public:
    AttributePtr _v;

    Fixture(Config cfg)
        : _v()
    { _v = search::AttributeFactory::createAttribute("test", cfg); }
    ~Fixture() { }
    DocIdRange addDocs(uint32_t numDocs) { return addAttributeDocs(_v, numDocs); }
    void populate(DocIdRange range, uint32_t values) { populateAttribute(_v, range, values); }
    void hammer(DocIdRange range, uint32_t count) { hammerAttribute(_v, range, count); }
    void clean(DocIdRange range) { cleanAttribute(*_v, range); }
    AttributeStatus getStatus() { _v->commit(true); return _v->getStatus(); }
    AttributeStatus getStatus(const vespalib::string &prefix) {
        AttributeStatus status(getStatus());
        LOG(info, "status %s: used=%zu, dead=%zu, onHold=%zu",
            prefix.c_str(), status.getUsed(), status.getDead(), status.getOnHold());
        return status;
    }
    const Config &getConfig() const { return _v->getConfig(); }
    AddressSpace getMultiValueAddressSpaceUsage() const {return _v->getAddressSpaceUsage().multiValueUsage(); }
    AddressSpace getMultiValueAddressSpaceUsage(const vespalib::string &prefix) {
        AddressSpace usage(getMultiValueAddressSpaceUsage());
        LOG(info, "address space usage %s: used=%zu, dead=%zu, limit=%zu, usage=%12.8f",
            prefix.c_str(), usage.used(), usage.dead(), usage.limit(), usage.usage());
        return usage;
    }
};

TEST_F("Test that compaction of integer array attribute reduces memory usage", Fixture({ BasicType::INT64, CollectionType::ARRAY }))
{
    DocIdRange range1 = f.addDocs(2000);
    DocIdRange range2 = f.addDocs(1000);
    f.populate(range1, 40);
    f.populate(range2, 40);
    AttributeStatus beforeStatus = f.getStatus("before");
    f.clean(range1);
    AttributeStatus afterStatus = f.getStatus("after");
    EXPECT_LESS(afterStatus.getUsed(), beforeStatus.getUsed());
}

TEST_F("Test that no compaction of int8 array attribute increases address space usage", Fixture(compactAddressSpaceAttributeConfig(false)))
{
    DocIdRange range1 = f.addDocs(1000);
    DocIdRange range2 = f.addDocs(1000);
    f.populate(range1, 1000);
    f.hammer(range2, 101);
    AddressSpace afterSpace = f.getMultiValueAddressSpaceUsage("after");
    EXPECT_EQUAL(100001, afterSpace.dead());
}

TEST_F("Test that compaction of int8 array attribute limits address space usage", Fixture(compactAddressSpaceAttributeConfig(true)))
{
    DocIdRange range1 = f.addDocs(1000);
    DocIdRange range2 = f.addDocs(1000);
    f.populate(range1, 1000);
    f.hammer(range2, 101);
    AddressSpace afterSpace = f.getMultiValueAddressSpaceUsage("after");
    EXPECT_GREATER(65536, afterSpace.dead());
}

TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>


<commit_before>/*
 *  This file is part of Poedit (http://www.poedit.net)
 *
 *  Copyright (C) 2003 Christophe Hermier
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include <wx/intl.h>
#include <wx/colour.h>
#include <wx/utils.h>
#include <wx/textfile.h>

#include "catalog.h"

namespace
{

// colours used in the list:
// (FIXME: this is duplicated with code in edframe.cpp, get rid of this
// duplication, preferably by making the colours customizable and stored
// in wxConfig)

#define g_darkColourFactor 0.95
#define DARKEN_COLOUR(r,g,b) (wxColour(int((r)*g_darkColourFactor),\
                                       int((g)*g_darkColourFactor),\
                                       int((b)*g_darkColourFactor)))
#define LIST_COLOURS(r,g,b) { wxColour(r,g,b), DARKEN_COLOUR(r,g,b) }
wxColour
    g_ItemColourNormal[2] =       LIST_COLOURS(0xFF,0xFF,0xFF), // white
    g_ItemColourUntranslated[2] = LIST_COLOURS(0xA5,0xEA,0xEF), // blue
    g_ItemColourFuzzy[2] =        LIST_COLOURS(0xF4,0xF1,0xC1); // yellow

// escape string for HTML:
wxString Escape(const wxString& str)
{
    wxString s(str);
    s.Replace(_T("&"), _T("&"));
    s.Replace(_T("<"), _T("<"));
    s.Replace(_T(">"), _T(">"));
    return s;
}

} // anonymous namespace

bool Catalog::ExportToHTML(const wxString& filename)
{
    size_t i;
    wxTextFile f;

    if ( wxFileExists(filename) )
    {
        wxRemoveFile ( filename);
    }

    if (!f.Create(filename))
    {
        return false;
    }

    // TODO use some kind of HTML template system to allow different styles

    wxString line;

    // HTML HEADER
    f.AddLine(_T("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"));
    f.AddLine(_T(""));

    f.AddLine(_T(""));
    line.Printf(_T("<title> %s - %s / %s - Poedit Export </title>"),
                Escape(m_header.Project).c_str(),
                Escape(m_header.Language).c_str(),
                Escape(m_header.Country).c_str());
    f.AddLine(line);
    f.AddLine(_T("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" ) );
    f.AddLine(_T(""));
    f.AddLine(_T(""));

    line.Printf(_T("
 %s : %s / %s
"),
                Escape(m_header.Project).c_str(),
                Escape(m_header.Language).c_str(),
                Escape(m_header.Country).c_str());
    f.AddLine(line);

    // po file header information :

    // String here are duplicates from the ones in setting.xrc
    // TODO find a way if possible to synchronize them

    f.AddLine(_T("
"));

    line.Printf(_T("
%s
"),
                _("Project info"));
    f.AddLine(line);
    wxString line_format = _T("
%s	%s
");
    line.Printf(line_format,
                _("Project name and version:"),
                Escape(m_header.Project).c_str());
    f.AddLine(line);
    line.Printf(line_format, _("Language:"),
                Escape(m_header.Language).c_str());
    f.AddLine(line);
    line.Printf(line_format, _("Country:"),
                Escape(m_header.Country).c_str());
    f.AddLine(line);
    line.Printf(line_format, _("Team:"),
                Escape(m_header.Team).c_str());
    f.AddLine(line);
    line.Printf(_T("
%s	%s
"),
                _("Team's email address:"),
                Escape(m_header.TeamEmail).c_str(),
                Escape(m_header.TeamEmail).c_str());
    f.AddLine(line);
    line.Printf(line_format, _("Charset:"),
                Escape(m_header.Charset).c_str());
    f.AddLine(line);

    f.AddLine( _T("
") );
    // statistics

    int all = 0;
    int fuzzy = 0;
    int untranslated = 0;
    int badtokens = 0;
    int unfinished = 0;
    GetStatistics(&all, &fuzzy, &badtokens, &untranslated, &unfinished);

    int percent = (all == 0 ) ? 0 : (100 * (all - unfinished) / all);
    line.Printf(_("%i %% translated, %i strings (%i fuzzy, %i bad tokens, %i not translated)"),
               percent, all, fuzzy, badtokens, untranslated);

    f.AddLine(line);

    // data printed in a table :
    f.AddLine(_T("
"));

    f.AddLine(_T("
"));
    f.AddLine(_T(""));
    f.AddLine(_("Source"));
    f.AddLine(_T("	"));
    f.AddLine(_T(""));
    f.AddLine(_("Translation"));
    f.AddLine(_T("	"));
    f.AddLine(_T("	"));
    f.AddLine(_T(""));
    f.AddLine(_("Notes"));
    f.AddLine(_T("	"));
    f.AddLine(_T("
"));

    for (i = 0; i < GetCount(); i++)
    {
        const CatalogItem& data = m_items[i];

        wxColour bgcolor = g_ItemColourNormal[i % 2];
        wxString source_string = data.GetString();

        wxString translation = data.GetTranslation();
        if (translation.empty())
        {
            translation = _T(" ");
            bgcolor = g_ItemColourUntranslated[i % 2];
        }

        wxString flags;

        if (data.IsAutomatic())
        {
            flags += _("Automatic translation");
            flags += _T("
");
        }
        if (data.IsFuzzy())
        {
            bgcolor = g_ItemColourFuzzy[i % 2];
            flags += _("Fuzzy translation");
            flags += _T("
");
        }
        if (flags.empty())
        {
            flags = _T(" ");
        }

        wxString tr;
        tr.Printf(_T("
"),
                  bgcolor.Red(), bgcolor.Green(), bgcolor.Blue());
        f.AddLine(tr);

        f.AddLine(_T(""));
        f.AddLine(Escape(source_string));
        f.AddLine(_T("	"));
        f.AddLine(_T(""));
        f.AddLine(Escape(translation));
        f.AddLine(_T("	"));
        f.AddLine(_T(""));
        f.AddLine(_T(""));
        f.AddLine(Escape(flags));
        f.AddLine(_T(""));
        f.AddLine(_T("	"));
        f.AddLine(_T("
"));
    }

    f.AddLine(_T("
"));
    f.AddLine(_T(""));
    f.AddLine(_T(""));

    bool written = f.Write(wxTextFileType_None, wxConvUTF8);

    f.Close();

    return written;
}
<commit_msg>Fix illegal markup in table header in HTML export.<commit_after>/*
 *  This file is part of Poedit (http://www.poedit.net)
 *
 *  Copyright (C) 2003 Christophe Hermier
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include <wx/intl.h>
#include <wx/colour.h>
#include <wx/utils.h>
#include <wx/textfile.h>

#include "catalog.h"

namespace
{

// colours used in the list:
// (FIXME: this is duplicated with code in edframe.cpp, get rid of this
// duplication, preferably by making the colours customizable and stored
// in wxConfig)

#define g_darkColourFactor 0.95
#define DARKEN_COLOUR(r,g,b) (wxColour(int((r)*g_darkColourFactor),\
                                       int((g)*g_darkColourFactor),\
                                       int((b)*g_darkColourFactor)))
#define LIST_COLOURS(r,g,b) { wxColour(r,g,b), DARKEN_COLOUR(r,g,b) }
wxColour
    g_ItemColourNormal[2] =       LIST_COLOURS(0xFF,0xFF,0xFF), // white
    g_ItemColourUntranslated[2] = LIST_COLOURS(0xA5,0xEA,0xEF), // blue
    g_ItemColourFuzzy[2] =        LIST_COLOURS(0xF4,0xF1,0xC1); // yellow

// escape string for HTML:
wxString Escape(const wxString& str)
{
    wxString s(str);
    s.Replace(_T("&"), _T("&"));
    s.Replace(_T("<"), _T("<"));
    s.Replace(_T(">"), _T(">"));
    return s;
}

} // anonymous namespace

bool Catalog::ExportToHTML(const wxString& filename)
{
    size_t i;
    wxTextFile f;

    if ( wxFileExists(filename) )
    {
        wxRemoveFile ( filename);
    }

    if (!f.Create(filename))
    {
        return false;
    }

    // TODO use some kind of HTML template system to allow different styles

    wxString line;

    // HTML HEADER
    f.AddLine(_T("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"));
    f.AddLine(_T(""));

    f.AddLine(_T(""));
    line.Printf(_T("<title> %s - %s / %s - Poedit Export </title>"),
                Escape(m_header.Project).c_str(),
                Escape(m_header.Language).c_str(),
                Escape(m_header.Country).c_str());
    f.AddLine(line);
    f.AddLine(_T("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" ) );
    f.AddLine(_T(""));
    f.AddLine(_T(""));

    line.Printf(_T("
 %s : %s / %s
"),
                Escape(m_header.Project).c_str(),
                Escape(m_header.Language).c_str(),
                Escape(m_header.Country).c_str());
    f.AddLine(line);

    // po file header information :

    // String here are duplicates from the ones in setting.xrc
    // TODO find a way if possible to synchronize them

    f.AddLine(_T("
"));

    line.Printf(_T("
%s
"),
                _("Project info"));
    f.AddLine(line);
    wxString line_format = _T("
%s	%s
");
    line.Printf(line_format,
                _("Project name and version:"),
                Escape(m_header.Project).c_str());
    f.AddLine(line);
    line.Printf(line_format, _("Language:"),
                Escape(m_header.Language).c_str());
    f.AddLine(line);
    line.Printf(line_format, _("Country:"),
                Escape(m_header.Country).c_str());
    f.AddLine(line);
    line.Printf(line_format, _("Team:"),
                Escape(m_header.Team).c_str());
    f.AddLine(line);
    line.Printf(_T("
%s	%s
"),
                _("Team's email address:"),
                Escape(m_header.TeamEmail).c_str(),
                Escape(m_header.TeamEmail).c_str());
    f.AddLine(line);
    line.Printf(line_format, _("Charset:"),
                Escape(m_header.Charset).c_str());
    f.AddLine(line);

    f.AddLine( _T("
") );
    // statistics

    int all = 0;
    int fuzzy = 0;
    int untranslated = 0;
    int badtokens = 0;
    int unfinished = 0;
    GetStatistics(&all, &fuzzy, &badtokens, &untranslated, &unfinished);

    int percent = (all == 0 ) ? 0 : (100 * (all - unfinished) / all);
    line.Printf(_("%i %% translated, %i strings (%i fuzzy, %i bad tokens, %i not translated)"),
               percent, all, fuzzy, badtokens, untranslated);

    f.AddLine(line);

    // data printed in a table :
    f.AddLine(_T("
"));

    f.AddLine(_T("
"));
    f.AddLine(_T(""));
    f.AddLine(_("Source"));
    f.AddLine(_T("	"));
    f.AddLine(_T(""));
    f.AddLine(_("Translation"));
    f.AddLine(_T("	"));
    f.AddLine(_T(""));
    f.AddLine(_("Notes"));
    f.AddLine(_T("	"));
    f.AddLine(_T("
"));

    for (i = 0; i < GetCount(); i++)
    {
        const CatalogItem& data = m_items[i];

        wxColour bgcolor = g_ItemColourNormal[i % 2];
        wxString source_string = data.GetString();

        wxString translation = data.GetTranslation();
        if (translation.empty())
        {
            translation = _T(" ");
            bgcolor = g_ItemColourUntranslated[i % 2];
        }

        wxString flags;

        if (data.IsAutomatic())
        {
            flags += _("Automatic translation");
            flags += _T("
");
        }
        if (data.IsFuzzy())
        {
            bgcolor = g_ItemColourFuzzy[i % 2];
            flags += _("Fuzzy translation");
            flags += _T("
");
        }
        if (flags.empty())
        {
            flags = _T(" ");
        }

        wxString tr;
        tr.Printf(_T("
"),
                  bgcolor.Red(), bgcolor.Green(), bgcolor.Blue());
        f.AddLine(tr);

        f.AddLine(_T(""));
        f.AddLine(Escape(source_string));
        f.AddLine(_T("	"));
        f.AddLine(_T(""));
        f.AddLine(Escape(translation));
        f.AddLine(_T("	"));
        f.AddLine(_T(""));
        f.AddLine(_T(""));
        f.AddLine(Escape(flags));
        f.AddLine(_T(""));
        f.AddLine(_T("	"));
        f.AddLine(_T("
"));
    }

    f.AddLine(_T("
"));
    f.AddLine(_T(""));
    f.AddLine(_T(""));

    bool written = f.Write(wxTextFileType_None, wxConvUTF8);

    f.Close();

    return written;
}
<|endoftext|>


<commit_before>#include "fake_player.hpp"

#include <ctime>

#include <boost/random/discrete_distribution.hpp>

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/exceptions.hpp>
#include <boost/log/sources/global_logger_storage.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/sources/severity_logger.hpp>

#include "exception.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"

BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(my_logger, boost::log::sources::logger)

namespace Quoridor {

FakePlayer::FakePlayer(std::shared_ptr<Board> board,
        std::shared_ptr<Pawn> pawn)
    : board_(board), pawn_(pawn), goal_nodes_(), gen_()
{
    board_->pawn_goal_nodes(pawn_, &goal_nodes_);
    gen_.seed(static_cast<unsigned int>(std::time(NULL)));
}

FakePlayer::~FakePlayer()
{
}

IMove *FakePlayer::get_move()
{
    boost::random::discrete_distribution<> dist{0.6, 0.6};

    boost::log::sources::logger &lg = my_logger::get();

    if (dist(gen_) == 0) {
        size_t min_path_len = 81;
        std::list<Pos> min_path;
        for (auto end_node : goal_nodes_) {
            std::list<Pos> path;
            if (board_->get_path(pawn_, end_node, &path)) {
                if (min_path_len > path.size()) {
                    min_path_len = path.size();
                    min_path = path;
                }
            }
        }

        if (min_path.size() == 0) {
            throw Exception("all pathes are blocked");
        }

        auto node_it = min_path.begin();
        Pos next_node = *node_it;
        BOOST_LOG_SEV(lg, boost::log::trivial::info) << "moving to "
            << next_node.row() << ":" << next_node.col();
        if (board_->is_occupied(next_node)) {
            // @todo
        }
        return new WalkMove(next_node);
    }
    else {
        boost::random::discrete_distribution<> dist_2{8, 2};
        boost::random::uniform_int_distribution<> dist_9(0, 8);
        boost::random::discrete_distribution<> dist_8{1, 1, 2, 3, 3, 2, 1, 1};
        return new WallMove(Wall(dist_2(gen_), dist_9(gen_), dist_8(gen_), 2));
    }
}

}  /* namespace Quoridor */
<commit_msg>Fix logging in fake_player.cpp<commit_after>#include "fake_player.hpp"

#include <ctime>

#include <boost/random/discrete_distribution.hpp>

#include "walk_move.hpp"
#include "wall_move.hpp"
#include "exception.hpp"
#include "logger.hpp"

static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;

namespace Quoridor {

FakePlayer::FakePlayer(std::shared_ptr<Board> board,
        std::shared_ptr<Pawn> pawn)
    : board_(board), pawn_(pawn), goal_nodes_(), gen_()
{
    board_->pawn_goal_nodes(pawn_, &goal_nodes_);
    gen_.seed(static_cast<unsigned int>(std::time(NULL)));
}

FakePlayer::~FakePlayer()
{
}

IMove *FakePlayer::get_move()
{
    boost::random::discrete_distribution<> dist{0.6, 0.6};

    if (dist(gen_) == 0) {
        size_t min_path_len = 81;
        std::list<Pos> min_path;
        for (auto end_node : goal_nodes_) {
            std::list<Pos> path;
            if (board_->get_path(pawn_, end_node, &path)) {
                if (min_path_len > path.size()) {
                    min_path_len = path.size();
                    min_path = path;
                }
            }
        }

        if (min_path.size() == 0) {
            throw Exception("all pathes are blocked");
        }

        auto node_it = min_path.begin();
        Pos next_node = *node_it;
        BOOST_LOG_SEV(lg, boost::log::trivial::info) << "moving to "
            << next_node.row() << ":" << next_node.col();
        if (board_->is_occupied(next_node)) {
            // @todo
        }
        return new WalkMove(next_node);
    }
    else {
        boost::random::discrete_distribution<> dist_2{8, 2};
        boost::random::uniform_int_distribution<> dist_9(0, 8);
        boost::random::discrete_distribution<> dist_8{1, 1, 2, 3, 3, 2, 1, 1};
        return new WallMove(Wall(dist_2(gen_), dist_9(gen_), dist_8(gen_), 2));
    }
}

}  /* namespace Quoridor */
<|endoftext|>


<commit_before>#include    <cstdlib>
#include    <cmath>
#include    <fstream>
#include    <sstream>
#include    <iostream>
#include    <iomanip>
#include    <string>
#include    <vector>
#include    <algorithm>
#include    <exception>
#include    <sys/time.h>
#include    "modules/htmTree.h"
#include    "modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"

//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
    //// Initializations ---------------------------------------------
    srand48(1234); // Make sure we have reproducability
    check_args(argc);
    Time t, time; // t for global, time for local
    init_time(t);
    Feat F;
    MTL M;

    // Read parameters file //
    F.readInputFile(argv[1]);
    printFile(argv[1]);

    // Read input files for standards, skys and targets.
    // Try to read SS and SF before targets to avoid wasting time if these
    // smaller files can't be read.
    init_time_at(time,"# Read target, SS, SF files",t);
    MTL SStars = read_MTLfile(F.SStarsfile,F,1,0);
    MTL SkyF   = read_MTLfile(F.SkyFfile,  F,0,1);
    MTL Targ   = read_MTLfile(F.Targfile,  F,0,0);
    print_time(time,"# ... took :");

    //combine the three input files
    M=Targ;
    printf(" Target size %d \n",M.size());
    M.insert(M.end(),SStars.begin(),SStars.end());
    printf(" Standard Star size %d \n",M.size());
    M.insert(M.end(),SkyF.begin(),SkyF.end());
    printf(" Sky Fiber size %d \n",M.size());

    F.Ngal = M.size();
    assign_priority_class(M);
    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        if(!M[i].SS&&!M[i].SF){
            count_class[M[i].priority_class]+=1;
        }
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }
    print_time(time,"# ... took :");

    // fiber positioners
    PP pp;
    pp.read_fiber_positions(F);
    F.Nfiber = pp.fp.size()/2;
    F.Npetal = max(pp.spectrom)+1;
    F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
    pp.get_neighbors(F);
    pp.compute_fibsofsp(F);

    //P is original list of plates
    Plates P = read_plate_centers(F);
    F.Nplate=P.size();
    printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

    // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
    F.cb = create_cb(); // cb=central body
    F.fh = create_fh(); // fh=fiber holder

    //// Collect available galaxies <-> tilefibers --------------------
    // HTM Tree of galaxies
    const double MinTreeSize = 0.01;
    init_time_at(time,"# Start building HTM tree",t);
    htmTree<struct target> T(M,MinTreeSize);
    print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect galaxies at ",t);

    // For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
    collect_galaxies_for_all(M,T,P,pp,F);
    print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect available tile-fibers at",t);

    // For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
    collect_available_tilefibers(M,P,F);

    //results_on_inputs("doc/figs/",G,P,F,true);

    //// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
    Assignment A(M,F);
    // Make a plan ----------------------------------------------------
    print_time(t,"# Start assignment at : ");
    simple_assign(M,P,pp,F,A);

    //check to see if there are tiles with no galaxies
    //need to keep mapping of old tile list to new tile list
    //and inverse map
    A.inv_order=initList(F.Nplate,-1);
    int inv_count=0;
    for (int j=0;j<F.Nplate ;++j){

        bool not_done=true;
        for(int k=0;k<F.Nfiber && not_done;++k){
            if(A.TF[j][k]!=-1){
                A.suborder.push_back(j);//suborder[jused] is jused-th used plate
                not_done=false;
                A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
                inv_count++;
            }
        }
    }
    F.NUsedplate=A.suborder.size();
    printf(" Plates actually used %d \n",F.NUsedplate);
    //for(int i=0;i<F.NUsedplate;i++)printf(" jused  %d  j  %d\n",i,A.suborder[i]);

    // Smooth out distribution of free fibers, and increase the number of assignments

    for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
    for (int i=0; i<3; i++) {
        improve(M,P,pp,F,A,0);
        redistribute_tf(M,P,pp,F,A,0);
    }
    init_time_at(time,"# assign SS and SF ",t);

    //try assigning SF and SS before real time assignment
    for (int jused=0;jused<F.NUsedplate;++jused){

        int j=A.suborder[jused];
        assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
        assign_unused(j,M,P,pp,F,A);
    }

    // Results -------------------------------------------------------*/
    std::vector <int> total_used_by_class(M.priority_list.size(),0);
    int total_used_SS=0;
    int total_used_SF=0;
    for (int jused=0;jused<F.NUsedplate;++jused){
        std::vector <int> used_by_class(M.priority_list.size(),0);
        int used_SS=0;
        int used_SF=0;
        int j=A.suborder[jused];
        for(int k=0;k<F.Nfiber;++k){
            int g=A.TF[j][k];
            if(g!=-1){
                if(M[g].SS){
                    total_used_SS++;
                    used_SS++;
                    }
                    else if(M[g].SF){
                        used_SF++;
                        total_used_SF++;
                    }
                    else{
                        used_by_class[M[g].priority_class]++;
                        total_used_by_class[M[g].priority_class]++;
                    }
            }
        }
       /* printf(" plate jused %5d j %5d  SS   %4d    SF   %4d",jused,j,used_SS,used_SF);
        for (int pr=0;pr<M.priority_list.size();++pr){
            printf(" class %2d   %5d",pr,used_by_class[pr]);
        }
        printf("\n");
        */
    }
    init_time_at(time,"# count SS and SF ",t);
    printf(" Totals SS   %4d    SF   %4d",total_used_SS,total_used_SF);
    std::cout.flush();
    for (int pr=0;pr<M.priority_list.size();++pr){
        printf(" class %2d   %5d",pr,total_used_by_class[pr]);
        std::cout.flush();
    }
    printf("\n");
    init_time_at(time,"# print txt files ",t);
    if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
        }
    init_time_at(time,"# print fits files ",t);
    if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        fa_write(j,F.outDir,M,P,pp,F,A); // Write output
    }

  print_time(t,"# Finished !... in");

  return(0);
}
<commit_msg>debugging fiberassign<commit_after>#include    <cstdlib>
#include    <cmath>
#include    <fstream>
#include    <sstream>
#include    <iostream>
#include    <iomanip>
#include    <string>
#include    <vector>
#include    <algorithm>
#include    <exception>
#include    <sys/time.h>
#include    "modules/htmTree.h"
#include    "modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"

//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
    //// Initializations ---------------------------------------------
    srand48(1234); // Make sure we have reproducability
    check_args(argc);
    Time t, time; // t for global, time for local
    init_time(t);
    Feat F;
    MTL M;

    // Read parameters file //
    F.readInputFile(argv[1]);
    printFile(argv[1]);
    // debug failure to assign any fibers 8/22/16
    FILE * FB;
    str s="/project/projectdirs/desi/users/rncahn/output.txt";
    FB=fopen(s.c_str(),"w");
    fprintf(FB,"test of output.txt\n");

    // Read input files for standards, skys and targets.
    // Try to read SS and SF before targets to avoid wasting time if these
    // smaller files can't be read.
    init_time_at(time,"# Read target, SS, SF files",t);
    MTL SStars = read_MTLfile(F.SStarsfile,F,1,0);
    MTL SkyF   = read_MTLfile(F.SkyFfile,  F,0,1);
    MTL Targ   = read_MTLfile(F.Targfile,  F,0,0);
    print_time(time,"# ... took :");

    //combine the three input files
    M=Targ;
    printf(" Target size %d \n",M.size());
    M.insert(M.end(),SStars.begin(),SStars.end());
    printf(" Standard Star size %d \n",M.size());
    M.insert(M.end(),SkyF.begin(),SkyF.end());
    printf(" Sky Fiber size %d \n",M.size());

    F.Ngal = M.size();
    assign_priority_class(M);
    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        if(!M[i].SS&&!M[i].SF){
            count_class[M[i].priority_class]+=1;
        }
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }
    print_time(time,"# ... took :");

    // fiber positioners
    PP pp;
    pp.read_fiber_positions(F);
    F.Nfiber = pp.fp.size()/2;
    F.Npetal = max(pp.spectrom)+1;
    F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
    pp.get_neighbors(F);
    pp.compute_fibsofsp(F);

    //P is original list of plates
    Plates P = read_plate_centers(F);
    F.Nplate=P.size();
    printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
    fprintf(FB,"# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

    // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
    F.cb = create_cb(); // cb=central body
    F.fh = create_fh(); // fh=fiber holder

    //// Collect available galaxies <-> tilefibers --------------------
    // HTM Tree of galaxies
    const double MinTreeSize = 0.01;
    init_time_at(time,"# Start building HTM tree",t);
    htmTree<struct target> T(M,MinTreeSize);
    print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect galaxies at ",t);

    // For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
    collect_galaxies_for_all(M,T,P,pp,F);
    print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect available tile-fibers at",t);

    // For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
    collect_available_tilefibers(M,P,F);

    //results_on_inputs("doc/figs/",G,P,F,true);

    //// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
    fprintf(FB," Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);

    Assignment A(M,F);
    // Make a plan ----------------------------------------------------
    print_time(t,"# Start assignment at : ");
    simple_assign(M,P,pp,F,A);

    //check to see if there are tiles with no galaxies
    //need to keep mapping of old tile list to new tile list
    //and inverse map
    A.inv_order=initList(F.Nplate,-1);
    int inv_count=0;
    for (int j=0;j<F.Nplate ;++j){

        bool not_done=true;
        for(int k=0;k<F.Nfiber && not_done;++k){
            if(A.TF[j][k]!=-1){
                A.suborder.push_back(j);//suborder[jused] is jused-th used plate
		fprintf(FB," j  %d  k  %d  used jused  %d \n",j,k,inv_count);
                not_done=false;
                A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
                inv_count++;
            }
        }
    }
    F.NUsedplate=A.suborder.size();
    printf(" Plates actually used %d \n",F.NUsedplate);
    fprintf(FB," Plates actually used %d \n",F.NUsedplate);
    for(int i=0;i<F.NUsedplate;i++)fprintf(FB," jused  %d  j  %d\n",i,A.suborder[i]);

    // Smooth out distribution of free fibers, and increase the number of assignments

    for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
    for (int i=0; i<3; i++) {
        improve(M,P,pp,F,A,0);
        redistribute_tf(M,P,pp,F,A,0);
    }
    init_time_at(time,"# assign SS and SF ",t);

    //try assigning SF and SS before real time assignment
    for (int jused=0;jused<F.NUsedplate;++jused){

        int j=A.suborder[jused];
        assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
        assign_unused(j,M,P,pp,F,A);
    }

    // Results -------------------------------------------------------*/
    std::vector <int> total_used_by_class(M.priority_list.size(),0);
    int total_used_SS=0;
    int total_used_SF=0;
    for (int jused=0;jused<F.NUsedplate;++jused){
        std::vector <int> used_by_class(M.priority_list.size(),0);
        int used_SS=0;
        int used_SF=0;
        int j=A.suborder[jused];
        for(int k=0;k<F.Nfiber;++k){
            int g=A.TF[j][k];
            if(g!=-1){
                if(M[g].SS){
                    total_used_SS++;
                    used_SS++;
                    }
                    else if(M[g].SF){
                        used_SF++;
                        total_used_SF++;
                    }
                    else{
                        used_by_class[M[g].priority_class]++;
                        total_used_by_class[M[g].priority_class]++;
                    }
            }
        }
       /* printf(" plate jused %5d j %5d  SS   %4d    SF   %4d",jused,j,used_SS,used_SF);
        for (int pr=0;pr<M.priority_list.size();++pr){
            printf(" class %2d   %5d",pr,used_by_class[pr]);
        }
        printf("\n");
        */
    }
    init_time_at(time,"# count SS and SF ",t);
    printf(" Totals SS   %4d    SF   %4d",total_used_SS,total_used_SF);
    std::cout.flush();
    for (int pr=0;pr<M.priority_list.size();++pr){
        printf(" class %2d   %5d",pr,total_used_by_class[pr]);
        std::cout.flush();
    }

    printf("\n");
    init_time_at(time,"# print txt files ",t);
    if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
        }
    init_time_at(time,"# print fits files ",t);
    if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        fa_write(j,F.outDir,M,P,pp,F,A); // Write output
    }

  print_time(t,"# Finished !... in");

  return(0);
}
<|endoftext|>