<commit_before>#pragma once
#ifndef OPENGM_GRAPHICALMODEL_MANIPULATOR_HXX
#define OPENGM_GRAPHICALMODEL_MANIPULATOR_HXX

#include <exception>
#include <set>
#include <vector>
#include <queue>

#include "opengm/graphicalmodel/graphicalmodel.hxx"
#include "opengm/graphicalmodel/space/discretespace.hxx"
#include "opengm/functions/view.hxx"
#include "opengm/functions/view_fix_variables_function.hxx"
#include "opengm/functions/constant.hxx"
#include <opengm/utilities/metaprogramming.hxx>

namespace opengm {

/// \brief GraphicalModelManipulator
///
/// Invariant: Order of the variables in the modified subgraphs is the same as in the original graph
///
/// \ingroup graphical_models
   template<class GM>
   class GraphicalModelManipulator
   {
   public:
      typedef GM                             OGM;
      typedef typename GM::SpaceType         OSpaceType;
      typedef typename GM::IndexType         IndexType;
      typedef typename GM::LabelType         LabelType;
      typedef typename GM::ValueType         ValueType;

      typedef typename opengm::DiscreteSpace<IndexType, LabelType> MSpaceType;
      typedef typename meta::TypeListGenerator< ViewFixVariablesFunction<GM>, ViewFunction<GM>, ConstantFunction<ValueType, IndexType, LabelType> >::type MFunctionTypeList;
      typedef GraphicalModel<ValueType, typename GM::OperatorType, MFunctionTypeList, MSpaceType> MGM;

      GraphicalModelManipulator(GM& gm);

      //BuildModels
      void buildModifiedModel();
      void buildModifiedSubModels();

      //Get Models
      const OGM& getOriginalModel() const;
      const MGM& getModifiedModel() const;
      const MGM& getModifiedSubModel(size_t) const;

      //GetInfo
      size_t numberOfSubmodels() const;
      void modifiedState2OriginalState(const std::vector<LabelType>&, std::vector<LabelType>&) const;
      void modifiedSubStates2OriginalState(const std::vector<std::vector<LabelType> >&, std::vector<LabelType>&) const;
      bool isLocked() const;

      //Manipulation
      void fixVariable(const typename GM::IndexType, const typename GM::LabelType);
      void freeVariable(const  typename GM::IndexType);
      void freeAllVariables();
      void unlock();
      void lock();

   private:
      void expand(IndexType, IndexType,  std::vector<bool>&);

      //General Members
      const OGM& gm_;                            // original model
      bool locked_;                              // if true no more manipulation is allowed
      std::vector<bool> fixVariable_;            // flag if variables are fixed
      std::vector<LabelType> fixVariableLabel_;  // label of fixed variables (otherwise undefined)

      //Modified Model
      bool validModel_;                          // true if modified model is valid
      MGM mgm_;                                  // modified model

      //Modified SubModels
      bool validSubModels_;                      // true if themodified submodels are valid
      std::vector<MGM> submodels_;               // modified submodels
      std::vector<IndexType> var2subProblem_;    // subproblem of variable (for fixed variables undefined)
   };

   template<class GM>
   GraphicalModelManipulator<GM>::GraphicalModelManipulator(GM& gm)
      : gm_(gm), locked_(false),  validModel_(false), validSubModels_(false),
        fixVariable_(std::vector<bool>(gm.numberOfVariables(),false)),
        fixVariableLabel_(std::vector<LabelType>(gm.numberOfVariables(),0)),
        var2subProblem_(std::vector<LabelType>(gm.numberOfVariables(),0))
   {
      return;
   }

/// \brief return the original graphical model
   template<class GM>
   inline const typename GraphicalModelManipulator<GM>::OGM &
   GraphicalModelManipulator<GM>::getOriginalModel() const
   {
      return gm_;
   }

/// \brief return the modified graphical model
   template<class GM>
   inline const typename GraphicalModelManipulator<GM>::MGM &
   GraphicalModelManipulator<GM>::getModifiedModel() const
   {
      OPENGM_ASSERT(isLocked() && validModel_);
      return mgm_;
   }

/// \brief return the i-th modified sub graphical model
   template<class GM>
   inline const typename GraphicalModelManipulator<GM>::MGM &
   GraphicalModelManipulator<GM>::getModifiedSubModel(size_t i) const
   {
      OPENGM_ASSERT(isLocked() && validSubModels_);
      OPENGM_ASSERT(i < submodels_.size());
      return submodels_[i];
   }

/// \brief return the number of submodels
   template<class GM>
   size_t GraphicalModelManipulator<GM>::numberOfSubmodels() const
   {
      OPENGM_ASSERT(isLocked());
      return submodels_.size();
   }

/// \brief unlock model
   template<class GM>
   void GraphicalModelManipulator<GM>::unlock()
   {
      locked_=false;
      validSubModels_=false;
      validModel_=false;
      submodels_.clear();
      freeAllVariables();
   }

/// \brief lock model
   template<class GM>
   void GraphicalModelManipulator<GM>::lock()
   {
      locked_=true;
   }

/// \brief return true if model is locked
   template<class GM>
   bool GraphicalModelManipulator<GM>::isLocked() const
   {
      return locked_;
   }

/// \brief fix label for variable
   template<class GM>
   void GraphicalModelManipulator<GM>::fixVariable(const typename GM::IndexType var, const typename GM::LabelType l)
   {
      OPENGM_ASSERT(!isLocked());
      if(!isLocked()){
         fixVariable_[var]=true;
         fixVariableLabel_[var]=l;
      }
   }

/// \brief remove fixed label for variable
   template<class GM>
   void GraphicalModelManipulator<GM>::freeVariable(const  typename GM::IndexType var)
   {
      OPENGM_ASSERT(!isLocked());
      if(!isLocked()){
         fixVariable_[var]=false;
      }
   }

/// \brief remove fixed label for all variable
   template<class GM>
   void GraphicalModelManipulator<GM>::freeAllVariables()
   {
      OPENGM_ASSERT(!isLocked())

         if(!isLocked()){
         for(IndexType var=0; var<fixVariable_.size(); ++var)
            fixVariable_[var]=false;
      }
   }

/// \brief transforming label of the modified to the labeling of the original problem
   template<class GM>
   void GraphicalModelManipulator<GM>::modifiedState2OriginalState(const std::vector<LabelType>& ml, std::vector<LabelType>& ol) const
   {
      OPENGM_ASSERT(isLocked());
      OPENGM_ASSERT(ml.size()==mgm_.numberOfVariables());

      if(isLocked() && ml.size()==mgm_.numberOfVariables()){
         ol.resize(gm_.numberOfVariables());
         size_t c = 0;
         for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
            if(fixVariable_[var]){
               ol[var] = fixVariableLabel_[var];
            }else{
               ol[var] = ml[c++];
            }
         }
      }
   }

/// \brief transforming label of the modified subproblems to the labeling of the original problem
   template<class GM>
   void GraphicalModelManipulator<GM>::modifiedSubStates2OriginalState(const std::vector<std::vector<LabelType> >& subconf, std::vector<LabelType>& conf) const
   {
      conf.resize(gm_.numberOfVariables());
      std::vector<IndexType> varCount(submodels_.size(),0);
      for(IndexType i=0;i<submodels_.size(); ++i){
          OPENGM_ASSERT(submodels_[i].numberOfVariables()==subconf[i].size());
      }
      for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
         if(fixVariable_[var]){
            conf[var] = fixVariableLabel_[var];
         }else{
            const IndexType sp=var2subProblem_[var];
            conf[var] = subconf[sp][varCount[sp]++];
         }
      }
   }

/// \brief build modified model
   template<class GM>
   void
   GraphicalModelManipulator<GM>::buildModifiedModel()
   {
      locked_ = true;
      validModel_ = true;
      IndexType numberOfVariables = 0;
      std::vector<IndexType> varMap(gm_.numberOfVariables(),0);
      for(IndexType var=0; var<gm_.numberOfVariables();++var){
         if(fixVariable_[var]==false){
            varMap[var] = numberOfVariables++;
         }
      }
      std::vector<LabelType> shape(numberOfVariables,0);
      for(IndexType var=0; var<gm_.numberOfVariables();++var){
         if(fixVariable_[var]==false){
            shape[varMap[var]] = gm_.numberOfLabels(var);
         }
      }
      MSpaceType space(shape.begin(),shape.end());
      mgm_ = MGM(space);

      std::vector<PositionAndLabel<IndexType,LabelType> > fixedVars;
      std::vector<IndexType> MVars;

      ValueType constant;
      GM::OperatorType::neutral(constant);
      for(IndexType f=0; f<gm_.numberOfFactors();++f){
         fixedVars.resize(0);
         MVars.resize(0);
         for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
            const IndexType var = gm_[f].variableIndex(i);
            if(fixVariable_[var]){
               fixedVars.push_back(PositionAndLabel<IndexType,LabelType>(i,fixVariableLabel_[var]));
            }else{
               MVars.push_back(varMap[var]);
            }
         }
         if(fixedVars.size()==0){//non fixed
            const ViewFunction<GM> func(gm_[f]);
            mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.end());
         }else if(fixedVars.size()==gm_[f].numberOfVariables()){//all fixed
            std::vector<LabelType> fixedStates(gm_[f].numberOfVariables(),0);
            for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
               fixedStates[i]=fixVariableLabel_[ gm_[f].variableIndex(i)];
            }
            GM::OperatorType::op(gm_[f](fixedStates.begin()),constant);
         }else{
            const ViewFixVariablesFunction<GM> func(gm_[f], fixedVars);
            mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.end());
         }
      }
      {
         LabelType temp;
         ConstantFunction<ValueType, IndexType, LabelType> func(&temp, &temp, constant);
         mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.begin());
      }
   }

/// \brief build modified sub-models
   template<class GM>
   void
   GraphicalModelManipulator<GM>::buildModifiedSubModels()
   {
      locked_ = true;
      validSubModels_ = true;

      //Find Connected Components
      std::vector<bool> closedVar   = fixVariable_;
      IndexType numberOfSubproblems = 0;
      for(IndexType var=0 ; var<gm_.numberOfVariables(); ++var){
         if(closedVar[var])
            continue;
         else{
            expand(var, numberOfSubproblems, closedVar);
         }
         ++numberOfSubproblems;
      }

      submodels_.resize(numberOfSubproblems);
      std::vector<IndexType> numberOfVariables(numberOfSubproblems,0);
      std::vector<IndexType> varMap(gm_.numberOfVariables(),0);
      for(IndexType var=0; var<gm_.numberOfVariables();++var){
         if(fixVariable_[var]==false){
            varMap[var] = numberOfVariables[var2subProblem_[var]]++;
         }
      }
      std::vector<std::vector<LabelType> > shape(numberOfSubproblems);
      for (size_t i=0; i<numberOfSubproblems; ++i){
         shape[i] = std::vector<LabelType>(numberOfVariables[i],0);
      }
      for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
         if(fixVariable_[var]==false){
            shape[var2subProblem_[var]][varMap[var]] = gm_.numberOfLabels(var);
         }
      }
      for (size_t i=0; i<numberOfSubproblems; ++i){
         MSpaceType space(shape[i].begin(),shape[i].end());
         submodels_[i] = MGM(space);
      }

      std::vector<PositionAndLabel<IndexType,LabelType> > fixedVars;
      std::vector<IndexType> MVars;

      ValueType constant;
      GM::OperatorType::neutral(constant);

      for(IndexType f=0; f<gm_.numberOfFactors();++f){
         IndexType subproblem = 0;
         fixedVars.resize(0);
         MVars.resize(0);
         for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
            const IndexType var = gm_[f].variableIndex(i);
            if(fixVariable_[var]){
               fixedVars.push_back(PositionAndLabel<IndexType,LabelType>(i,fixVariableLabel_[var]));
            }else{
               MVars.push_back(varMap[var]);
               subproblem = var2subProblem_[var];
            }
         }
         if(MVars.size()==0){ //constant, all fixed
            std::vector<LabelType> fixedStates(gm_[f].numberOfVariables(),0);
            for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
               fixedStates[i]=fixVariableLabel_[ gm_[f].variableIndex(i)];
            }
            GM::OperatorType::op(gm_[f](fixedStates.begin()),constant);
         }
         else if(fixedVars.size()==0){//non fixed
            const ViewFunction<GM> func(gm_[f]);
            submodels_[subproblem].addFactor(submodels_[subproblem].addFunction(func),MVars.begin(), MVars.end());
         }else{
            const ViewFixVariablesFunction<GM> func(gm_[f], fixedVars);
             submodels_[subproblem].addFactor(submodels_[subproblem].addFunction(func),MVars.begin(), MVars.end());
         }
      }
      {
         LabelType temp;
         ConstantFunction<ValueType, IndexType, LabelType> func(&temp, &temp, constant);
         submodels_[0].addFactor( submodels_[0].addFunction(func),MVars.begin(), MVars.begin());
      }
   }

////////////////////
// Private Methods
////////////////////
   template<class GM>
   void
   GraphicalModelManipulator<GM>::expand(IndexType var, IndexType CCN,  std::vector<bool>& closedVar)
   {
      if(closedVar[var])
         return;
      else{
         closedVar[var]       = true;
         var2subProblem_[var] = CCN;
         for( typename GM::ConstFactorIterator itf = gm_.factorsOfVariableBegin(var); itf!=gm_.factorsOfVariableEnd(var); ++itf){
            for( typename  GM::ConstVariableIterator itv = gm_.variablesOfFactorBegin(*itf); itv!=gm_.variablesOfFactorEnd(*itf);++itv){
               expand(*itv, CCN, closedVar);
            }
         }
      }
    }

} //namespace opengm

#endif // #ifndef OPENGM_GRAPHICALMODEL_HXX
<commit_msg>fixed minor bug in constructor... a const GM & gm should be passed instead of GM &gm<commit_after>#pragma once
#ifndef OPENGM_GRAPHICALMODEL_MANIPULATOR_HXX
#define OPENGM_GRAPHICALMODEL_MANIPULATOR_HXX

#include <exception>
#include <set>
#include <vector>
#include <queue>

#include "opengm/graphicalmodel/graphicalmodel.hxx"
#include "opengm/graphicalmodel/space/discretespace.hxx"
#include "opengm/functions/view.hxx"
#include "opengm/functions/view_fix_variables_function.hxx"
#include "opengm/functions/constant.hxx"
#include <opengm/utilities/metaprogramming.hxx>

namespace opengm {

/// \brief GraphicalModelManipulator
///
/// Invariant: Order of the variables in the modified subgraphs is the same as in the original graph
///
/// \ingroup graphical_models
   template<class GM>
   class GraphicalModelManipulator
   {
   public:
      typedef GM                             OGM;
      typedef typename GM::SpaceType         OSpaceType;
      typedef typename GM::IndexType         IndexType;
      typedef typename GM::LabelType         LabelType;
      typedef typename GM::ValueType         ValueType;

      typedef typename opengm::DiscreteSpace<IndexType, LabelType> MSpaceType;
      typedef typename meta::TypeListGenerator< ViewFixVariablesFunction<GM>, ViewFunction<GM>, ConstantFunction<ValueType, IndexType, LabelType> >::type MFunctionTypeList;
      typedef GraphicalModel<ValueType, typename GM::OperatorType, MFunctionTypeList, MSpaceType> MGM;

      GraphicalModelManipulator(const GM& gm);

      //BuildModels
      void buildModifiedModel();
      void buildModifiedSubModels();

      //Get Models
      const OGM& getOriginalModel() const;
      const MGM& getModifiedModel() const;
      const MGM& getModifiedSubModel(size_t) const;

      //GetInfo
      size_t numberOfSubmodels() const;
      void modifiedState2OriginalState(const std::vector<LabelType>&, std::vector<LabelType>&) const;
      void modifiedSubStates2OriginalState(const std::vector<std::vector<LabelType> >&, std::vector<LabelType>&) const;
      bool isLocked() const;

      //Manipulation
      void fixVariable(const typename GM::IndexType, const typename GM::LabelType);
      void freeVariable(const  typename GM::IndexType);
      void freeAllVariables();
      void unlock();
      void lock();

   private:
      void expand(IndexType, IndexType,  std::vector<bool>&);

      //General Members
      const OGM& gm_;                            // original model
      bool locked_;                              // if true no more manipulation is allowed
      std::vector<bool> fixVariable_;            // flag if variables are fixed
      std::vector<LabelType> fixVariableLabel_;  // label of fixed variables (otherwise undefined)

      //Modified Model
      bool validModel_;                          // true if modified model is valid
      MGM mgm_;                                  // modified model

      //Modified SubModels
      bool validSubModels_;                      // true if themodified submodels are valid
      std::vector<MGM> submodels_;               // modified submodels
      std::vector<IndexType> var2subProblem_;    // subproblem of variable (for fixed variables undefined)
   };

   template<class GM>
   GraphicalModelManipulator<GM>::GraphicalModelManipulator(const GM& gm)
      : gm_(gm), locked_(false),  validModel_(false), validSubModels_(false),
        fixVariable_(std::vector<bool>(gm.numberOfVariables(),false)),
        fixVariableLabel_(std::vector<LabelType>(gm.numberOfVariables(),0)),
        var2subProblem_(std::vector<LabelType>(gm.numberOfVariables(),0))
   {
      return;
   }

/// \brief return the original graphical model
   template<class GM>
   inline const typename GraphicalModelManipulator<GM>::OGM &
   GraphicalModelManipulator<GM>::getOriginalModel() const
   {
      return gm_;
   }

/// \brief return the modified graphical model
   template<class GM>
   inline const typename GraphicalModelManipulator<GM>::MGM &
   GraphicalModelManipulator<GM>::getModifiedModel() const
   {
      OPENGM_ASSERT(isLocked() && validModel_);
      return mgm_;
   }

/// \brief return the i-th modified sub graphical model
   template<class GM>
   inline const typename GraphicalModelManipulator<GM>::MGM &
   GraphicalModelManipulator<GM>::getModifiedSubModel(size_t i) const
   {
      OPENGM_ASSERT(isLocked() && validSubModels_);
      OPENGM_ASSERT(i < submodels_.size());
      return submodels_[i];
   }

/// \brief return the number of submodels
   template<class GM>
   size_t GraphicalModelManipulator<GM>::numberOfSubmodels() const
   {
      OPENGM_ASSERT(isLocked());
      return submodels_.size();
   }

/// \brief unlock model
   template<class GM>
   void GraphicalModelManipulator<GM>::unlock()
   {
      locked_=false;
      validSubModels_=false;
      validModel_=false;
      submodels_.clear();
      freeAllVariables();
   }

/// \brief lock model
   template<class GM>
   void GraphicalModelManipulator<GM>::lock()
   {
      locked_=true;
   }

/// \brief return true if model is locked
   template<class GM>
   bool GraphicalModelManipulator<GM>::isLocked() const
   {
      return locked_;
   }

/// \brief fix label for variable
   template<class GM>
   void GraphicalModelManipulator<GM>::fixVariable(const typename GM::IndexType var, const typename GM::LabelType l)
   {
      OPENGM_ASSERT(!isLocked());
      if(!isLocked()){
         fixVariable_[var]=true;
         fixVariableLabel_[var]=l;
      }
   }

/// \brief remove fixed label for variable
   template<class GM>
   void GraphicalModelManipulator<GM>::freeVariable(const  typename GM::IndexType var)
   {
      OPENGM_ASSERT(!isLocked());
      if(!isLocked()){
         fixVariable_[var]=false;
      }
   }

/// \brief remove fixed label for all variable
   template<class GM>
   void GraphicalModelManipulator<GM>::freeAllVariables()
   {
      OPENGM_ASSERT(!isLocked())

         if(!isLocked()){
         for(IndexType var=0; var<fixVariable_.size(); ++var)
            fixVariable_[var]=false;
      }
   }

/// \brief transforming label of the modified to the labeling of the original problem
   template<class GM>
   void GraphicalModelManipulator<GM>::modifiedState2OriginalState(const std::vector<LabelType>& ml, std::vector<LabelType>& ol) const
   {
      OPENGM_ASSERT(isLocked());
      OPENGM_ASSERT(ml.size()==mgm_.numberOfVariables());

      if(isLocked() && ml.size()==mgm_.numberOfVariables()){
         ol.resize(gm_.numberOfVariables());
         size_t c = 0;
         for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
            if(fixVariable_[var]){
               ol[var] = fixVariableLabel_[var];
            }else{
               ol[var] = ml[c++];
            }
         }
      }
   }

/// \brief transforming label of the modified subproblems to the labeling of the original problem
   template<class GM>
   void GraphicalModelManipulator<GM>::modifiedSubStates2OriginalState(const std::vector<std::vector<LabelType> >& subconf, std::vector<LabelType>& conf) const
   {
      conf.resize(gm_.numberOfVariables());
      std::vector<IndexType> varCount(submodels_.size(),0);
      for(IndexType i=0;i<submodels_.size(); ++i){
          OPENGM_ASSERT(submodels_[i].numberOfVariables()==subconf[i].size());
      }
      for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
         if(fixVariable_[var]){
            conf[var] = fixVariableLabel_[var];
         }else{
            const IndexType sp=var2subProblem_[var];
            conf[var] = subconf[sp][varCount[sp]++];
         }
      }
   }

/// \brief build modified model
   template<class GM>
   void
   GraphicalModelManipulator<GM>::buildModifiedModel()
   {
      locked_ = true;
      validModel_ = true;
      IndexType numberOfVariables = 0;
      std::vector<IndexType> varMap(gm_.numberOfVariables(),0);
      for(IndexType var=0; var<gm_.numberOfVariables();++var){
         if(fixVariable_[var]==false){
            varMap[var] = numberOfVariables++;
         }
      }
      std::vector<LabelType> shape(numberOfVariables,0);
      for(IndexType var=0; var<gm_.numberOfVariables();++var){
         if(fixVariable_[var]==false){
            shape[varMap[var]] = gm_.numberOfLabels(var);
         }
      }
      MSpaceType space(shape.begin(),shape.end());
      mgm_ = MGM(space);

      std::vector<PositionAndLabel<IndexType,LabelType> > fixedVars;
      std::vector<IndexType> MVars;

      ValueType constant;
      GM::OperatorType::neutral(constant);
      for(IndexType f=0; f<gm_.numberOfFactors();++f){
         fixedVars.resize(0);
         MVars.resize(0);
         for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
            const IndexType var = gm_[f].variableIndex(i);
            if(fixVariable_[var]){
               fixedVars.push_back(PositionAndLabel<IndexType,LabelType>(i,fixVariableLabel_[var]));
            }else{
               MVars.push_back(varMap[var]);
            }
         }
         if(fixedVars.size()==0){//non fixed
            const ViewFunction<GM> func(gm_[f]);
            mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.end());
         }else if(fixedVars.size()==gm_[f].numberOfVariables()){//all fixed
            std::vector<LabelType> fixedStates(gm_[f].numberOfVariables(),0);
            for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
               fixedStates[i]=fixVariableLabel_[ gm_[f].variableIndex(i)];
            }
            GM::OperatorType::op(gm_[f](fixedStates.begin()),constant);
         }else{
            const ViewFixVariablesFunction<GM> func(gm_[f], fixedVars);
            mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.end());
         }
      }
      {
         LabelType temp;
         ConstantFunction<ValueType, IndexType, LabelType> func(&temp, &temp, constant);
         mgm_.addFactor(mgm_.addFunction(func),MVars.begin(), MVars.begin());
      }
   }

/// \brief build modified sub-models
   template<class GM>
   void
   GraphicalModelManipulator<GM>::buildModifiedSubModels()
   {
      locked_ = true;
      validSubModels_ = true;

      //Find Connected Components
      std::vector<bool> closedVar   = fixVariable_;
      IndexType numberOfSubproblems = 0;
      for(IndexType var=0 ; var<gm_.numberOfVariables(); ++var){
         if(closedVar[var])
            continue;
         else{
            expand(var, numberOfSubproblems, closedVar);
         }
         ++numberOfSubproblems;
      }

      submodels_.resize(numberOfSubproblems);
      std::vector<IndexType> numberOfVariables(numberOfSubproblems,0);
      std::vector<IndexType> varMap(gm_.numberOfVariables(),0);
      for(IndexType var=0; var<gm_.numberOfVariables();++var){
         if(fixVariable_[var]==false){
            varMap[var] = numberOfVariables[var2subProblem_[var]]++;
         }
      }
      std::vector<std::vector<LabelType> > shape(numberOfSubproblems);
      for (size_t i=0; i<numberOfSubproblems; ++i){
         shape[i] = std::vector<LabelType>(numberOfVariables[i],0);
      }
      for(IndexType var=0; var<gm_.numberOfVariables(); ++var){
         if(fixVariable_[var]==false){
            shape[var2subProblem_[var]][varMap[var]] = gm_.numberOfLabels(var);
         }
      }
      for (size_t i=0; i<numberOfSubproblems; ++i){
         MSpaceType space(shape[i].begin(),shape[i].end());
         submodels_[i] = MGM(space);
      }

      std::vector<PositionAndLabel<IndexType,LabelType> > fixedVars;
      std::vector<IndexType> MVars;

      ValueType constant;
      GM::OperatorType::neutral(constant);

      for(IndexType f=0; f<gm_.numberOfFactors();++f){
         IndexType subproblem = 0;
         fixedVars.resize(0);
         MVars.resize(0);
         for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
            const IndexType var = gm_[f].variableIndex(i);
            if(fixVariable_[var]){
               fixedVars.push_back(PositionAndLabel<IndexType,LabelType>(i,fixVariableLabel_[var]));
            }else{
               MVars.push_back(varMap[var]);
               subproblem = var2subProblem_[var];
            }
         }
         if(MVars.size()==0){ //constant, all fixed
            std::vector<LabelType> fixedStates(gm_[f].numberOfVariables(),0);
            for(IndexType i=0; i<gm_[f].numberOfVariables(); ++i){
               fixedStates[i]=fixVariableLabel_[ gm_[f].variableIndex(i)];
            }
            GM::OperatorType::op(gm_[f](fixedStates.begin()),constant);
         }
         else if(fixedVars.size()==0){//non fixed
            const ViewFunction<GM> func(gm_[f]);
            submodels_[subproblem].addFactor(submodels_[subproblem].addFunction(func),MVars.begin(), MVars.end());
         }else{
            const ViewFixVariablesFunction<GM> func(gm_[f], fixedVars);
             submodels_[subproblem].addFactor(submodels_[subproblem].addFunction(func),MVars.begin(), MVars.end());
         }
      }
      {
         LabelType temp;
         ConstantFunction<ValueType, IndexType, LabelType> func(&temp, &temp, constant);
         submodels_[0].addFactor( submodels_[0].addFunction(func),MVars.begin(), MVars.begin());
      }
   }

////////////////////
// Private Methods
////////////////////
   template<class GM>
   void
   GraphicalModelManipulator<GM>::expand(IndexType var, IndexType CCN,  std::vector<bool>& closedVar)
   {
      if(closedVar[var])
         return;
      else{
         closedVar[var]       = true;
         var2subProblem_[var] = CCN;
         for( typename GM::ConstFactorIterator itf = gm_.factorsOfVariableBegin(var); itf!=gm_.factorsOfVariableEnd(var); ++itf){
            for( typename  GM::ConstVariableIterator itv = gm_.variablesOfFactorBegin(*itf); itv!=gm_.variablesOfFactorEnd(*itf);++itv){
               expand(*itv, CCN, closedVar);
            }
         }
      }
    }

} //namespace opengm

#endif // #ifndef OPENGM_GRAPHICALMODEL_HXX
<|endoftext|>


<commit_before>/*
 ============================================================================
 Author     : Alexey Tikhvinsky
 Copyright  : Copyright (C) 2011 Rhomobile (http://www.rhomobile.com).
              All rights reserved.

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ============================================================================
 */

#include <android/native_activity.h>

#include "rhodes/JNIRhodes.h"

RHO_GLOBAL void delete_files_in_folder(const char *szFolderPath)
{
//    JNIEnv *env = jnienv();
//    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
//    if (!cls) return;
//    jmethodID mid = getJNIClassStaticMethod(env, cls, "deleteFilesInFolder", "(Ljava/lang/String;)V");
//    if (!mid) return;
//    jhstring objFolderPath = rho_cast<jhstring>(szFolderPath);
//    env->CallStaticVoidMethod(cls, mid, objFolderPath.get());
}

RHO_GLOBAL rho::String rho_sysimpl_get_phone_id()
{
    return "";
}

RHO_GLOBAL void rho_free_callbackdata(void* pData)
{
}

RHO_GLOBAL int rho_net_ping_network(const char* szHost)
{
    return 1;
}
<commit_msg>Rhosync-client-Java: fix build.<commit_after>/*
 ============================================================================
 Author     : Alexey Tikhvinsky
 Copyright  : Copyright (C) 2011 Rhomobile (http://www.rhomobile.com).
              All rights reserved.

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ============================================================================
 */

#include <android/native_activity.h>

#include "rhodes/JNIRhodes.h"

RHO_GLOBAL void delete_files_in_folder(const char *szFolderPath)
{
//    JNIEnv *env = jnienv();
//    jclass cls = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE);
//    if (!cls) return;
//    jmethodID mid = getJNIClassStaticMethod(env, cls, "deleteFilesInFolder", "(Ljava/lang/String;)V");
//    if (!mid) return;
//    jhstring objFolderPath = rho_cast<jhstring>(szFolderPath);
//    env->CallStaticVoidMethod(cls, mid, objFolderPath.get());
}

rho::String rho_sysimpl_get_phone_id()
{
    return "";
}

RHO_GLOBAL void rho_free_callbackdata(void* pData)
{
}

RHO_GLOBAL int rho_net_ping_network(const char* szHost)
{
    return 1;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012, Steinwurf ApS
// All rights reserved.
//
// Redistribution and use 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 Steinwurf ApS 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 Steinwurf ApS 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 <gtest/gtest.h>

#include <sak/buffer.hpp>

TEST(TestBuffer, construct)
{
    sak::buffer b;
    EXPECT_EQ(0U, b.size());
}

TEST(TestBuffer, resize)
{
    sak::buffer b;
    b.resize(100);
    EXPECT_EQ(100U, b.size());
}

TEST(TestBuffer, resize_and_copy)
{
    sak::buffer b1;
    b1.resize(100);
    EXPECT_EQ(100U, b1.size());

    sak::buffer b2 = b1;
    EXPECT_EQ(100U, b2.size());
}

TEST(TestBuffer, append_to_empty_with_size)
{
    std::vector<uint8_t> data(32);
    EXPECT_EQ(32U, data.size());

    sak::buffer b;
    EXPECT_EQ(0U, b.size());

    b.append(&data[0], static_cast<uint32_t>(data.size()));
    EXPECT_EQ(data.size(), b.size());
}

TEST(TestBuffer, append_to_empty_with_pointers)
{
    std::vector<uint8_t> data(32);
    EXPECT_EQ(32U, data.size());

    sak::buffer b;
    EXPECT_EQ(b.size(), 0U);

    b.append(&data[0], &data[0] + data.size());
    EXPECT_EQ(b.size(), data.size());
}

TEST(TestBuffer, append_to_empty_with_storage)
{
    std::vector<uint8_t> data(32);
    EXPECT_EQ(32U, data.size());

    sak::buffer b;
    EXPECT_EQ(b.size(), 0U);

    b.append(sak::storage(data));
    EXPECT_EQ(b.size(), data.size());
}

TEST(TestBuffer, append_to_initialized)
{
    {
        sak::buffer b(10);
        EXPECT_EQ(b.size(), 0U);

        std::vector<uint8_t> data(32, 'x');
        EXPECT_EQ(32U, data.size());
        b.append(&data[0], static_cast<uint32_t>(data.size()));
        EXPECT_EQ(b.size(), data.size());
    }

    {
        sak::buffer b(10);
        EXPECT_EQ(b.size(), 0U);

        std::vector<uint8_t> data(32, 'x');
        EXPECT_EQ(32U, data.size());
        b.append(&data[0], &data[0] + data.size());
        EXPECT_EQ(b.size(), data.size());
    }

    {
        sak::buffer b(10);
        EXPECT_EQ(b.size(), 0U);

        std::vector<uint8_t> data(32, 'x');
        EXPECT_EQ(32U, data.size());
        b.append(sak::storage(data));
        EXPECT_EQ(b.size(), data.size());
    }
}

TEST(TestBuffer, resize_and_clear)
{
    sak::buffer b(100);
    EXPECT_EQ(0U, b.size());
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(10);
    EXPECT_EQ(10U, b.size());
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(101);
    EXPECT_EQ(101U, b.size());
    std::fill_n(b.data(), b.size(), 'x');

    b.clear();
    EXPECT_EQ(0U, b.size());

    b.resize(0);
    EXPECT_EQ(0U, b.size());

    b.resize(102);
    EXPECT_EQ(102U, b.size());
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(0);
    EXPECT_EQ(0U, b.size());

    b.clear();
    EXPECT_EQ(0U, b.size());
}
<commit_msg>Re-order vector constructors<commit_after>// Copyright (c) 2012, Steinwurf ApS
// All rights reserved.
//
// Redistribution and use 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 Steinwurf ApS 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 Steinwurf ApS 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 <gtest/gtest.h>

#include <sak/buffer.hpp>

TEST(TestBuffer, construct)
{
    sak::buffer b;
    EXPECT_EQ(0U, b.size());
}

TEST(TestBuffer, resize)
{
    sak::buffer b;
    b.resize(100);
    EXPECT_EQ(100U, b.size());
}

TEST(TestBuffer, resize_and_copy)
{
    sak::buffer b1;
    b1.resize(100);
    EXPECT_EQ(100U, b1.size());

    sak::buffer b2 = b1;
    EXPECT_EQ(100U, b2.size());
}

TEST(TestBuffer, append_to_empty_with_size)
{
    std::vector<uint8_t> data(32);
    EXPECT_EQ(32U, data.size());

    sak::buffer b;
    EXPECT_EQ(0U, b.size());

    b.append(&data[0], static_cast<uint32_t>(data.size()));
    EXPECT_EQ(data.size(), b.size());
}

TEST(TestBuffer, append_to_empty_with_pointers)
{
    std::vector<uint8_t> data(32);
    EXPECT_EQ(32U, data.size());

    sak::buffer b;
    EXPECT_EQ(b.size(), 0U);

    b.append(&data[0], &data[0] + data.size());
    EXPECT_EQ(b.size(), data.size());
}

TEST(TestBuffer, append_to_empty_with_storage)
{
    std::vector<uint8_t> data(32);
    EXPECT_EQ(32U, data.size());

    sak::buffer b;
    EXPECT_EQ(b.size(), 0U);

    b.append(sak::storage(data));
    EXPECT_EQ(b.size(), data.size());
}

TEST(TestBuffer, append_to_initialized)
{
    {
        std::vector<uint8_t> data(32, 'x');
        EXPECT_EQ(32U, data.size());

        sak::buffer b(10);
        EXPECT_EQ(b.size(), 0U);

        b.append(&data[0], static_cast<uint32_t>(data.size()));
        EXPECT_EQ(b.size(), data.size());
    }

    {
        std::vector<uint8_t> data(32, 'x');
        EXPECT_EQ(32U, data.size());

        sak::buffer b(10);
        EXPECT_EQ(b.size(), 0U);

        b.append(&data[0], &data[0] + data.size());
        EXPECT_EQ(b.size(), data.size());
    }

    {
        std::vector<uint8_t> data(32, 'x');
        EXPECT_EQ(32U, data.size());

        sak::buffer b(10);
        EXPECT_EQ(b.size(), 0U);

        b.append(sak::storage(data));
        EXPECT_EQ(b.size(), data.size());
    }
}

TEST(TestBuffer, resize_and_clear)
{
    sak::buffer b(100);
    EXPECT_EQ(0U, b.size());
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(10);
    EXPECT_EQ(10U, b.size());
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(101);
    EXPECT_EQ(101U, b.size());
    std::fill_n(b.data(), b.size(), 'x');

    b.clear();
    EXPECT_EQ(0U, b.size());

    b.resize(0);
    EXPECT_EQ(0U, b.size());

    b.resize(102);
    EXPECT_EQ(102U, b.size());
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(0);
    EXPECT_EQ(0U, b.size());

    b.clear();
    EXPECT_EQ(0U, b.size());
}
<|endoftext|>


<commit_before>/**
 * @file   measurement_systen_node.cpp
 * @author Izabella Thais Oliveira Gomes
 * @date   23/09/2016
 *
 * @attention Copyright (C) 2014 UnBall Robot Soccer Team
 *
 * @brief Rotate robot position datas acording to camera position in the vision and simulator and publishes that.
 *
*/

#include <vector>
#include <cmath>

#include <ros/ros.h>

#include <unball/VisionMessage.h>
#include <unball/SimulatorMessage.h>
#include <unball/MeasurementSystemMessage.h>
#include <opencv2/opencv.hpp>

const float field_x_length = 1.50;
const float field_y_length = 1.30;

const float camera_x_length = 640;
const float camera_y_length = 480;

void receiveVisionMessage(const unball::VisionMessage::ConstPtr &msg_s);
void rotateAxis();
void convertPixelsToMeters();
void receiveSimulatorMessage(const unball::SimulatorMessage::ConstPtr &msg_v);
void publishMeasurementSystemMessage(ros::Publisher &publisher);
void filter();

unball::MeasurementSystemMessage message;

ros::Publisher publisher;

int main(int argc, char **argv)
{
    ros::init(argc, argv, "measurement_system_node");

    ros::NodeHandle n;
    ros::Rate loop_rate(10); // Hz

    ros::Subscriber sub = n.subscribe("vision_topic", 1, receiveVisionMessage);
    publisher = n.advertise<unball::MeasurementSystemMessage>("measurement_system_topic", 1);

    while (ros::ok())
    {
        ros::spinOnce();
        loop_rate.sleep();
    }

    return 0;
}

void receiveVisionMessage(const unball::VisionMessage::ConstPtr &msg_v)
{
    std::vector<float> x(6), y(6), th(6);
    std::vector<float> ball_location(2);

    ROS_INFO("\n\n[MeasurementNode]:ReceiveVisionMessage - Receiving vision message");

    for (int robot_index = 0; robot_index < 6; robot_index++)
    {
        ROS_INFO("%d x: %f\t y: %f\t th: %f", robot_index, msg_v->x[robot_index], msg_v->y[robot_index],
            msg_v->th[robot_index]);
        if (not (msg_v->x[robot_index] == -1 and msg_v->y[robot_index] == -1))
        {
            message.x[robot_index] = msg_v->x[robot_index];
            message.y[robot_index] = msg_v->y[robot_index];
            if (not std::isnan(msg_v->th[robot_index])){
                message.th[robot_index] = msg_v->th[robot_index] * -1;
            }

        }
        //if(message.th[robot_index]!=0){
        //    message.th[robot_index] = msg_v->th[robot_index] * -1;
        //}
    }
    message.ball_x = msg_v->ball_x;
    message.ball_y = msg_v->ball_y;
    convertPixelsToMeters();

    filter();

    ROS_INFO("\n\n[MeasurementNode]:ReceiveVisionMessage - Sending measurement system message");

    for (int robot_index = 0; robot_index < 6; robot_index++)
    {
        ROS_INFO("%d x: %f\t y: %f\t th: %f", robot_index, message.x[robot_index], message.y[robot_index],
            message.th[robot_index]);
    }
    ROS_INFO("Ball: x: %f, y: %f", message.ball_x, message.ball_y);

    publisher.publish(message);
}

void convertPixelsToMeters(){
    auto x_conversion = field_x_length / camera_x_length;
    auto y_conversion = (field_y_length / camera_y_length) * -1;
    for (int i = 0; i < 6; ++i)
    {
        message.x[i] -= camera_x_length / 2;
        message.y[i] -= camera_y_length / 2;
        message.x[i] *= x_conversion;
        message.y[i] *= y_conversion;
    }
    message.ball_x -= camera_x_length / 2;
    message.ball_y -= camera_y_length / 2;
    message.ball_x *= x_conversion;
    message.ball_y *= y_conversion;
}

float mean_array_x[6]={0,0,0,0,0,0};
float mean_array_y[6]={0,0,0,0,0,0};
float mean_ball_x=0;
float mean_ball_y=0;
float mean_array_th[6]={0,0,0,0,0,0};
float N_mean=4;

void filter(){
    for (int i = 0; i < 6; ++i)
    {
        mean_array_x[i] += (message.x[i] - mean_array_x[i])/N_mean;
        message.x[i] = mean_array_x[i];

        mean_array_y[i] += (message.y[i] - mean_array_y[i])/N_mean;
        message.y[i] = mean_array_y[i];

        if (not std::isnan(mean_array_th[i] + (message.th[i] - mean_array_th[i])/N_mean)) {
            if(abs(message.th[i]-mean_array_th[i])>M_PI/2){
                    mean_array_th[i]=message.th[i];
                }else{
                    mean_array_th[i] += (message.th[i] - mean_array_th[i])/N_mean;
                }
            message.th[i] = mean_array_th[i];
        }
    }

    mean_ball_x += (message.ball_x - mean_ball_x)/N_mean;
    message.ball_x = mean_ball_x;

    mean_ball_y += (message.ball_y - mean_ball_y)/N_mean;
    message.ball_y = mean_ball_y;
}<commit_msg>final ajusts<commit_after>/**
 * @file   measurement_systen_node.cpp
 * @author Izabella Thais Oliveira Gomes
 * @date   23/09/2016
 *
 * @attention Copyright (C) 2014 UnBall Robot Soccer Team
 *
 * @brief Rotate robot position datas acording to camera position in the vision and simulator and publishes that.
 *
*/

#include <vector>
#include <cmath>

#include <ros/ros.h>

#include <unball/VisionMessage.h>
#include <unball/SimulatorMessage.h>
#include <unball/MeasurementSystemMessage.h>
#include <opencv2/opencv.hpp>

//const float field_x_length = 1.50;
//const float field_y_length = 1.30;

const float field_x_length = 1.60;
const float field_y_length = 1.30;

const float camera_x_length = 640;
const float camera_y_length = 480;

void receiveVisionMessage(const unball::VisionMessage::ConstPtr &msg_s);
void rotateAxis();
void convertPixelsToMeters();
void receiveSimulatorMessage(const unball::SimulatorMessage::ConstPtr &msg_v);
void publishMeasurementSystemMessage(ros::Publisher &publisher);
void filter();

unball::MeasurementSystemMessage message;

ros::Publisher publisher;

int main(int argc, char **argv)
{
    ros::init(argc, argv, "measurement_system_node");

    ros::NodeHandle n;
    ros::Rate loop_rate(10); // Hz

    ros::Subscriber sub = n.subscribe("vision_topic", 1, receiveVisionMessage);
    publisher = n.advertise<unball::MeasurementSystemMessage>("measurement_system_topic", 1);

    while (ros::ok())
    {
        ros::spinOnce();
        loop_rate.sleep();
    }

    return 0;
}

void receiveVisionMessage(const unball::VisionMessage::ConstPtr &msg_v)
{
    std::vector<float> x(6), y(6), th(6);
    std::vector<float> ball_location(2);

    ROS_INFO("\n\n[MeasurementNode]:ReceiveVisionMessage - Receiving vision message");

    for (int robot_index = 0; robot_index < 6; robot_index++)
    {
        ROS_INFO("%d x: %f\t y: %f\t th: %f", robot_index, msg_v->x[robot_index], msg_v->y[robot_index],
            msg_v->th[robot_index]);
        if (not (msg_v->x[robot_index] == -1 and msg_v->y[robot_index] == -1))
        {
            message.x[robot_index] = msg_v->x[robot_index];
            message.y[robot_index] = msg_v->y[robot_index];
            if (not std::isnan(msg_v->th[robot_index])){
                message.th[robot_index] = msg_v->th[robot_index];
            }

        }

    }
    message.ball_x = msg_v->ball_x;
    message.ball_y = msg_v->ball_y;
    convertPixelsToMeters();

    //filter();

    ROS_INFO("\n\n[MeasurementNode]:ReceiveVisionMessage - Sending measurement system message");

    for (int robot_index = 0; robot_index < 6; robot_index++)
    {
        ROS_INFO("%d x: %f\t y: %f\t th: %f", robot_index, message.x[robot_index], message.y[robot_index],
            message.th[robot_index]);
    }
    ROS_INFO("Ball: x: %f, y: %f", message.ball_x, message.ball_y);

    publisher.publish(message);
}

void convertPixelsToMeters(){
    auto x_conversion = field_x_length / camera_x_length;
    auto y_conversion = (field_y_length / camera_y_length) * -1;
    for (int i = 0; i < 6; ++i)
    {
        message.x[i] -= camera_x_length / 2;
        message.y[i] -= camera_y_length / 2;
        message.x[i] *= x_conversion;
        message.y[i] *= y_conversion;
    }
    message.ball_x -= camera_x_length / 2;
    message.ball_y -= camera_y_length / 2;
    message.ball_x *= x_conversion;
    message.ball_y *= y_conversion;
}

float mean_array_x[6]={0,0,0,0,0,0};
float mean_array_y[6]={0,0,0,0,0,0};
float mean_ball_x=0;
float mean_ball_y=0;
float mean_array_th[6]={0,0,0,0,0,0};
float N_mean=10;

void filter(){
    for (int i = 0; i < 6; ++i)
    {
        mean_array_x[i] += (message.x[i] - mean_array_x[i])/N_mean;
        message.x[i] = mean_array_x[i];

        mean_array_y[i] += (message.y[i] - mean_array_y[i])/N_mean;
        message.y[i] = mean_array_y[i];

        if (not std::isnan(mean_array_th[i] + (message.th[i] - mean_array_th[i])/N_mean)) {
            if(abs(message.th[i]-mean_array_th[i])>M_PI/2){
                    mean_array_th[i]=message.th[i];
                }else{
                    mean_array_th[i] += (message.th[i] - mean_array_th[i])/N_mean;
                }
            message.th[i] = mean_array_th[i];
        }
    }

    mean_ball_x += (message.ball_x - mean_ball_x)/N_mean;
    message.ball_x = mean_ball_x;

    mean_ball_y += (message.ball_y - mean_ball_y)/N_mean;
    message.ball_y = mean_ball_y;
}<|endoftext|>


<commit_before>#include "dll/dbn.hpp"

template<typename DBN>
void test_dbn(){
    DBN dbn;

    dbn.display();

    std::vector<vector<double>> images;
    std::vector<vector<double>> labels;

    dbn.pretrain(images, 10);
    dbn.fine_tune(images, labels, 10, 10);
}

template <typename RBM>
using pcd2_trainer_t = dll::persistent_cd_trainer<2, RBM>;

int main(){
    //Basic example

    typedef dll::dbn<
        dll::layer<28 * 28, 100, dll::in_dbn, dll::momentum, dll::batch_size<50>, dll::init_weights, dll::weight_decay<dll::decay_type::L2>, dll::sparsity>,
        dll::layer<100, 100, dll::in_dbn, dll::momentum, dll::batch_size<50>>,
        dll::layer<110, 200, dll::in_dbn, dll::batch_size<50>, dll::momentum, dll::weight_decay<dll::decay_type::L2_FULL>>
    > dbn_1;

    //Test them all

    test_dbn<dbn_1>();

    return 0;
}<commit_msg>Fix test<commit_after>#include "dll/dbn.hpp"

template<typename DBN>
void test_dbn(){
    DBN dbn;

    dbn.display();

    std::vector<vector<double>> images;
    std::vector<uint8_t> labels;

    dbn.pretrain(images, 10);
    dbn.fine_tune(images, labels, 10, 10);
}

template <typename RBM>
using pcd2_trainer_t = dll::persistent_cd_trainer<2, RBM>;

int main(){
    //Basic example

    typedef dll::dbn<
        dll::layer<28 * 28, 100, dll::in_dbn, dll::momentum, dll::batch_size<50>, dll::init_weights, dll::weight_decay<dll::decay_type::L2>, dll::sparsity>,
        dll::layer<100, 100, dll::in_dbn, dll::momentum, dll::batch_size<50>>,
        dll::layer<110, 200, dll::in_dbn, dll::batch_size<50>, dll::momentum, dll::weight_decay<dll::decay_type::L2_FULL>>
    > dbn_1;

    //Test them all

    test_dbn<dbn_1>();

    return 0;
}<|endoftext|>


<commit_before>// Copyright (c) 2010 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/cryptohome_library.h"

#include "base/hash_tables.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"

namespace chromeos {

// This class handles the interaction with the ChromeOS cryptohome library APIs.
class CryptohomeLibraryImpl : public CryptohomeLibrary {
 public:
  CryptohomeLibraryImpl() {
    if (CrosLibrary::Get()->EnsureLoaded())
      Init();
  }
  virtual ~CryptohomeLibraryImpl() {}

  bool CheckKey(const std::string& user_email, const std::string& passhash) {
    return chromeos::CryptohomeCheckKey(user_email.c_str(), passhash.c_str());
  }

  bool AsyncCheckKey(const std::string& user_email,
                     const std::string& passhash,
                     Delegate* d) {
    return CacheCallback(
        chromeos::CryptohomeAsyncCheckKey(user_email.c_str(), passhash.c_str()),
        d,
        "Couldn't initiate async check of user's key.");
  }

  bool MigrateKey(const std::string& user_email,
                  const std::string& old_hash,
                  const std::string& new_hash) {
    return chromeos::CryptohomeMigrateKey(user_email.c_str(),
                                          old_hash.c_str(),
                                          new_hash.c_str());
  }

  bool AsyncMigrateKey(const std::string& user_email,
                       const std::string& old_hash,
                       const std::string& new_hash,
                       Delegate* d) {
    return CacheCallback(
        chromeos::CryptohomeAsyncMigrateKey(user_email.c_str(),
                                            old_hash.c_str(),
                                            new_hash.c_str()),
        d,
        "Couldn't initiate aync migration of user's key");
  }

  bool Mount(const std::string& user_email,
             const std::string& passhash,
             int* error_code) {
    return chromeos::CryptohomeMountAllowFail(user_email.c_str(),
                                              passhash.c_str(),
                                              error_code);
  }

  bool AsyncMount(const std::string& user_email,
                  const std::string& passhash,
                  const bool create_if_missing,
                  Delegate* d) {
    return CacheCallback(
        chromeos::CryptohomeAsyncMount(user_email.c_str(),
                                       passhash.c_str(),
                                       create_if_missing,
                                       "",
                                       std::vector<std::string>()),
        d,
        "Couldn't initiate async mount of cryptohome.");
  }

  bool MountForBwsi(int* error_code) {
    return chromeos::CryptohomeMountGuest(error_code);
  }

  bool AsyncMountForBwsi(Delegate* d) {
    return CacheCallback(chromeos::CryptohomeAsyncMountGuest(),
                         d,
                         "Couldn't initiate async mount of cryptohome.");
  }

  bool Remove(const std::string& user_email) {
    return chromeos::CryptohomeRemove(user_email.c_str());
  }

  bool AsyncRemove(const std::string& user_email, Delegate* d) {
    return CacheCallback(
        chromeos::CryptohomeAsyncRemove(user_email.c_str()),
        d,
        "Couldn't initiate async removal of cryptohome.");
  }

  bool IsMounted() {
    return chromeos::CryptohomeIsMounted();
  }

  CryptohomeBlob GetSystemSalt() {
    return chromeos::CryptohomeGetSystemSalt();
  }

 private:
  static void Handler(const chromeos::CryptohomeAsyncCallStatus& event,
                      void* cryptohome_library) {
    CryptohomeLibraryImpl* library =
        reinterpret_cast<CryptohomeLibraryImpl*>(cryptohome_library);
    library->Dispatch(event);
  }

  void Init() {
    cryptohome_connection_ = chromeos::CryptohomeMonitorSession(&Handler, this);
  }

  void Dispatch(const chromeos::CryptohomeAsyncCallStatus& event) {
    callback_map_[event.async_id]->OnComplete(event.return_status,
                                              event.return_code);
    callback_map_[event.async_id] = NULL;
  }

  bool CacheCallback(int async_id,
                     Delegate* d,
                     const char* error) {
    if (async_id == 0) {
      LOG(ERROR) << error;
      return false;
    }
    callback_map_[async_id] = d;
    return true;
  }

  typedef base::hash_map<int, Delegate*> CallbackMap;
  mutable CallbackMap callback_map_;

  void* cryptohome_connection_;

  DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl);
};

class CryptohomeLibraryStubImpl : public CryptohomeLibrary {
 public:
  CryptohomeLibraryStubImpl() {}
  virtual ~CryptohomeLibraryStubImpl() {}

  bool CheckKey(const std::string& user_email, const std::string& passhash) {
    return true;
  }

  bool AsyncCheckKey(const std::string& user_email,
                     const std::string& passhash,
                     Delegate* callback) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableFunction(&DoStubCallback, callback));
    return true;
  }

  bool MigrateKey(const std::string& user_email,
                  const std::string& old_hash,
                  const std::string& new_hash) {
    return true;
  }

  bool AsyncMigrateKey(const std::string& user_email,
                       const std::string& old_hash,
                       const std::string& new_hash,
                       Delegate* callback) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableFunction(&DoStubCallback, callback));
    return true;
  }

  bool Remove(const std::string& user_email) {
    return true;
  }

  bool AsyncRemove(const std::string& user_email, Delegate* callback) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableFunction(&DoStubCallback, callback));
    return true;
  }

  bool Mount(const std::string& user_email,
             const std::string& passhash,
             int* error_code) {
    return true;
  }

  bool AsyncMount(const std::string& user_email,
                  const std::string& passhash,
                  const bool create_if_missing,
                  Delegate* callback) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableFunction(&DoStubCallback, callback));
    return true;
  }

  bool MountForBwsi(int* error_code) {
    return true;
  }

  bool AsyncMountForBwsi(Delegate* callback) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableFunction(&DoStubCallback, callback));
    return true;
  }

  bool IsMounted() {
    return true;
  }

  CryptohomeBlob GetSystemSalt() {
    CryptohomeBlob salt = CryptohomeBlob();
    salt.push_back(0);
    salt.push_back(0);
    return salt;
  }

 private:
  static void DoStubCallback(Delegate* callback) {
    callback->OnComplete(true, kCryptohomeMountErrorNone);
  }
  DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryStubImpl);
};

// static
CryptohomeLibrary* CryptohomeLibrary::GetImpl(bool stub) {
  if (stub)
    return new CryptohomeLibraryStubImpl();
  else
    return new CryptohomeLibraryImpl();
}

} // namespace chromeos
<commit_msg>[Chrome OS] Log and handle cryptohomed callbacks for calls we didn't initiate<commit_after>// Copyright (c) 2010 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/cryptohome_library.h"

#include "base/hash_tables.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"

namespace chromeos {

// This class handles the interaction with the ChromeOS cryptohome library APIs.
class CryptohomeLibraryImpl : public CryptohomeLibrary {
 public:
  CryptohomeLibraryImpl() {
    if (CrosLibrary::Get()->EnsureLoaded())
      Init();
  }
  virtual ~CryptohomeLibraryImpl() {}

  bool CheckKey(const std::string& user_email, const std::string& passhash) {
    return chromeos::CryptohomeCheckKey(user_email.c_str(), passhash.c_str());
  }

  bool AsyncCheckKey(const std::string& user_email,
                     const std::string& passhash,
                     Delegate* d) {
    return CacheCallback(
        chromeos::CryptohomeAsyncCheckKey(user_email.c_str(), passhash.c_str()),
        d,
        "Couldn't initiate async check of user's key.");
  }

  bool MigrateKey(const std::string& user_email,
                  const std::string& old_hash,
                  const std::string& new_hash) {
    return chromeos::CryptohomeMigrateKey(user_email.c_str(),
                                          old_hash.c_str(),
                                          new_hash.c_str());
  }

  bool AsyncMigrateKey(const std::string& user_email,
                       const std::string& old_hash,
                       const std::string& new_hash,
                       Delegate* d) {
    return CacheCallback(
        chromeos::CryptohomeAsyncMigrateKey(user_email.c_str(),
                                            old_hash.c_str(),
                                            new_hash.c_str()),
        d,
        "Couldn't initiate aync migration of user's key");
  }

  bool Mount(const std::string& user_email,
             const std::string& passhash,
             int* error_code) {
    return chromeos::CryptohomeMountAllowFail(user_email.c_str(),
                                              passhash.c_str(),
                                              error_code);
  }

  bool AsyncMount(const std::string& user_email,
                  const std::string& passhash,
                  const bool create_if_missing,
                  Delegate* d) {
    return CacheCallback(
        chromeos::CryptohomeAsyncMount(user_email.c_str(),
                                       passhash.c_str(),
                                       create_if_missing,
                                       "",
                                       std::vector<std::string>()),
        d,
        "Couldn't initiate async mount of cryptohome.");
  }

  bool MountForBwsi(int* error_code) {
    return chromeos::CryptohomeMountGuest(error_code);
  }

  bool AsyncMountForBwsi(Delegate* d) {
    return CacheCallback(chromeos::CryptohomeAsyncMountGuest(),
                         d,
                         "Couldn't initiate async mount of cryptohome.");
  }

  bool Remove(const std::string& user_email) {
    return chromeos::CryptohomeRemove(user_email.c_str());
  }

  bool AsyncRemove(const std::string& user_email, Delegate* d) {
    return CacheCallback(
        chromeos::CryptohomeAsyncRemove(user_email.c_str()),
        d,
        "Couldn't initiate async removal of cryptohome.");
  }

  bool IsMounted() {
    return chromeos::CryptohomeIsMounted();
  }

  CryptohomeBlob GetSystemSalt() {
    return chromeos::CryptohomeGetSystemSalt();
  }

 private:
  static void Handler(const chromeos::CryptohomeAsyncCallStatus& event,
                      void* cryptohome_library) {
    CryptohomeLibraryImpl* library =
        reinterpret_cast<CryptohomeLibraryImpl*>(cryptohome_library);
    library->Dispatch(event);
  }

  void Init() {
    cryptohome_connection_ = chromeos::CryptohomeMonitorSession(&Handler, this);
  }

  void Dispatch(const chromeos::CryptohomeAsyncCallStatus& event) {
    if (!callback_map_[event.async_id]) {
      LOG(ERROR) << "Received signal for unknown async_id " << event.async_id;
      return;
    }
    callback_map_[event.async_id]->OnComplete(event.return_status,
                                              event.return_code);
    callback_map_[event.async_id] = NULL;
  }

  bool CacheCallback(int async_id, Delegate* d, const char* error) {
    if (async_id == 0) {
      LOG(ERROR) << error;
      return false;
    }
    LOG(INFO) << "Adding handler for " << async_id;
    callback_map_[async_id] = d;
    return true;
  }

  typedef base::hash_map<int, Delegate*> CallbackMap;
  mutable CallbackMap callback_map_;

  void* cryptohome_connection_;

  DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl);
};

class CryptohomeLibraryStubImpl : public CryptohomeLibrary {
 public:
  CryptohomeLibraryStubImpl() {}
  virtual ~CryptohomeLibraryStubImpl() {}

  bool CheckKey(const std::string& user_email, const std::string& passhash) {
    return true;
  }

  bool AsyncCheckKey(const std::string& user_email,
                     const std::string& passhash,
                     Delegate* callback) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableFunction(&DoStubCallback, callback));
    return true;
  }

  bool MigrateKey(const std::string& user_email,
                  const std::string& old_hash,
                  const std::string& new_hash) {
    return true;
  }

  bool AsyncMigrateKey(const std::string& user_email,
                       const std::string& old_hash,
                       const std::string& new_hash,
                       Delegate* callback) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableFunction(&DoStubCallback, callback));
    return true;
  }

  bool Remove(const std::string& user_email) {
    return true;
  }

  bool AsyncRemove(const std::string& user_email, Delegate* callback) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableFunction(&DoStubCallback, callback));
    return true;
  }

  bool Mount(const std::string& user_email,
             const std::string& passhash,
             int* error_code) {
    return true;
  }

  bool AsyncMount(const std::string& user_email,
                  const std::string& passhash,
                  const bool create_if_missing,
                  Delegate* callback) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableFunction(&DoStubCallback, callback));
    return true;
  }

  bool MountForBwsi(int* error_code) {
    return true;
  }

  bool AsyncMountForBwsi(Delegate* callback) {
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE,
        NewRunnableFunction(&DoStubCallback, callback));
    return true;
  }

  bool IsMounted() {
    return true;
  }

  CryptohomeBlob GetSystemSalt() {
    CryptohomeBlob salt = CryptohomeBlob();
    salt.push_back(0);
    salt.push_back(0);
    return salt;
  }

 private:
  static void DoStubCallback(Delegate* callback) {
    callback->OnComplete(true, kCryptohomeMountErrorNone);
  }
  DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryStubImpl);
};

// static
CryptohomeLibrary* CryptohomeLibrary::GetImpl(bool stub) {
  if (stub)
    return new CryptohomeLibraryStubImpl();
  else
    return new CryptohomeLibraryImpl();
}

} // namespace chromeos
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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 <gtk/gtk.h>

#include "base/string_util.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/gtk/bookmark_editor_gtk.h"
#include "chrome/browser/gtk/bookmark_tree_model.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::Time;
using base::TimeDelta;
using bookmark_utils::GetTitleFromTreeIter;

// Base class for bookmark editor tests. This class is a copy from
// bookmark_editor_view_unittest.cc, and all the tests in this file are
// GTK-ifications of the corresponding views tests. Testing here is really
// important because on Linux, we make round trip copies from chrome's
// BookmarkModel class to GTK's native GtkTreeStore.
class BookmarkEditorGtkTest : public testing::Test {
 public:
  BookmarkEditorGtkTest() : model_(NULL) {
  }

  virtual void SetUp() {
    profile_.reset(new TestingProfile());
    profile_->set_has_history_service(true);
    profile_->CreateBookmarkModel(true);

    model_ = profile_->GetBookmarkModel();

    AddTestData();
  }

  virtual void TearDown() {
  }

 protected:
  MessageLoopForUI message_loop_;
  BookmarkModel* model_;
  scoped_ptr<TestingProfile> profile_;

  std::string base_path() const { return "file:///c:/tmp/"; }

  BookmarkNode* GetNode(const std::string& name) {
    return model_->GetMostRecentlyAddedNodeForURL(GURL(base_path() + name));
  }

 private:
  // Creates the following structure:
  // bookmark bar node
  //   a
  //   F1
  //    f1a
  //    F11
  //     f11a
  //   F2
  // other node
  //   oa
  //   OF1
  //     of1a
  void AddTestData() {
    std::string test_base = base_path();

    model_->AddURL(model_->GetBookmarkBarNode(), 0, L"a",
                   GURL(test_base + "a"));
    BookmarkNode* f1 = model_->AddGroup(model_->GetBookmarkBarNode(), 1, L"F1");
    model_->AddURL(f1, 0, L"f1a", GURL(test_base + "f1a"));
    BookmarkNode* f11 = model_->AddGroup(f1, 1, L"F11");
    model_->AddURL(f11, 0, L"f11a", GURL(test_base + "f11a"));
    model_->AddGroup(model_->GetBookmarkBarNode(), 2, L"F2");

    // Children of the other node.
    model_->AddURL(model_->other_node(), 0, L"oa",
                   GURL(test_base + "oa"));
    BookmarkNode* of1 = model_->AddGroup(model_->other_node(), 1, L"OF1");
    model_->AddURL(of1, 0, L"of1a", GURL(test_base + "of1a"));
  }
};

// Makes sure the tree model matches that of the bookmark bar model.
TEST_F(BookmarkEditorGtkTest, ModelsMatch) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
                           BookmarkEditor::SHOW_TREE, NULL);

  // The root should have two children, one for the bookmark bar node,
  // the other for the 'other bookmarks' folder.
  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  GtkTreeIter toplevel;
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &toplevel));
  GtkTreeIter bookmark_bar_node = toplevel;
  ASSERT_TRUE(gtk_tree_model_iter_next(store, &toplevel));
  GtkTreeIter other_node = toplevel;
  ASSERT_FALSE(gtk_tree_model_iter_next(store, &toplevel));

  // The bookmark bar should have 2 nodes: folder F1 and F2.
  GtkTreeIter f1_iter;
  GtkTreeIter child;
  ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
  ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &bookmark_bar_node));
  f1_iter = child;
  ASSERT_EQ(L"F1", GetTitleFromTreeIter(store, &child));
  ASSERT_TRUE(gtk_tree_model_iter_next(store, &child));
  ASSERT_EQ(L"F2", GetTitleFromTreeIter(store, &child));
  ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));

  // F1 should have one child, F11
  ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f1_iter));
  ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &f1_iter));
  ASSERT_EQ(L"F11", GetTitleFromTreeIter(store, &child));
  ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));

  // Other node should have one child (OF1).
  ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &other_node));
  ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &other_node));
  ASSERT_EQ(L"OF1", GetTitleFromTreeIter(store, &child));
  ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
}

// Changes the title and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditTitleKeepsPosition) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
                           BookmarkEditor::SHOW_TREE, NULL);
  gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");

  GtkTreeIter bookmark_bar_node;
  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
  editor.ApplyEdits(&bookmark_bar_node);

  BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
  ASSERT_EQ(L"new_a", bb_node->GetChild(0)->GetTitle());
  // The URL shouldn't have changed.
  ASSERT_TRUE(GURL(base_path() + "a") == bb_node->GetChild(0)->GetURL());
}

// Changes the url and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditURLKeepsPosition) {
  Time node_time = Time::Now() + TimeDelta::FromDays(2);
  GetNode("a")->date_added_ = node_time;
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
                           BookmarkEditor::SHOW_TREE, NULL);
  gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
                     GURL(base_path() + "new_a").spec().c_str());

  GtkTreeIter bookmark_bar_node;
  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
  editor.ApplyEdits(&bookmark_bar_node);

  BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
  ASSERT_EQ(L"a", bb_node->GetChild(0)->GetTitle());
  // The URL should have changed.
  ASSERT_TRUE(GURL(base_path() + "new_a") == bb_node->GetChild(0)->GetURL());
  ASSERT_TRUE(node_time == bb_node->GetChild(0)->date_added());
}

// Moves 'a' to be a child of the other node.
TEST_F(BookmarkEditorGtkTest, ChangeParent) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
                           BookmarkEditor::SHOW_TREE, NULL);

  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  GtkTreeIter gtk_other_node;
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &gtk_other_node));
  ASSERT_TRUE(gtk_tree_model_iter_next(store, &gtk_other_node));
  editor.ApplyEdits(&gtk_other_node);

  BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
  ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
  ASSERT_TRUE(GURL(base_path() + "a") == other_node->GetChild(2)->GetURL());
}

// Moves 'a' to be a child of the other node.
// Moves 'a' to be a child of the other node and changes its url to new_a.
TEST_F(BookmarkEditorGtkTest, ChangeParentAndURL) {
  Time node_time = Time::Now() + TimeDelta::FromDays(2);
  GetNode("a")->date_added_ = node_time;
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
                           BookmarkEditor::SHOW_TREE, NULL);

  gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
                     GURL(base_path() + "new_a").spec().c_str());

  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  GtkTreeIter gtk_other_node;
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &gtk_other_node));
  ASSERT_TRUE(gtk_tree_model_iter_next(store, &gtk_other_node));
  editor.ApplyEdits(&gtk_other_node);

  BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
  ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
  ASSERT_TRUE(GURL(base_path() + "new_a") == other_node->GetChild(2)->GetURL());
  ASSERT_TRUE(node_time == other_node->GetChild(2)->date_added());
}

// Creates a new folder and moves a node to it.
TEST_F(BookmarkEditorGtkTest, MoveToNewParent) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
                           BookmarkEditor::SHOW_TREE, NULL);

  GtkTreeIter bookmark_bar_node;
  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));

  // The bookmark bar should have 2 nodes: folder F1 and F2.
  GtkTreeIter f2_iter;
  ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
  ASSERT_TRUE(gtk_tree_model_iter_children(store, &f2_iter,
                                           &bookmark_bar_node));
  ASSERT_TRUE(gtk_tree_model_iter_next(store, &f2_iter));

  // Create two nodes: "F21" as a child of "F2" and "F211" as a child of "F21".
  GtkTreeIter f21_iter;
  editor.AddNewGroup(&f2_iter, &f21_iter);
  gtk_tree_store_set(editor.tree_store_, &f21_iter,
                     bookmark_utils::FOLDER_NAME, "F21", -1);
  GtkTreeIter f211_iter;
  editor.AddNewGroup(&f21_iter, &f211_iter);
  gtk_tree_store_set(editor.tree_store_, &f211_iter,
                     bookmark_utils::FOLDER_NAME, "F211", -1);

  ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f2_iter));

  editor.ApplyEdits(&f2_iter);

  BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
  BookmarkNode* mf2 = bb_node->GetChild(1);

  // F2 in the model should have two children now: F21 and the node edited.
  ASSERT_EQ(2, mf2->GetChildCount());
  // F21 should be first.
  ASSERT_EQ(L"F21", mf2->GetChild(0)->GetTitle());
  // Then a.
  ASSERT_EQ(L"a", mf2->GetChild(1)->GetTitle());

  // F21 should have one child, F211.
  BookmarkNode* mf21 = mf2->GetChild(0);
  ASSERT_EQ(1, mf21->GetChildCount());
  ASSERT_EQ(L"F211", mf21->GetChild(0)->GetTitle());
}

// Brings up the editor, creating a new URL on the bookmark bar.
TEST_F(BookmarkEditorGtkTest, NewURL) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
                           BookmarkEditor::SHOW_TREE, NULL);

  gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
                     GURL(base_path() + "a").spec().c_str());
  gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");

  GtkTreeIter bookmark_bar_node;
  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
  editor.ApplyEdits(&bookmark_bar_node);

  BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
  ASSERT_EQ(4, bb_node->GetChildCount());

  BookmarkNode* new_node = bb_node->GetChild(3);
  EXPECT_EQ(L"new_a", new_node->GetTitle());
  EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}

// Brings up the editor with no tree and modifies the url.
TEST_F(BookmarkEditorGtkTest, ChangeURLNoTree) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
                           model_->other_node()->GetChild(0),
                           BookmarkEditor::NO_TREE, NULL);

  gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
                     GURL(base_path() + "a").spec().c_str());
  gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");

  editor.ApplyEdits(NULL);

  BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
  ASSERT_EQ(2, other_node->GetChildCount());

  BookmarkNode* new_node = other_node->GetChild(0);

  EXPECT_EQ(L"new_a", new_node->GetTitle());
  EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}

// Brings up the editor with no tree and modifies only the title.
TEST_F(BookmarkEditorGtkTest, ChangeTitleNoTree) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
                           model_->other_node()->GetChild(0),
                           BookmarkEditor::NO_TREE, NULL);
  gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");

  editor.ApplyEdits();

  BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
  ASSERT_EQ(2, other_node->GetChildCount());

  BookmarkNode* new_node = other_node->GetChild(0);
  EXPECT_EQ(L"new_a", new_node->GetTitle());
}
<commit_msg>Disable a failing test on linux.<commit_after>// Copyright (c) 2006-2008 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 <gtk/gtk.h>

#include "base/string_util.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/gtk/bookmark_editor_gtk.h"
#include "chrome/browser/gtk/bookmark_tree_model.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::Time;
using base::TimeDelta;
using bookmark_utils::GetTitleFromTreeIter;

// Base class for bookmark editor tests. This class is a copy from
// bookmark_editor_view_unittest.cc, and all the tests in this file are
// GTK-ifications of the corresponding views tests. Testing here is really
// important because on Linux, we make round trip copies from chrome's
// BookmarkModel class to GTK's native GtkTreeStore.
class BookmarkEditorGtkTest : public testing::Test {
 public:
  BookmarkEditorGtkTest() : model_(NULL) {
  }

  virtual void SetUp() {
    profile_.reset(new TestingProfile());
    profile_->set_has_history_service(true);
    profile_->CreateBookmarkModel(true);

    model_ = profile_->GetBookmarkModel();

    AddTestData();
  }

  virtual void TearDown() {
  }

 protected:
  MessageLoopForUI message_loop_;
  BookmarkModel* model_;
  scoped_ptr<TestingProfile> profile_;

  std::string base_path() const { return "file:///c:/tmp/"; }

  BookmarkNode* GetNode(const std::string& name) {
    return model_->GetMostRecentlyAddedNodeForURL(GURL(base_path() + name));
  }

 private:
  // Creates the following structure:
  // bookmark bar node
  //   a
  //   F1
  //    f1a
  //    F11
  //     f11a
  //   F2
  // other node
  //   oa
  //   OF1
  //     of1a
  void AddTestData() {
    std::string test_base = base_path();

    model_->AddURL(model_->GetBookmarkBarNode(), 0, L"a",
                   GURL(test_base + "a"));
    BookmarkNode* f1 = model_->AddGroup(model_->GetBookmarkBarNode(), 1, L"F1");
    model_->AddURL(f1, 0, L"f1a", GURL(test_base + "f1a"));
    BookmarkNode* f11 = model_->AddGroup(f1, 1, L"F11");
    model_->AddURL(f11, 0, L"f11a", GURL(test_base + "f11a"));
    model_->AddGroup(model_->GetBookmarkBarNode(), 2, L"F2");

    // Children of the other node.
    model_->AddURL(model_->other_node(), 0, L"oa",
                   GURL(test_base + "oa"));
    BookmarkNode* of1 = model_->AddGroup(model_->other_node(), 1, L"OF1");
    model_->AddURL(of1, 0, L"of1a", GURL(test_base + "of1a"));
  }
};

// Makes sure the tree model matches that of the bookmark bar model.
TEST_F(BookmarkEditorGtkTest, ModelsMatch) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
                           BookmarkEditor::SHOW_TREE, NULL);

  // The root should have two children, one for the bookmark bar node,
  // the other for the 'other bookmarks' folder.
  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  GtkTreeIter toplevel;
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &toplevel));
  GtkTreeIter bookmark_bar_node = toplevel;
  ASSERT_TRUE(gtk_tree_model_iter_next(store, &toplevel));
  GtkTreeIter other_node = toplevel;
  ASSERT_FALSE(gtk_tree_model_iter_next(store, &toplevel));

  // The bookmark bar should have 2 nodes: folder F1 and F2.
  GtkTreeIter f1_iter;
  GtkTreeIter child;
  ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
  ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &bookmark_bar_node));
  f1_iter = child;
  ASSERT_EQ(L"F1", GetTitleFromTreeIter(store, &child));
  ASSERT_TRUE(gtk_tree_model_iter_next(store, &child));
  ASSERT_EQ(L"F2", GetTitleFromTreeIter(store, &child));
  ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));

  // F1 should have one child, F11
  ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f1_iter));
  ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &f1_iter));
  ASSERT_EQ(L"F11", GetTitleFromTreeIter(store, &child));
  ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));

  // Other node should have one child (OF1).
  ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &other_node));
  ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &other_node));
  ASSERT_EQ(L"OF1", GetTitleFromTreeIter(store, &child));
  ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
}

// Changes the title and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditTitleKeepsPosition) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
                           BookmarkEditor::SHOW_TREE, NULL);
  gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");

  GtkTreeIter bookmark_bar_node;
  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
  editor.ApplyEdits(&bookmark_bar_node);

  BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
  ASSERT_EQ(L"new_a", bb_node->GetChild(0)->GetTitle());
  // The URL shouldn't have changed.
  ASSERT_TRUE(GURL(base_path() + "a") == bb_node->GetChild(0)->GetURL());
}

// Changes the url and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditURLKeepsPosition) {
  Time node_time = Time::Now() + TimeDelta::FromDays(2);
  GetNode("a")->date_added_ = node_time;
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
                           BookmarkEditor::SHOW_TREE, NULL);
  gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
                     GURL(base_path() + "new_a").spec().c_str());

  GtkTreeIter bookmark_bar_node;
  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
  editor.ApplyEdits(&bookmark_bar_node);

  BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
  ASSERT_EQ(L"a", bb_node->GetChild(0)->GetTitle());
  // The URL should have changed.
  ASSERT_TRUE(GURL(base_path() + "new_a") == bb_node->GetChild(0)->GetURL());
  ASSERT_TRUE(node_time == bb_node->GetChild(0)->date_added());
}

// Moves 'a' to be a child of the other node.
TEST_F(BookmarkEditorGtkTest, ChangeParent) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
                           BookmarkEditor::SHOW_TREE, NULL);

  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  GtkTreeIter gtk_other_node;
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &gtk_other_node));
  ASSERT_TRUE(gtk_tree_model_iter_next(store, &gtk_other_node));
  editor.ApplyEdits(&gtk_other_node);

  BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
  ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
  ASSERT_TRUE(GURL(base_path() + "a") == other_node->GetChild(2)->GetURL());
}

// Moves 'a' to be a child of the other node.
// Moves 'a' to be a child of the other node and changes its url to new_a.
TEST_F(BookmarkEditorGtkTest, ChangeParentAndURL) {
  Time node_time = Time::Now() + TimeDelta::FromDays(2);
  GetNode("a")->date_added_ = node_time;
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
                           BookmarkEditor::SHOW_TREE, NULL);

  gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
                     GURL(base_path() + "new_a").spec().c_str());

  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  GtkTreeIter gtk_other_node;
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &gtk_other_node));
  ASSERT_TRUE(gtk_tree_model_iter_next(store, &gtk_other_node));
  editor.ApplyEdits(&gtk_other_node);

  BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
  ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
  ASSERT_TRUE(GURL(base_path() + "new_a") == other_node->GetChild(2)->GetURL());
  ASSERT_TRUE(node_time == other_node->GetChild(2)->date_added());
}

// TODO(tc): Test failing. Can't use DISABLED_ because of FRIEND_TEST.
#if 0
// Creates a new folder and moves a node to it.
TEST_F(BookmarkEditorGtkTest, MoveToNewParent) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
                           BookmarkEditor::SHOW_TREE, NULL);

  GtkTreeIter bookmark_bar_node;
  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));

  // The bookmark bar should have 2 nodes: folder F1 and F2.
  GtkTreeIter f2_iter;
  ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
  ASSERT_TRUE(gtk_tree_model_iter_children(store, &f2_iter,
                                           &bookmark_bar_node));
  ASSERT_TRUE(gtk_tree_model_iter_next(store, &f2_iter));

  // Create two nodes: "F21" as a child of "F2" and "F211" as a child of "F21".
  GtkTreeIter f21_iter;
  editor.AddNewGroup(&f2_iter, &f21_iter);
  gtk_tree_store_set(editor.tree_store_, &f21_iter,
                     bookmark_utils::FOLDER_NAME, "F21", -1);
  GtkTreeIter f211_iter;
  editor.AddNewGroup(&f21_iter, &f211_iter);
  gtk_tree_store_set(editor.tree_store_, &f211_iter,
                     bookmark_utils::FOLDER_NAME, "F211", -1);

  ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f2_iter));

  editor.ApplyEdits(&f2_iter);

  BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
  BookmarkNode* mf2 = bb_node->GetChild(1);

  // F2 in the model should have two children now: F21 and the node edited.
  ASSERT_EQ(2, mf2->GetChildCount());
  // F21 should be first.
  ASSERT_EQ(L"F21", mf2->GetChild(0)->GetTitle());
  // Then a.
  ASSERT_EQ(L"a", mf2->GetChild(1)->GetTitle());

  // F21 should have one child, F211.
  BookmarkNode* mf21 = mf2->GetChild(0);
  ASSERT_EQ(1, mf21->GetChildCount());
  ASSERT_EQ(L"F211", mf21->GetChild(0)->GetTitle());
}
#endif

// Brings up the editor, creating a new URL on the bookmark bar.
TEST_F(BookmarkEditorGtkTest, NewURL) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
                           BookmarkEditor::SHOW_TREE, NULL);

  gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
                     GURL(base_path() + "a").spec().c_str());
  gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");

  GtkTreeIter bookmark_bar_node;
  GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
  ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
  editor.ApplyEdits(&bookmark_bar_node);

  BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
  ASSERT_EQ(4, bb_node->GetChildCount());

  BookmarkNode* new_node = bb_node->GetChild(3);
  EXPECT_EQ(L"new_a", new_node->GetTitle());
  EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}

// Brings up the editor with no tree and modifies the url.
TEST_F(BookmarkEditorGtkTest, ChangeURLNoTree) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
                           model_->other_node()->GetChild(0),
                           BookmarkEditor::NO_TREE, NULL);

  gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
                     GURL(base_path() + "a").spec().c_str());
  gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");

  editor.ApplyEdits(NULL);

  BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
  ASSERT_EQ(2, other_node->GetChildCount());

  BookmarkNode* new_node = other_node->GetChild(0);

  EXPECT_EQ(L"new_a", new_node->GetTitle());
  EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}

// Brings up the editor with no tree and modifies only the title.
TEST_F(BookmarkEditorGtkTest, ChangeTitleNoTree) {
  BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
                           model_->other_node()->GetChild(0),
                           BookmarkEditor::NO_TREE, NULL);
  gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");

  editor.ApplyEdits();

  BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
  ASSERT_EQ(2, other_node->GetChildCount());

  BookmarkNode* new_node = other_node->GetChild(0);
  EXPECT_EQ(L"new_a", new_node->GetTitle());
}
<|endoftext|>