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

#include <algorithm>
#include <boost/property_tree/ptree.hpp>

#include "clotho/utility/state_object.hpp"
#include "clotho/utility/log_helper.hpp"

#include "clotho/cuda/data_spaces/event_space/device_event_space.hpp"
#include "clotho/cuda/mutation/mutation_event_generator.hpp"

#ifndef USE_OFFSPRING_CROSSOVER
#include "clotho/cuda/crossover/crossover_generator.hpp"
#else
#include "clotho/cuda/crossover/offspring_generator.hpp"
#endif  // USE_OFFSPRING_CROSSOVER

//#include "clotho/cuda/selection/selection_event_generator.hpp"
#include "clotho/cuda/selection/fit_selection_generator.hpp"
#include "clotho/cuda/phenotype/phenotype_translator.hpp"

#include "clotho/cuda/analysis/allele_frequency.hpp"
#include "clotho/cuda/analysis/sequence_hamming_weight.hpp"

#include "clotho/utility/timer.hpp"
#include "clotho/utility/log_helper.hpp"

#include "clotho/cuda/fitness/quadratic_fitness_translator.hpp"

template < class PopulationSpaceType >
class qtl_cuda_simulate_engine : public clotho::utility::iStateObject {
public:
    typedef PopulationSpaceType                                 population_space_type;

    typedef typename population_space_type::allele_space_type       allele_space_type;
    typedef typename population_space_type::sequence_space_type     sequence_space_type;

    typedef typename allele_space_type::real_type                           real_type;
    typedef typename sequence_space_type::int_type                          int_type;
    typedef typename population_space_type::free_space_type::order_tag_type order_tag_type;

    typedef MutationEventGenerator< real_type, int_type, order_tag_type >   mutation_generator_type;
    typedef typename mutation_generator_type::space_type            mutation_event_space_type;

#ifndef USE_OFFSPRING_CROSSOVER
    typedef CrossoverGenerator< population_space_type >             crossover_generator_type;
#else
    typedef OffspringGenerator< population_space_type >             crossover_generator_type;
#endif  // USE_OFFSPRING_CROSSOVER

    //typedef SelectionEventGenerator                                 selection_generator_type;
    typedef FitSelectionGenerator< int_type, real_type >            selection_generator_type;

    typedef QuadraticFitnessTranslator< typename population_space_type::phenotype_space_type >                 fitness_type;

    typedef clotho::utility::timer                                  timer_type;

    qtl_cuda_simulate_engine( boost::property_tree::ptree & config ) :
        current_pop( &hPop0 )
        , prev_pop( &hPop1 )
        , mut_gen( config )
        , xover_gen( config )
        , sel_gen(config)
        , pheno_trans(config)
        , fit_trans( config )
        , all_freq( config )
        , seq_weight( config )
    {
        parse_config( config );
        initialize();
    }

#ifndef USE_OFFSPRING_CROSSOVER
    void simulate( unsigned int N ) {
        swap();
        unsigned int cur_seq_count = 2 * N;

        prev_pop->record_fixed( fixed_alleles );

        mut_gen.generate( dMutations, cur_seq_count );

        current_pop->resize( prev_pop, dMutations, cur_seq_count );

        xover_gen( current_pop );

        // recombine parents
        sel_gen.generate_and_recombine( prev_pop, current_pop, fit_trans.get_device_space() );

        mut_gen.scatter( current_pop, dMutations, cur_seq_count );

        pheno_trans.translate( current_pop );

        fit_trans( current_pop->pheno_space, cur_seq_count );

        current_pop->update_metadata();

        cudaDeviceSynchronize();

        size_t fsize, tsize;
        cudaError_t err = cudaMemGetInfo( &fsize, &tsize );

        if( err != cudaSuccess ) {
            std::cerr << "Unable to determine device memory (simulate): " << cudaGetErrorString(err) << std::endl;

            assert(false);
            fsize = 0;
        }
        clotho::utility::add_value_array(dev_space.get_child("free"), fsize );
    }
#else
    void simulate( unsigned int N ) {
        swap();
        unsigned int cur_seq_count = 2 * N;

        prev_pop->record_fixed( fixed_alleles );

        mut_gen.generate( dMutations, cur_seq_count );

        current_pop->resize( prev_pop, dMutations, cur_seq_count );

        sel_gen.generate( prev_pop, current_pop, fit_trans.get_device_space() );

        xover_gen( prev_pop, sel_gen.get_device_space(), current_pop );

        mut_gen.scatter( current_pop, dMutations, cur_seq_count );

        pheno_trans.translate( current_pop );

        fit_trans( current_pop->pheno_space, cur_seq_count );

        current_pop->update_metadata();

        cudaDeviceSynchronize();
    }
#endif  // USE_OFFSPRING_CROSSOVER

    void analyze_population( ) {
        all_freq.evaluate( current_pop );
        seq_weight.evaluate( current_pop );

        cudaDeviceSynchronize();
    }

    void get_state( boost::property_tree::ptree & state ) {
        boost::property_tree::ptree cur, prev;
        current_pop->get_state( cur );
        prev_pop->get_state( prev );

        boost::property_tree::ptree fx;
        fixed_alleles.get_state( fx );

        boost::property_tree::ptree mut;
        get_device_object_state( mut, dMutations );

        boost::property_tree::ptree sel;
        sel_gen.get_state( sel );

        boost::property_tree::ptree asis;
        all_freq.get_state( asis );
        seq_weight.get_state( asis );

        boost::property_tree::ptree fit;
        fit_trans.get_state( fit );

        state.put_child("device.memory", dev_space );

        state.put_child( "population.current", cur );
        state.put_child( "population.current.fitness", fit );

        state.put_child( "population.previous", prev );
        state.put_child( "mutations", mut );
        state.put_child( "selection", sel );
        state.put_child( "analysis", asis );
        state.put_child( "alleles.fixed", fx );
    }

    void swap() {
        std::swap( prev_pop, current_pop );
    }

    virtual ~qtl_cuda_simulate_engine() {
        delete_space( dMutations );
    }

protected:

    void parse_config( boost::property_tree::ptree & config ) {
    }

    void initialize( ) {
        create_space( dMutations );

        size_t fsize = 0;
        size_t tsize = 0;

        cudaError_t err = cudaMemGetInfo( &fsize, &tsize);

        if( err != cudaSuccess ) {
            std::cerr << "Unable to initialize memory space sizes" << std::endl;
        }

        boost::property_tree::ptree tmp;
        clotho::utility::add_value_array(tmp, fsize );
        dev_space.put_child( "free", tmp );
        dev_space.put("total", tsize);
    }

    mutation_event_space_type     * dMutations;
    population_space_type   hPop0, hPop1;
    population_space_type   * prev_pop, * current_pop;

    allele_space_type       fixed_alleles;

    mutation_generator_type     mut_gen;
    crossover_generator_type    xover_gen;
    selection_generator_type    sel_gen;
    phenotype_translator        pheno_trans;

    fitness_type                fit_trans;

    AlleleFrequency             all_freq;
    SequenceHammingWeight       seq_weight;

    boost::property_tree::ptree dev_space;
};

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

#include <algorithm>
#include <boost/property_tree/ptree.hpp>

#include "clotho/utility/state_object.hpp"
#include "clotho/utility/log_helper.hpp"

#include "clotho/cuda/data_spaces/event_space/device_event_space.hpp"
#include "clotho/cuda/mutation/mutation_event_generator.hpp"

#ifndef USE_OFFSPRING_CROSSOVER
#include "clotho/cuda/crossover/crossover_generator.hpp"
#else
#include "clotho/cuda/crossover/offspring_generator.hpp"
#endif  // USE_OFFSPRING_CROSSOVER

//#include "clotho/cuda/selection/selection_event_generator.hpp"
#include "clotho/cuda/selection/fit_selection_generator.hpp"
#include "clotho/cuda/phenotype/phenotype_translator.hpp"

#include "clotho/cuda/analysis/allele_frequency.hpp"
#include "clotho/cuda/analysis/sequence_hamming_weight.hpp"

#include "clotho/utility/timer.hpp"
#include "clotho/utility/log_helper.hpp"

#include "clotho/cuda/fitness/quadratic_fitness_translator.hpp"

template < class PopulationSpaceType >
class qtl_cuda_simulate_engine : public clotho::utility::iStateObject {
public:
    typedef PopulationSpaceType                                 population_space_type;

    typedef typename population_space_type::allele_space_type       allele_space_type;
    typedef typename population_space_type::sequence_space_type     sequence_space_type;

    typedef typename allele_space_type::real_type                           real_type;
    typedef typename sequence_space_type::int_type                          int_type;
    typedef typename population_space_type::free_space_type::order_tag_type order_tag_type;

    typedef MutationEventGenerator< real_type, int_type, order_tag_type >   mutation_generator_type;
    typedef typename mutation_generator_type::space_type            mutation_event_space_type;

#ifndef USE_OFFSPRING_CROSSOVER
    typedef CrossoverGenerator< population_space_type >             crossover_generator_type;
#else
    typedef OffspringGenerator< population_space_type >             crossover_generator_type;
#endif  // USE_OFFSPRING_CROSSOVER

    //typedef SelectionEventGenerator                                 selection_generator_type;
    typedef FitSelectionGenerator< int_type, real_type >            selection_generator_type;

    typedef QuadraticFitnessTranslator< typename population_space_type::phenotype_space_type >                 fitness_type;

    typedef clotho::utility::timer                                  timer_type;

    qtl_cuda_simulate_engine( boost::property_tree::ptree & config ) :
        current_pop( &hPop0 )
        , prev_pop( &hPop1 )
        , mut_gen( config )
        , xover_gen( config )
        , sel_gen(config)
        , pheno_trans(config)
        , fit_trans( config )
        , all_freq( config )
        , seq_weight( config )
    {
        parse_config( config );
        initialize();
    }

#ifndef USE_OFFSPRING_CROSSOVER
    void simulate( unsigned int N ) {
        swap();
        unsigned int cur_seq_count = 2 * N;

        prev_pop->record_fixed( fixed_alleles );

        mut_gen.generate( dMutations, cur_seq_count );

        current_pop->resize( prev_pop, dMutations, cur_seq_count );

        xover_gen( current_pop );

        // recombine parents
        sel_gen.generate_and_recombine( prev_pop, current_pop, fit_trans.get_device_space() );

        mut_gen.scatter( current_pop, dMutations, cur_seq_count );

        pheno_trans.translate( current_pop );

        fit_trans( current_pop->pheno_space, cur_seq_count );

        current_pop->update_metadata();

        cudaDeviceSynchronize();

/*
        size_t fsize, tsize;
        cudaError_t err = cudaMemGetInfo( &fsize, &tsize );

        if( err != cudaSuccess ) {
            std::cerr << "Unable to determine device memory (simulate): " << cudaGetErrorString(err) << std::endl;

            assert(false);
            fsize = 0;
        }
        clotho::utility::add_value_array(dev_space.get_child("free"), fsize );
*/
    }
#else
    void simulate( unsigned int N ) {
        swap();
        unsigned int cur_seq_count = 2 * N;

        prev_pop->record_fixed( fixed_alleles );

        mut_gen.generate( dMutations, cur_seq_count );

        current_pop->resize( prev_pop, dMutations, cur_seq_count );

        sel_gen.generate( prev_pop, current_pop, fit_trans.get_device_space() );

        xover_gen( prev_pop, sel_gen.get_device_space(), current_pop );

        mut_gen.scatter( current_pop, dMutations, cur_seq_count );

        pheno_trans.translate( current_pop );

        fit_trans( current_pop->pheno_space, cur_seq_count );

        current_pop->update_metadata();

        cudaDeviceSynchronize();
    }
#endif  // USE_OFFSPRING_CROSSOVER

    void analyze_population( ) {
        all_freq.evaluate( current_pop );
        seq_weight.evaluate( current_pop );

        cudaDeviceSynchronize();
    }

    void get_state( boost::property_tree::ptree & state ) {
        boost::property_tree::ptree cur, prev;
        current_pop->get_state( cur );
        prev_pop->get_state( prev );

        boost::property_tree::ptree fx;
        fixed_alleles.get_state( fx );

        boost::property_tree::ptree mut;
        get_device_object_state( mut, dMutations );

        boost::property_tree::ptree sel;
        sel_gen.get_state( sel );

        boost::property_tree::ptree asis;
        all_freq.get_state( asis );
        seq_weight.get_state( asis );

        boost::property_tree::ptree fit;
        fit_trans.get_state( fit );

//        state.put_child("device.memory", dev_space );

        state.put_child( "population.current", cur );
        state.put_child( "population.current.fitness", fit );

        state.put_child( "population.previous", prev );
        state.put_child( "mutations", mut );
        state.put_child( "selection", sel );
        state.put_child( "analysis", asis );
        state.put_child( "alleles.fixed", fx );
    }

    void swap() {
        std::swap( prev_pop, current_pop );
    }

    virtual ~qtl_cuda_simulate_engine() {
        delete_space( dMutations );
    }

protected:

    void parse_config( boost::property_tree::ptree & config ) {
    }

    void initialize( ) {
        create_space( dMutations );

        size_t fsize = 0;
        size_t tsize = 0;

/*
        cudaError_t err = cudaMemGetInfo( &fsize, &tsize);

        if( err != cudaSuccess ) {
            std::cerr << "Unable to initialize memory space sizes" << std::endl;
        }

        boost::property_tree::ptree tmp;
        clotho::utility::add_value_array(tmp, fsize );
        dev_space.put_child( "free", tmp );
        dev_space.put("total", tsize);
*/
    }

    mutation_event_space_type     * dMutations;
    population_space_type   hPop0, hPop1;
    population_space_type   * prev_pop, * current_pop;

    allele_space_type       fixed_alleles;

    mutation_generator_type     mut_gen;
    crossover_generator_type    xover_gen;
    selection_generator_type    sel_gen;
    phenotype_translator        pheno_trans;

    fitness_type                fit_trans;

    AlleleFrequency             all_freq;
    SequenceHammingWeight       seq_weight;

//    boost::property_tree::ptree dev_space;
};

#endif  // QTL_CUDA_SIMULATE_ENGINE_HPP_
<|endoftext|>


<commit_before>/**
 * scoreboard.cpp
 *
 * The implementation of the scoreboard.h interface
 */

#include "scoreboard.h"

/**
 * Sets the score for a given competition and a given period
 *
 * If the given competitor or period is negative, then no changes take effect
 * If the given competitor or period is greater than the current board size
 * the size of the scoreboard is increased to address this new score
 *
 * @param competitor the competitor to set the score for
 * @param period the period to set the score for
 * @param score the score to set
 */
void Scoreboard::setScore(int competitor, int period, int score) {
    competitor--;
    period--;

    if (competitor < 0 || period < 0) {
        return;
    }

    if (competitor >= scores.size()) {
        for (int i = scores.size(); i < competitor; i++) {
            scores.push_back(vector<int>());
        }
    }

    if (period >= scores[competitor].size()) {
        for (int i = scores[competitor].size(); i < period; i++) {
            scores[competitor].push_back(0);
        }
    }

    scores[competitor][period] = score;
}

/**
 * Gets the score for a given competitor and period
 * @param  competitor the competitor to get the score for
 * @param  period the period to get the score for
 * @return the score
 */
int Scoreboard::getScore(int competitor, int period)
{
    if (competitor < scores.size() && period < scores[competitor].size())
    {
      return scores[competitor][period];
    }
    return INT_MIN;
}

/**
 * Gets the total score for the competitor over all periods
 * @param  competitor the competitor to get the total score for
 * @return the total score
 */
int Scoreboard::getTotalScore(int competitor) {
  int totalScore = 0;

  if (competitor < 1 || competitor > scores.size())
    return 0; //out of range

  for (int i = 1; i <= scores[competitor].size(); ++i)
  {
    totalScore += getScore(competitor, i);
  }

  return totalScore;
}

void Scoreboard::clearScoreboard() {
   for(unsigned int i = 0; i < scores.size(); ++i) {
      for(unsigned int j = 0; j < scores[i].size(); ++j) {
         scores[i][j] = 0;
      }
   }
}

/** For shits */
int main(int argc,char *argv[])
{

}<commit_msg>Fixed cpp again<commit_after>/**
 * scoreboard.cpp
 *
 * The implementation of the scoreboard.h interface
 */

#include "scoreboard.h"

/**
 * Sets the score for a given competition and a given period
 *
 * If the given competitor or period is negative, then no changes take effect
 * If the given competitor or period is greater than the current board size
 * the size of the scoreboard is increased to address this new score
 *
 * @param competitor the competitor to set the score for
 * @param period the period to set the score for
 * @param score the score to set
 */
void Scoreboard::setScore(int competitor, int period, int score) {
    competitor--;
    period--;

    if (competitor < 0 || period < 0) {
        return;
    }

    if (competitor >= scores.size()) {
        for (int i = scores.size(); i < competitor; i++) {
            scores.push_back(vector<int>());
        }
    }

    if (period >= scores[competitor].size()) {
        for (int i = scores[competitor].size(); i < period; i++) {
            scores[competitor].push_back(0);
        }
    }

    scores[competitor][period] = score;
}

/**
 * Gets the score for a given competitor and period
 * @param  competitor the competitor to get the score for
 * @param  period the period to get the score for
 * @return the score
 */
int Scoreboard::getScore(int competitor, int period)
{
    if (competitor < scores.size() && period < scores[competitor].size())
    {
      return scores[competitor][period];
    }
    return INT_MIN;
}

/**
 * Gets the total score for the competitor over all periods
 * @param  competitor the competitor to get the total score for
 * @return the total score
 */
int Scoreboard::getTotalScore(int competitor) {
  int totalScore = 0;

  if (competitor < 1 || competitor > scores.size())
    return 0; //out of range

  for (int i = 1; i <= scores[competitor].size(); ++i)
  {
    totalScore += getScore(competitor, i);
  }

  return totalScore;
}

void Scoreboard::clearScoreboard() {
   for(unsigned int i = 0; i < scores.size(); ++i) {
      for(unsigned int j = 0; j < scores[i].size(); ++j) {
         scores[i][j] = 0;
      }
   }
}

/** For shits */
int main(int argc,char *argv[])
{

}<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_SPACE_LAGRANGE_CONTINUOUS_HH
#define DUNE_DETAILED_DISCRETIZATIONS_SPACE_LAGRANGE_CONTINUOUS_HH

#include <dune/localfunctions/lagrange/equidistantpoints.hh>
#include <dune/localfunctions/lagrange.hh>

#include <dune/fem_localfunctions/localfunctions/transformations.hh>
#include <dune/fem_localfunctions/basefunctions/genericbasefunctionsetstorage.hh>
#include <dune/fem_localfunctions/basefunctionsetmap/basefunctionsetmap.hh>
#include <dune/fem_localfunctions/space/genericdiscretefunctionspace.hh>

#include "../mapper/fem.hh"
#include "../basefunctionset/fem-localfunctions.hh"
#include "interface.hh"

namespace Dune {
namespace Detailed {
namespace Discretizations {

// forward, to be used in the traits and to allow for specialization
template< class GridPartImp, class RangeFieldImp, unsigned int rangeDim, int polynomialOrder >
class ContinuousLagrangeSpace;

// forward, to allow for specialization
template< class GridPartImp, class RangeFieldImp, unsigned int rangeDim, int polynomialOrder >
class ContinuousLagrangeSpaceTraits;

/**
 *  \brief Traits class for ContinuousLagrangeSpace for dimRange 1.
 */
template< class GridPartImp, class RangeFieldImp, int polynomialOrder >
class ContinuousLagrangeSpaceTraits< GridPartImp, RangeFieldImp, 1, polynomialOrder >
{
public:
  typedef GridPartImp                   GridPartType;
private:
  typedef typename GridPartType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = GridPartType::dimension;
public:
  typedef RangeFieldImp                 RangeFieldType;
  static const unsigned int             dimRange = 1;
  static const int                      polOrder = polynomialOrder;
  typedef ContinuousLagrangeSpace< GridPartType, RangeFieldType, dimRange, polOrder > derived_type;
private:
  typedef ContinuousLagrangeSpaceTraits< GridPartType, RangeFieldType, dimRange, polOrder > ThisType;
  typedef Dune::LagrangeLocalFiniteElement< Dune::EquidistantPointSet,
                                            dimDomain,
                                            DomainFieldType,
                                            RangeFieldType >        FiniteElementType;
  typedef Dune::FemLocalFunctions::BaseFunctionSetMap<  GridPartType,
                                                        FiniteElementType,
                                                        Dune::FemLocalFunctions::NoTransformation,
                                                        Dune::FemLocalFunctions::SimpleStorage,
                                                        polOrder,
                                                        polOrder >  BaseFunctionSetMapType;
public:
  typedef Dune::FemLocalFunctions::DiscreteFunctionSpace< BaseFunctionSetMapType >  BackendType;
  typedef Mapper::FemWrapper< ThisType >                                            MapperType;
  typedef BaseFunctionSet::FemLocalfunctionsWrapper< ThisType >                     BaseFunctionSetType;
  typedef typename BaseFunctionSetType::EntityType                                  EntityType;
private:
  friend class ContinuousLagrangeSpace< GridPartType, RangeFieldType, dimRange, polOrder >;
};

template< class GridPartImp, class RangeFieldImp, unsigned int rangeDim, int polynomialOrder >
class ContinuousLagrangeSpace
  : public SpaceInterface< ContinuousLagrangeSpaceTraits< GridPartImp, RangeFieldImp, rangeDim, polynomialOrder > >
{
public:
  typedef ContinuousLagrangeSpace< GridPartImp, RangeFieldImp, rangeDim, polynomialOrder >        ThisType;
  typedef ContinuousLagrangeSpaceTraits< GridPartImp, RangeFieldImp, rangeDim, polynomialOrder >  Traits;
  typedef SpaceInterface< Traits >                                                                InterfaceType;

  typedef typename Traits::GridPartType   GridPartType;
  typedef typename GridPartType::ctype    DomainFieldType;
  static const unsigned int               dimDomain = GridPartType::dimension;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRange = Traits::dimRange;
  static const int                        polOrder = Traits::polOrder;

  typedef typename Traits::BackendType          BackendType;
  typedef typename Traits::MapperType           MapperType;
  typedef typename Traits::BaseFunctionSetType  BaseFunctionSetType;
  typedef typename Traits::EntityType           EntityType;

private:
  typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType;

public:
  ContinuousLagrangeSpace(const GridPartType& gridPart)
    : gridPart_(gridPart)
    , baseFunctionSetMap_(gridPart_)
    , backend_(const_cast< GridPartType& >(gridPart_), baseFunctionSetMap_)
    , mapper_(*this)
  {}

  const GridPartType& gridPart() const
  {
    return gridPart_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  bool continuous() const
  {
    return true;
  }

  const MapperType& mapper() const
  {
    return mapper_;
  }

  BaseFunctionSetType baseFunctionSet(const EntityType& entity) const
  {
    return BaseFunctionSetType(*this, entity);
  }

private:
  const GridPartType& gridPart_;
  BaseFunctionSetMapType baseFunctionSetMap_;
  const BackendType backend_;
  const MapperType mapper_;
}; // class ContinuousLagrangeSpace

} // namespace Discretizations
} // namespace Detailed
} // namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_SPACE_LAGRANGE_CONTINUOUS_HH
<commit_msg>[space.lagrange-continuous] update<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_SPACE_LAGRANGE_CONTINUOUS_HH
#define DUNE_DETAILED_DISCRETIZATIONS_SPACE_LAGRANGE_CONTINUOUS_HH

#include <dune/common/static_assert.hh>
#include <dune/common/exceptions.hh>

#include <dune/localfunctions/lagrange/equidistantpoints.hh>
#include <dune/localfunctions/lagrange.hh>

#include <dune/fem/space/common/allgeomtypes.hh>

#include <dune/fem_localfunctions/localfunctions/transformations.hh>
#include <dune/fem_localfunctions/basefunctions/genericbasefunctionsetstorage.hh>
#include <dune/fem_localfunctions/basefunctionsetmap/basefunctionsetmap.hh>
#include <dune/fem_localfunctions/space/genericdiscretefunctionspace.hh>

#include <dune/stuff/common/color.hh>

#include "../mapper/fem.hh"
#include "../basefunctionset/fem-localfunctions.hh"
#include "interface.hh"

namespace Dune {
namespace Detailed {
namespace Discretizations {

// forward, to be used in the traits and to allow for specialization
template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDimRows = 1, int rangeDimCols = 1 >
class ContinuousLagrangeSpace;

// forward, to allow for specialization
template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDimRows = 1, int rangeDimCols = 1 >
class ContinuousLagrangeSpaceTraits;

/**
 *  \brief Traits class for ContinuousLagrangeSpace for dimRange 1x1.
 */
template< class GridPartImp, int polynomialOrder, class RangeFieldImp >
class ContinuousLagrangeSpaceTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
{
public:
  typedef GridPartImp                   GridPartType;
  static const int                      polOrder = polynomialOrder;
  dune_static_assert((polOrder >= 1), "ERROR: wrong polOrder given!");
private:
  typedef typename GridPartType::ctype  DomainFieldType;
  static const unsigned int             dimDomain = GridPartType::dimension;
public:
  typedef RangeFieldImp                 RangeFieldType;
  static const unsigned int             dimRangeRows = 1;
  static const unsigned int             dimRangeCols = 1;
  typedef ContinuousLagrangeSpace< GridPartType, polOrder, RangeFieldType, dimRangeRows, dimRangeCols > derived_type;
private:
  typedef ContinuousLagrangeSpaceTraits< GridPartType, polOrder, RangeFieldType, dimRangeRows, dimRangeCols > ThisType;
  typedef Dune::LagrangeLocalFiniteElement< Dune::EquidistantPointSet,
                                            dimDomain,
                                            DomainFieldType,
                                            RangeFieldType >        FiniteElementType;
  typedef Dune::FemLocalFunctions::BaseFunctionSetMap<  GridPartType,
                                                        FiniteElementType,
                                                        Dune::FemLocalFunctions::NoTransformation,
                                                        Dune::FemLocalFunctions::SimpleStorage,
                                                        polOrder,
                                                        polOrder >  BaseFunctionSetMapType;
public:
  typedef Dune::FemLocalFunctions::DiscreteFunctionSpace< BaseFunctionSetMapType >  BackendType;
  typedef MapperWrappedFemDofMapper< typename BackendType::MapperType >             MapperType;
  typedef BaseFunctionSetFemLocalfunctionsWrapper< BaseFunctionSetMapType >         BaseFunctionSetType;
  typedef typename BaseFunctionSetType::EntityType                                  EntityType;
private:
  friend class ContinuousLagrangeSpace< GridPartType, polOrder, RangeFieldType, dimRangeRows, dimRangeCols >;
}; // class ContinuousLagrangeSpaceTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >

template< class GridPartImp, int polynomialOrder, class RangeFieldImp >
class ContinuousLagrangeSpace< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >
  : public SpaceInterface< ContinuousLagrangeSpaceTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > >
{
public:
  typedef ContinuousLagrangeSpaceTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > Traits;

  typedef typename Traits::GridPartType   GridPartType;
  typedef typename GridPartType::ctype    DomainFieldType;
  static const int                        polOrder = Traits::polOrder;
  static const unsigned int               dimDomain = GridPartType::dimension;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRangeRows = Traits::dimRangeRows;
  static const unsigned int               dimRangeCols = Traits::dimRangeCols;

  typedef typename Traits::BackendType          BackendType;
  typedef typename Traits::MapperType           MapperType;
  typedef typename Traits::BaseFunctionSetType  BaseFunctionSetType;
  typedef typename Traits::EntityType           EntityType;

private:
  typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType;

public:
  ContinuousLagrangeSpace(const GridPartType& gridP)
    : gridPart_(checkGridPart(gridP))
    , baseFunctionSetMap_(gridPart_)
    , backend_(const_cast< GridPartType& >(gridPart_), baseFunctionSetMap_)
    , mapper_(backend_.mapper())
  {}

  const GridPartType& gridPart() const
  {
    return gridPart_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  bool continuous() const
  {
    return true;
  }

  const MapperType& mapper() const
  {
    return mapper_;
  }

  BaseFunctionSetType baseFunctionSet(const EntityType& entity) const
  {
    return BaseFunctionSetType(baseFunctionSetMap_, entity);
  }

private:
  static const GridPartType& checkGridPart(const GridPartType& gP)
  {
    // check
    typedef typename Dune::Fem::AllGeomTypes< typename GridPartType::IndexSetType,
                                              typename GridPartType::GridType > AllGeometryTypes;
    const AllGeometryTypes allGeometryTypes(gP.indexSet());
    const std::vector< Dune::GeometryType >& geometryTypes = allGeometryTypes.geomTypes(0);
    if (!(geometryTypes.size() == 1 && geometryTypes[0].isSimplex()))
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                 << " this space is only implemented for simplicial grids!");
    return gP;
  }

  const GridPartType& gridPart_;
  BaseFunctionSetMapType baseFunctionSetMap_;
  const BackendType backend_;
  const MapperType mapper_;
}; // class ContinuousLagrangeSpace< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 >

} // namespace Discretizations
} // namespace Detailed
} // namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_SPACE_LAGRANGE_CONTINUOUS_HH
<|endoftext|>


<commit_before>/*    Copyright (c) 2010-2017, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 */

#include "acceleration.h"
#include "thrust.h"

#include "Tudat/InputOutput/JsonInterface/Mathematics/interpolation.h"

namespace tudat
{

namespace simulation_setup
{

// ThrustDirectionGuidanceSettings

//! Create a `json` object from a shared pointer to a `AccelerationSettings` object.
void to_json( json& jsonObject, const boost::shared_ptr< ThrustDirectionGuidanceSettings >& directionSettings )
{
    if ( ! directionSettings )
    {
        return;
    }
    using namespace json_interface;
    using K = Keys::Propagator::Acceleration::Thrust::Direction;

    const ThrustDirectionGuidanceTypes directionType = directionSettings->thrustDirectionType_;
    jsonObject[ K::type ] = directionType;
    jsonObject[ K::relativeBody ] = directionSettings->relativeBody_;

    switch ( directionType ) {
    case colinear_with_state_segment_thrust_direction:
    {
        boost::shared_ptr< ThrustDirectionFromStateGuidanceSettings > directionFromStateGuidanceSettings
                = boost::dynamic_pointer_cast< ThrustDirectionFromStateGuidanceSettings >( directionSettings );
        enforceNonNullPointer( directionFromStateGuidanceSettings );
        jsonObject[ K::colinearWithVelocity ] = directionFromStateGuidanceSettings->isColinearWithVelocity_;
        jsonObject[ K::towardsRelativeBody ] = directionFromStateGuidanceSettings->directionIsOppositeToVector_;
        return;
    }
    case thrust_direction_from_existing_body_orientation:
    {
        return;
    }
    default:
        handleUnimplementedEnumValue( directionType, thrustDirectionTypes, unsupportedThrustDirectionTypes );
    }
}

//! Create a shared pointer to a `ThrustDirectionGuidanceSettings` object from a `json` object.
void from_json( const json& jsonObject, boost::shared_ptr< ThrustDirectionGuidanceSettings >& directionSettings )
{
    using namespace json_interface;
    using K = Keys::Propagator::Acceleration::Thrust::Direction;

    const ThrustDirectionGuidanceTypes directionType = getValue< ThrustDirectionGuidanceTypes >( jsonObject, K::type );
    const std::string relativeBody = getValue< std::string >( jsonObject, K::relativeBody );

    switch ( directionType ) {
    case colinear_with_state_segment_thrust_direction:
    {
        directionSettings = boost::make_shared< ThrustDirectionFromStateGuidanceSettings >(
                    relativeBody,
                    getValue< bool >( jsonObject, K::colinearWithVelocity),
                    getValue< bool >( jsonObject, K::towardsRelativeBody ) );
        return;
    }
    case thrust_direction_from_existing_body_orientation:
    {
        directionSettings = boost::make_shared< ThrustDirectionGuidanceSettings >( directionType, relativeBody );
        return;
    }
    default:
        handleUnimplementedEnumValue( directionType, thrustDirectionTypes, unsupportedThrustDirectionTypes );
    }
}

// ThrustEngineSettings

//! Create a `json` object from a shared pointer to a `ThrustEngineSettings` object.
void to_json( json& jsonObject, const boost::shared_ptr< ThrustEngineSettings >& magnitudeSettings )
{
    if ( ! magnitudeSettings )
    {
        return;
    }
    using namespace json_interface;
    using K = Keys::Propagator::Acceleration::Thrust::Magnitude;

    const ThrustMagnitudeTypes magnitudeType = magnitudeSettings->thrustMagnitudeGuidanceType_;
    jsonObject[ K::type ] = magnitudeType;
    assignIfNotEmpty( jsonObject, K::originID, magnitudeSettings->thrustOriginId_ );

    switch ( magnitudeType ) {
    case constant_thrust_magnitude:
    {
        boost::shared_ptr< ConstantThrustEngineSettings > contantMagnitudeSettings
                = boost::dynamic_pointer_cast< ConstantThrustEngineSettings >( magnitudeSettings );
        enforceNonNullPointer( contantMagnitudeSettings );
        jsonObject[ K::constantMagnitude ] = contantMagnitudeSettings->thrustMagnitude_;
        jsonObject[ K::specificImpulse ] = contantMagnitudeSettings->specificImpulse_;
        jsonObject[ K::bodyFixedDirection ] = contantMagnitudeSettings->bodyFixedThrustDirection_;
        return;
    }
    case from_engine_properties_thrust_magnitude:
    {
        boost::shared_ptr< FromBodyThrustEngineSettings > fromBodyMagnitudeSettings
                = boost::dynamic_pointer_cast< FromBodyThrustEngineSettings >( magnitudeSettings );
        enforceNonNullPointer( fromBodyMagnitudeSettings );
        jsonObject[ K::useAllEngines ] = fromBodyMagnitudeSettings->useAllEngines_;
        return;
    }
    default:
        handleUnimplementedEnumValue( magnitudeType, thrustMagnitudeTypes, unsupportedThrustMagnitudeTypes );
    }
}

//! Create a shared pointer to a `ThrustEngineSettings` object from a `json` object.
void from_json( const json& jsonObject, boost::shared_ptr< ThrustEngineSettings >& magnitudeSettings )
{
    using namespace json_interface;
    using K = Keys::Propagator::Acceleration::Thrust::Magnitude;

    const ThrustMagnitudeTypes magnitudeType = getValue< ThrustMagnitudeTypes >( jsonObject, K::type );

    switch ( magnitudeType ) {
    case constant_thrust_magnitude:
    {
        ConstantThrustEngineSettings defaults( TUDAT_NAN, TUDAT_NAN );
        magnitudeSettings = boost::make_shared< ConstantThrustEngineSettings >(
                    getValue< double >( jsonObject, K::constantMagnitude ),
                    getValue< double >( jsonObject, K::specificImpulse ),
                    getValue( jsonObject, K::bodyFixedDirection, defaults.bodyFixedThrustDirection_ ) );
        return;
    }
    case from_engine_properties_thrust_magnitude:
    {
        FromBodyThrustEngineSettings defaults;
        magnitudeSettings = boost::make_shared< FromBodyThrustEngineSettings >(
                    getValue( jsonObject, K::useAllEngines, defaults.useAllEngines_ ),
                    getValue( jsonObject, K::originID, defaults.thrustOriginId_ ) );
        return;
    }
    default:
        handleUnimplementedEnumValue( magnitudeType, thrustMagnitudeTypes, unsupportedThrustMagnitudeTypes );
    }
}

// Thrust

//! Create a `json` object from a shared pointer to a `ThrustAccelerationSettings` object.
void to_json( json& jsonObject, const boost::shared_ptr< ThrustAccelerationSettings >& thrustAccelerationSettings )
{
    if ( ! thrustAccelerationSettings )
    {
        return;
    }
    using namespace json_interface;
    using namespace interpolators;
    using K = Keys::Propagator::Acceleration::Thrust;

    jsonObject[ Keys::Propagator::Acceleration::type ] = basic_astrodynamics::thrust_acceleration;

    if ( thrustAccelerationSettings->dataInterpolationSettings_ )
    {
        jsonObject[ K::dataInterpolation ] = thrustAccelerationSettings->dataInterpolationSettings_;
        jsonObject[ K::specificImpulse ] = thrustAccelerationSettings->constantSpecificImpulse_;
        jsonObject[ K::frame ] = thrustAccelerationSettings->thrustFrame_;
        assignIfNotEmpty( jsonObject, K::centralBody, thrustAccelerationSettings->centralBody_ );
    }
    else
    {
        jsonObject[ K::direction ] = thrustAccelerationSettings->thrustDirectionGuidanceSettings_;
        jsonObject[ K::magnitude ] = thrustAccelerationSettings->thrustMagnitudeSettings_;
    }
}

//! Create a shared pointer to a `ThrustAccelerationSettings` object from a `json` object.
void from_json( const json& jsonObject, boost::shared_ptr< ThrustAccelerationSettings >& thrustAccelerationSettings )
{
    using namespace json_interface;
    using namespace interpolators;
    using K = Keys::Propagator::Acceleration::Thrust;

    if ( isDefined( jsonObject, K::dataInterpolation ) )
    {
        thrustAccelerationSettings = boost::make_shared< ThrustAccelerationSettings >(
                    getValue< boost::shared_ptr< DataInterpolationSettings< double, Eigen::Vector3d > > >(
                        jsonObject, K::dataInterpolation ),
                    getValue< double >( jsonObject, K::specificImpulse ),
                    getValue( jsonObject, K::frame ),
                    getValue( jsonObject, K::centralBody ) );
    }
    else
    {
        thrustAccelerationSettings = boost::make_shared< ThrustAccelerationSettings >(
                    getValue< boost::shared_ptr< ThrustDirectionGuidanceSettings > >( jsonObject, K::direction ),
                    getValue< boost::shared_ptr< ThrustEngineSettings > >( jsonObject, K::magnitude ) );
    }
}

} // namespace simulation_setup

} // namespace tudat
<commit_msg>Fix missing template type<commit_after>/*    Copyright (c) 2010-2017, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 */

#include "acceleration.h"
#include "thrust.h"

#include "Tudat/InputOutput/JsonInterface/Mathematics/interpolation.h"

namespace tudat
{

namespace simulation_setup
{

// ThrustDirectionGuidanceSettings

//! Create a `json` object from a shared pointer to a `AccelerationSettings` object.
void to_json( json& jsonObject, const boost::shared_ptr< ThrustDirectionGuidanceSettings >& directionSettings )
{
    if ( ! directionSettings )
    {
        return;
    }
    using namespace json_interface;
    using K = Keys::Propagator::Acceleration::Thrust::Direction;

    const ThrustDirectionGuidanceTypes directionType = directionSettings->thrustDirectionType_;
    jsonObject[ K::type ] = directionType;
    jsonObject[ K::relativeBody ] = directionSettings->relativeBody_;

    switch ( directionType ) {
    case colinear_with_state_segment_thrust_direction:
    {
        boost::shared_ptr< ThrustDirectionFromStateGuidanceSettings > directionFromStateGuidanceSettings
                = boost::dynamic_pointer_cast< ThrustDirectionFromStateGuidanceSettings >( directionSettings );
        enforceNonNullPointer( directionFromStateGuidanceSettings );
        jsonObject[ K::colinearWithVelocity ] = directionFromStateGuidanceSettings->isColinearWithVelocity_;
        jsonObject[ K::towardsRelativeBody ] = directionFromStateGuidanceSettings->directionIsOppositeToVector_;
        return;
    }
    case thrust_direction_from_existing_body_orientation:
    {
        return;
    }
    default:
        handleUnimplementedEnumValue( directionType, thrustDirectionTypes, unsupportedThrustDirectionTypes );
    }
}

//! Create a shared pointer to a `ThrustDirectionGuidanceSettings` object from a `json` object.
void from_json( const json& jsonObject, boost::shared_ptr< ThrustDirectionGuidanceSettings >& directionSettings )
{
    using namespace json_interface;
    using K = Keys::Propagator::Acceleration::Thrust::Direction;

    const ThrustDirectionGuidanceTypes directionType = getValue< ThrustDirectionGuidanceTypes >( jsonObject, K::type );
    const std::string relativeBody = getValue< std::string >( jsonObject, K::relativeBody );

    switch ( directionType ) {
    case colinear_with_state_segment_thrust_direction:
    {
        directionSettings = boost::make_shared< ThrustDirectionFromStateGuidanceSettings >(
                    relativeBody,
                    getValue< bool >( jsonObject, K::colinearWithVelocity),
                    getValue< bool >( jsonObject, K::towardsRelativeBody ) );
        return;
    }
    case thrust_direction_from_existing_body_orientation:
    {
        directionSettings = boost::make_shared< ThrustDirectionGuidanceSettings >( directionType, relativeBody );
        return;
    }
    default:
        handleUnimplementedEnumValue( directionType, thrustDirectionTypes, unsupportedThrustDirectionTypes );
    }
}

// ThrustEngineSettings

//! Create a `json` object from a shared pointer to a `ThrustEngineSettings` object.
void to_json( json& jsonObject, const boost::shared_ptr< ThrustEngineSettings >& magnitudeSettings )
{
    if ( ! magnitudeSettings )
    {
        return;
    }
    using namespace json_interface;
    using K = Keys::Propagator::Acceleration::Thrust::Magnitude;

    const ThrustMagnitudeTypes magnitudeType = magnitudeSettings->thrustMagnitudeGuidanceType_;
    jsonObject[ K::type ] = magnitudeType;
    assignIfNotEmpty( jsonObject, K::originID, magnitudeSettings->thrustOriginId_ );

    switch ( magnitudeType ) {
    case constant_thrust_magnitude:
    {
        boost::shared_ptr< ConstantThrustEngineSettings > contantMagnitudeSettings
                = boost::dynamic_pointer_cast< ConstantThrustEngineSettings >( magnitudeSettings );
        enforceNonNullPointer( contantMagnitudeSettings );
        jsonObject[ K::constantMagnitude ] = contantMagnitudeSettings->thrustMagnitude_;
        jsonObject[ K::specificImpulse ] = contantMagnitudeSettings->specificImpulse_;
        jsonObject[ K::bodyFixedDirection ] = contantMagnitudeSettings->bodyFixedThrustDirection_;
        return;
    }
    case from_engine_properties_thrust_magnitude:
    {
        boost::shared_ptr< FromBodyThrustEngineSettings > fromBodyMagnitudeSettings
                = boost::dynamic_pointer_cast< FromBodyThrustEngineSettings >( magnitudeSettings );
        enforceNonNullPointer( fromBodyMagnitudeSettings );
        jsonObject[ K::useAllEngines ] = fromBodyMagnitudeSettings->useAllEngines_;
        return;
    }
    default:
        handleUnimplementedEnumValue( magnitudeType, thrustMagnitudeTypes, unsupportedThrustMagnitudeTypes );
    }
}

//! Create a shared pointer to a `ThrustEngineSettings` object from a `json` object.
void from_json( const json& jsonObject, boost::shared_ptr< ThrustEngineSettings >& magnitudeSettings )
{
    using namespace json_interface;
    using K = Keys::Propagator::Acceleration::Thrust::Magnitude;

    const ThrustMagnitudeTypes magnitudeType = getValue< ThrustMagnitudeTypes >( jsonObject, K::type );

    switch ( magnitudeType ) {
    case constant_thrust_magnitude:
    {
        ConstantThrustEngineSettings defaults( TUDAT_NAN, TUDAT_NAN );
        magnitudeSettings = boost::make_shared< ConstantThrustEngineSettings >(
                    getValue< double >( jsonObject, K::constantMagnitude ),
                    getValue< double >( jsonObject, K::specificImpulse ),
                    getValue( jsonObject, K::bodyFixedDirection, defaults.bodyFixedThrustDirection_ ) );
        return;
    }
    case from_engine_properties_thrust_magnitude:
    {
        FromBodyThrustEngineSettings defaults;
        magnitudeSettings = boost::make_shared< FromBodyThrustEngineSettings >(
                    getValue( jsonObject, K::useAllEngines, defaults.useAllEngines_ ),
                    getValue( jsonObject, K::originID, defaults.thrustOriginId_ ) );
        return;
    }
    default:
        handleUnimplementedEnumValue( magnitudeType, thrustMagnitudeTypes, unsupportedThrustMagnitudeTypes );
    }
}

// Thrust

//! Create a `json` object from a shared pointer to a `ThrustAccelerationSettings` object.
void to_json( json& jsonObject, const boost::shared_ptr< ThrustAccelerationSettings >& thrustAccelerationSettings )
{
    if ( ! thrustAccelerationSettings )
    {
        return;
    }
    using namespace json_interface;
    using namespace interpolators;
    using K = Keys::Propagator::Acceleration::Thrust;

    jsonObject[ Keys::Propagator::Acceleration::type ] = basic_astrodynamics::thrust_acceleration;

    if ( thrustAccelerationSettings->dataInterpolationSettings_ )
    {
        jsonObject[ K::dataInterpolation ] = thrustAccelerationSettings->dataInterpolationSettings_;
        jsonObject[ K::specificImpulse ] = thrustAccelerationSettings->constantSpecificImpulse_;
        jsonObject[ K::frame ] = thrustAccelerationSettings->thrustFrame_;
        assignIfNotEmpty( jsonObject, K::centralBody, thrustAccelerationSettings->centralBody_ );
    }
    else
    {
        jsonObject[ K::direction ] = thrustAccelerationSettings->thrustDirectionGuidanceSettings_;
        jsonObject[ K::magnitude ] = thrustAccelerationSettings->thrustMagnitudeSettings_;
    }
}

//! Create a shared pointer to a `ThrustAccelerationSettings` object from a `json` object.
void from_json( const json& jsonObject, boost::shared_ptr< ThrustAccelerationSettings >& thrustAccelerationSettings )
{
    using namespace json_interface;
    using namespace interpolators;
    using K = Keys::Propagator::Acceleration::Thrust;

    if ( isDefined( jsonObject, K::dataInterpolation ) )
    {
        thrustAccelerationSettings = boost::make_shared< ThrustAccelerationSettings >(
                    getValue< boost::shared_ptr< DataInterpolationSettings< double, Eigen::Vector3d > > >(
                        jsonObject, K::dataInterpolation ),
                    getValue< double >( jsonObject, K::specificImpulse ),
                    getValue< ThrustFrames >( jsonObject, K::frame ),
                    getValue< std::string >( jsonObject, K::centralBody ) );
    }
    else
    {
        thrustAccelerationSettings = boost::make_shared< ThrustAccelerationSettings >(
                    getValue< boost::shared_ptr< ThrustDirectionGuidanceSettings > >( jsonObject, K::direction ),
                    getValue< boost::shared_ptr< ThrustEngineSettings > >( jsonObject, K::magnitude ) );
    }
}

} // namespace simulation_setup

} // namespace tudat
<|endoftext|>


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

#include <viewer/AutomationSpec.h>
#include <viewer/Settings.h>

#include <gtest/gtest.h>

using namespace filament::viewer;

class ViewSettingsTest : public testing::Test {};

static const char* JSON_TEST_DEFAULTS = R"TXT(
{
    "view": {
        "antiAliasing": "FXAA",
        "taa": {
            "enabled": false,
            "filterWidth": 1.0,
            "feedback": 0.04
        },
        "msaa": {
            "enabled": false,
            "sampleCount": 4,
            "customResolve": false
        },
        "dsr": {
            "enabled": false,
            "minScale": [0.25, 0.25],
            "maxScale": [1.0, 1.0],
            "sharpness": 0.9,
            "enabled": false,
            "homogeneousScaling": false,
            "quality": "MEDIUM"
        },
        "colorGrading": {
            "enabled": true,
            "quality": "MEDIUM",
            "toneMapping": "ACES_LEGACY",
            "genericToneMapper": {
                "contrast": 1.0,
                "midGrayIn": 1.0,
                "midGrayOut": 1.0,
                "hdrMax": 16.0
            },
            "luminanceScaling": false,
            "gamutMapping": false,
            "exposure": 0,
            "nightAdaptation": 0,
            "temperature": 0,
            "tint": 0,
            "outRed": [1.0, 0.0, 0.0],
            "outGreen": [0.0, 1.0, 0.0],
            "outBlue": [0.0, 0.0, 1.0],
            "shadows": [1.0, 1.0, 1.0, 0.0],
            "midtones": [1.0, 1.0, 1.0, 0.0],
            "highlights": [1.0, 1.0, 1.0, 0.0],
            "ranges": [0.0, 0.333, 0.550, 1.0],
            "contrast": 1.0,
            "vibrance": 1.0,
            "saturation": 1.0,
            "slope": [1.0, 1.0, 1.0],
            "offset": [0.0, 0.0, 0.0],
            "power": [1.0, 1.0, 1.0],
            "gamma": [1.0, 1.0, 1.0],
            "midPoint": [1.0, 1.0, 1.0],
            "scale": [1.0, 1.0, 1.0],
            "linkedCurves": false
        },
        "ssao": {
            "enabled": false,
            "radius": 0.3,
            "power": 1.0,
            "bias": 0.0005,
            "resolution": 0.5,
            "intensity": 1.0,
            "quality": "LOW",
            "upsampling": "LOW",
            "minHorizonAngleRad": 0.0,
            "ssct": {
                "enabled": false,
                "lightConeRad": 1.0,
                "shadowDistance": 0.3,
                "contactDistanceMax": 1.0,
                "intensity": 0.8,
                "lightDirection": [0, -1, 0],
                "depthBias": 0.01,
                "depthSlopeBias": 0.01,
                "sampleCount": 4
            }
        },
        "bloom": {
            "enabled": false,
            "strength": 0.10,
            "resolution": 360,
            "anamorphism": 1.0,
            "levels": 6,
            "blendMode": "ADD",
            "threshold": true,
            "highlight": 1000.0
        },
        "fog": {
            "enabled": false,
            "distance": 0.0,
            "maximumOpacity": 1.0,
            "height": 0.0,
            "heightFalloff": 1.0,
            "color": [0.5, 0.5, 0.5],
            "density": 0.1,
            "inScatteringStart": 0.0,
            "inScatteringSize": -1.0,
            "fogColorFromIbl": false
        },
        "dof": {
            "enabled": false,
            "cocScale": 1.0,
            "maxApertureDiameter": 0.01
        },
        "vignette": {
            "enabled": false,
            "midPoint": 0.5,
            "roundness": 0.5,
            "feather": 0.5,
            "color": [0, 0, 0, 1]
        },
        "dithering": "TEMPORAL",
        "renderQuality": {
            "hdrColorBuffer": "HIGH"
        },
        "dynamicLighting": {
            "zLightNear": 5,
            "zLightFar": 100,
        },
        "shadowType": "PCF",
        "vsmShadowOptions": {
            "anisotropy": 1
        },
        "postProcessingEnabled": true
    }
}
)TXT";

static const char* JSON_TEST_MATERIAL = R"TXT(
"material": {
  "scalar": { "foo": 5.0, "bar": 2.0 },
  "float3": { "baz": [1, 2, 3] }
})TXT";

static const char* JSON_TEST_AUTOMATION = R"TXT([{
    "name": "test_72_cases",
    "base": { "view.bloom.strength": 0.5 },
    "permute": {
        "view.bloom.enabled": [false, true],
        "material.scalar.metallicFactor": [0.0, 0.2, 0.4, 0.6, 0.8, 1.0],
        "material.scalar.roughnessFactor": [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
    }
}])TXT";

TEST_F(ViewSettingsTest, JsonTestDefaults) {
    JsonSerializer serializer;
    Settings settings1;
    ASSERT_TRUE(serializer.readJson(JSON_TEST_DEFAULTS, strlen(JSON_TEST_DEFAULTS), &settings1));

    ASSERT_TRUE(settings1.view.bloom.threshold);

    Settings settings2;
    ASSERT_TRUE(serializer.readJson("{}", strlen("{}"), &settings2));
    ASSERT_FALSE(serializer.readJson("{ badly_formed }", strlen("{ badly_formed }"), &settings2));

    Settings settings3;
    ASSERT_EQ(serializer.writeJson(settings2), serializer.writeJson(settings3));
}

TEST_F(ViewSettingsTest, JsonTestSerialization) {
    auto canParse = [](bool parseResult, std::string json) {
        if (parseResult) {
            return testing::AssertionSuccess() << "Settings can be serialized.";
        } else {
            return testing::AssertionFailure() << "JSON has errors:\n" << json.c_str() << std::endl;
        }
    };

    JsonSerializer serializer;
    Settings outSettings = {};
    std::string jsonstr = serializer.writeJson(outSettings);
    Settings inSettings = {};
    bool result = serializer.readJson(jsonstr.c_str(), jsonstr.size(), &inSettings);
    ASSERT_TRUE(canParse(result, jsonstr));
}

TEST_F(ViewSettingsTest, JsonTestMaterial) {
    JsonSerializer serializer;
    Settings settings;
    std::string js = "{" + std::string(JSON_TEST_MATERIAL) + "}";
    ASSERT_TRUE(serializer.readJson(js.c_str(), js.size(), &settings));
    std::string serialized = serializer.writeJson(settings);
    ASSERT_PRED_FORMAT2(testing::IsSubstring, "\"baz\": [1, 2, 3]", serialized);
}

TEST_F(ViewSettingsTest, DefaultAutomationSpec) {
    AutomationSpec* specs = AutomationSpec::generateDefaultTestCases();
    ASSERT_TRUE(specs);
    ASSERT_EQ(specs->size(), 66);

    Settings settings;

    ASSERT_TRUE(specs->get(0, &settings));
    ASSERT_FALSE(settings.view.postProcessingEnabled);
    ASSERT_EQ(settings.view.dithering, Dithering::TEMPORAL);

    ASSERT_TRUE(specs->get(1, &settings));
    ASSERT_TRUE(settings.view.postProcessingEnabled);

    ASSERT_TRUE(specs->get(65, &settings));
    ASSERT_FALSE(specs->get(66, &settings));

    delete specs;
}

TEST_F(ViewSettingsTest, CustomAutomationSpec) {
    AutomationSpec* spec = AutomationSpec::generate(JSON_TEST_AUTOMATION,
            strlen(JSON_TEST_AUTOMATION));
    ASSERT_TRUE(spec);
    ASSERT_EQ(spec->size(), 72);
    delete spec;
}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>Remove unit test that is not very useful.<commit_after>/*
 * Copyright 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <viewer/AutomationSpec.h>
#include <viewer/Settings.h>

#include <gtest/gtest.h>

using namespace filament::viewer;

class ViewSettingsTest : public testing::Test {};

static const char* JSON_TEST_DEFAULTS = R"TXT(
{
    "view": {
        "antiAliasing": "FXAA",
        "taa": {
            "enabled": false,
            "filterWidth": 1.0,
            "feedback": 0.04
        },
        "msaa": {
            "enabled": false,
            "sampleCount": 4,
            "customResolve": false
        },
        "dsr": {
            "enabled": false,
            "minScale": [0.25, 0.25],
            "maxScale": [1.0, 1.0],
            "sharpness": 0.9,
            "enabled": false,
            "homogeneousScaling": false,
            "quality": "MEDIUM"
        },
        "colorGrading": {
            "enabled": true,
            "quality": "MEDIUM",
            "toneMapping": "ACES_LEGACY",
            "genericToneMapper": {
                "contrast": 1.0,
                "midGrayIn": 1.0,
                "midGrayOut": 1.0,
                "hdrMax": 16.0
            },
            "luminanceScaling": false,
            "gamutMapping": false,
            "exposure": 0,
            "nightAdaptation": 0,
            "temperature": 0,
            "tint": 0,
            "outRed": [1.0, 0.0, 0.0],
            "outGreen": [0.0, 1.0, 0.0],
            "outBlue": [0.0, 0.0, 1.0],
            "shadows": [1.0, 1.0, 1.0, 0.0],
            "midtones": [1.0, 1.0, 1.0, 0.0],
            "highlights": [1.0, 1.0, 1.0, 0.0],
            "ranges": [0.0, 0.333, 0.550, 1.0],
            "contrast": 1.0,
            "vibrance": 1.0,
            "saturation": 1.0,
            "slope": [1.0, 1.0, 1.0],
            "offset": [0.0, 0.0, 0.0],
            "power": [1.0, 1.0, 1.0],
            "gamma": [1.0, 1.0, 1.0],
            "midPoint": [1.0, 1.0, 1.0],
            "scale": [1.0, 1.0, 1.0],
            "linkedCurves": false
        },
        "ssao": {
            "enabled": false,
            "radius": 0.3,
            "power": 1.0,
            "bias": 0.0005,
            "resolution": 0.5,
            "intensity": 1.0,
            "quality": "LOW",
            "upsampling": "LOW",
            "minHorizonAngleRad": 0.0,
            "ssct": {
                "enabled": false,
                "lightConeRad": 1.0,
                "shadowDistance": 0.3,
                "contactDistanceMax": 1.0,
                "intensity": 0.8,
                "lightDirection": [0, -1, 0],
                "depthBias": 0.01,
                "depthSlopeBias": 0.01,
                "sampleCount": 4
            }
        },
        "bloom": {
            "enabled": false,
            "strength": 0.10,
            "resolution": 360,
            "anamorphism": 1.0,
            "levels": 6,
            "blendMode": "ADD",
            "threshold": true,
            "highlight": 1000.0
        },
        "fog": {
            "enabled": false,
            "distance": 0.0,
            "maximumOpacity": 1.0,
            "height": 0.0,
            "heightFalloff": 1.0,
            "color": [0.5, 0.5, 0.5],
            "density": 0.1,
            "inScatteringStart": 0.0,
            "inScatteringSize": -1.0,
            "fogColorFromIbl": false
        },
        "dof": {
            "enabled": false,
            "cocScale": 1.0,
            "maxApertureDiameter": 0.01
        },
        "vignette": {
            "enabled": false,
            "midPoint": 0.5,
            "roundness": 0.5,
            "feather": 0.5,
            "color": [0, 0, 0, 1]
        },
        "dithering": "TEMPORAL",
        "renderQuality": {
            "hdrColorBuffer": "HIGH"
        },
        "dynamicLighting": {
            "zLightNear": 5,
            "zLightFar": 100,
        },
        "shadowType": "PCF",
        "vsmShadowOptions": {
            "anisotropy": 1
        },
        "postProcessingEnabled": true
    }
}
)TXT";

static const char* JSON_TEST_MATERIAL = R"TXT(
"material": {
  "scalar": { "foo": 5.0, "bar": 2.0 },
  "float3": { "baz": [1, 2, 3] }
})TXT";

static const char* JSON_TEST_AUTOMATION = R"TXT([{
    "name": "test_72_cases",
    "base": { "view.bloom.strength": 0.5 },
    "permute": {
        "view.bloom.enabled": [false, true],
        "material.scalar.metallicFactor": [0.0, 0.2, 0.4, 0.6, 0.8, 1.0],
        "material.scalar.roughnessFactor": [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
    }
}])TXT";

TEST_F(ViewSettingsTest, JsonTestDefaults) {
    JsonSerializer serializer;
    Settings settings1;
    ASSERT_TRUE(serializer.readJson(JSON_TEST_DEFAULTS, strlen(JSON_TEST_DEFAULTS), &settings1));

    ASSERT_TRUE(settings1.view.bloom.threshold);

    Settings settings2;
    ASSERT_TRUE(serializer.readJson("{}", strlen("{}"), &settings2));
    ASSERT_FALSE(serializer.readJson("{ badly_formed }", strlen("{ badly_formed }"), &settings2));

    Settings settings3;
    ASSERT_EQ(serializer.writeJson(settings2), serializer.writeJson(settings3));
}

TEST_F(ViewSettingsTest, JsonTestSerialization) {
    auto canParse = [](bool parseResult, std::string json) {
        if (parseResult) {
            return testing::AssertionSuccess() << "Settings can be serialized.";
        } else {
            return testing::AssertionFailure() << "JSON has errors:\n" << json.c_str() << std::endl;
        }
    };

    JsonSerializer serializer;
    Settings outSettings = {};
    std::string jsonstr = serializer.writeJson(outSettings);
    Settings inSettings = {};
    bool result = serializer.readJson(jsonstr.c_str(), jsonstr.size(), &inSettings);
    ASSERT_TRUE(canParse(result, jsonstr));
}

TEST_F(ViewSettingsTest, JsonTestMaterial) {
    JsonSerializer serializer;
    Settings settings;
    std::string js = "{" + std::string(JSON_TEST_MATERIAL) + "}";
    ASSERT_TRUE(serializer.readJson(js.c_str(), js.size(), &settings));
    std::string serialized = serializer.writeJson(settings);
    ASSERT_PRED_FORMAT2(testing::IsSubstring, "\"baz\": [1, 2, 3]", serialized);
}

TEST_F(ViewSettingsTest, CustomAutomationSpec) {
    AutomationSpec* spec = AutomationSpec::generate(JSON_TEST_AUTOMATION,
            strlen(JSON_TEST_AUTOMATION));
    ASSERT_TRUE(spec);
    ASSERT_EQ(spec->size(), 72);
    delete spec;
}

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


<commit_before><commit_msg>Remove floating point suffix for glsl<commit_after><|endoftext|>


<commit_before>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_THERMALBLOCK_BINDINGS_GENERATOR_HH
#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_THERMALBLOCK_BINDINGS_GENERATOR_HH

#ifdef ENABLE_MPI
# undef ENABLE_MPI
#endif
#define ENABLE_MPI 0

#include <dune/stuff/common/disable_warnings.hh>
# include "config.h"

# if HAVE_ALUGRID
#   include <dune/grid/alugrid.hh>
# endif
# include <dune/grid/yaspgrid.hh>

# include "thermalblock.hh"

template< class G, Dune::GDT::ChooseSpaceBackend s, Dune::Stuff::LA::ChooseBackend l >
class PbCgExample
  : public CgExample< G, s, l >
{
  typedef CgExample< G, s, l > BaseType;

public:
  using typename BaseType::DiscretizationType;

  template< class... Args >
  explicit PbCgExample(Args&& ...args)
    : BaseType(std::forward< Args >(args)...)
  {}

  DiscretizationType* pb_discretization_and_return_ptr()
  {
    return new DiscretizationType(this->discretization());
  }
}; // class PbCgExample

#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_THERMALBLOCK_BINDINGS_GENERATOR_HH
<commit_msg>[examples...thermalblock] disable PARMETIS<commit_after>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_THERMALBLOCK_BINDINGS_GENERATOR_HH
#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_THERMALBLOCK_BINDINGS_GENERATOR_HH

#ifdef ENABLE_MPI
# undef ENABLE_MPI
#endif
#define ENABLE_MPI 0

#ifdef ENABLE_PARMETIS
# undef ENABLE_PARMETIS
#endif
#define ENABLE_PARMETIS 0

#include <dune/stuff/common/disable_warnings.hh>
# include "config.h"

# if HAVE_ALUGRID
#   include <dune/grid/alugrid.hh>
# endif
# include <dune/grid/yaspgrid.hh>

# include "thermalblock.hh"

template< class G, Dune::GDT::ChooseSpaceBackend s, Dune::Stuff::LA::ChooseBackend l >
class PbCgExample
  : public CgExample< G, s, l >
{
  typedef CgExample< G, s, l > BaseType;

public:
  using typename BaseType::DiscretizationType;

  template< class... Args >
  explicit PbCgExample(Args&& ...args)
    : BaseType(std::forward< Args >(args)...)
  {}

  DiscretizationType* pb_discretization_and_return_ptr()
  {
    return new DiscretizationType(this->discretization());
  }
}; // class PbCgExample

#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_THERMALBLOCK_BINDINGS_GENERATOR_HH
<|endoftext|>


<commit_before>//
//  LemonScriptSymbolTable.cpp
//  lemonscript
//
//  Created by Donald Pinckney on 2/6/16.
//  Copyright © 2016 Donald Pinckney. All rights reserved.
//

#include "LemonScriptSymbolTable.h"

#include <stdlib.h>
#include <iostream>

std::vector<void *> LemonScriptSymbolTable::variableAddressHeap;

void LemonScriptSymbolTable::declareVariable(int line, const std::string &name, DataType type, void *pointerToValue) {
    if(variableAddresses.find(name) != variableAddresses.end()) {
        throw "Line " + std::to_string(line) + ":\nDuplicate variable definition: " + name;
    }

    void *address;
    switch (type) {
        case INT:
            address = malloc(sizeof(int));
            memcpy(address, pointerToValue, sizeof(int));
            break;

        case FLOAT:
            address = malloc(sizeof(float));
            memcpy(address, pointerToValue, sizeof(float));
            break;

        case BOOLEAN:
            address = malloc(sizeof(bool));
            memcpy(address, pointerToValue, sizeof(bool));
            break;

        default:
            break;
    }

    variableAddresses[name] = address;
    variableTypes[name] = type;

    variableAddressHeap.push_back(address);
}

void * LemonScriptSymbolTable::addressOfVariable(const std::string &variableName) const {
    auto it = variableAddresses.find(variableName);
    if(it != variableAddresses.end()) {
        return it->second;
    } else {
        return NULL;
    }
}

DataType LemonScriptSymbolTable::typeOfVariable(const std::string &variableName) const {
    auto it = variableTypes.find(variableName);

    if(it != variableTypes.end()) {
        return it->second;
    } else {
        return INT;
    }
}

void LemonScriptSymbolTable::freeVariables() {

    for (int i = 0; i < variableAddressHeap.size(); i++) {
        void *varAddress = variableAddressHeap[i];
        free(varAddress);
    }

    variableAddressHeap.clear();
}
<commit_msg>Add missing include<commit_after>//
//  LemonScriptSymbolTable.cpp
//  lemonscript
//
//  Created by Donald Pinckney on 2/6/16.
//  Copyright © 2016 Donald Pinckney. All rights reserved.
//

#include "LemonScriptSymbolTable.h"

#include <stdlib.h>
#include <string.h>
#include <iostream>

std::vector<void *> LemonScriptSymbolTable::variableAddressHeap;

void LemonScriptSymbolTable::declareVariable(int line, const std::string &name, DataType type, void *pointerToValue) {
    if(variableAddresses.find(name) != variableAddresses.end()) {
        throw "Line " + std::to_string(line) + ":\nDuplicate variable definition: " + name;
    }

    void *address;
    switch (type) {
        case INT:
            address = malloc(sizeof(int));
            memcpy(address, pointerToValue, sizeof(int));
            break;

        case FLOAT:
            address = malloc(sizeof(float));
            memcpy(address, pointerToValue, sizeof(float));
            break;

        case BOOLEAN:
            address = malloc(sizeof(bool));
            memcpy(address, pointerToValue, sizeof(bool));
            break;

        default:
            break;
    }

    variableAddresses[name] = address;
    variableTypes[name] = type;

    variableAddressHeap.push_back(address);
}

void * LemonScriptSymbolTable::addressOfVariable(const std::string &variableName) const {
    auto it = variableAddresses.find(variableName);
    if(it != variableAddresses.end()) {
        return it->second;
    } else {
        return NULL;
    }
}

DataType LemonScriptSymbolTable::typeOfVariable(const std::string &variableName) const {
    auto it = variableTypes.find(variableName);

    if(it != variableTypes.end()) {
        return it->second;
    } else {
        return INT;
    }
}

void LemonScriptSymbolTable::freeVariables() {

    for (int i = 0; i < variableAddressHeap.size(); i++) {
        void *varAddress = variableAddressHeap[i];
        free(varAddress);
    }

    variableAddressHeap.clear();
}
<|endoftext|>


<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "extproc/extproc_job.hpp"
#include "extproc/extproc_pool.hpp"
#include "extproc/extproc_worker.hpp"

extproc_job_t::extproc_job_t(extproc_pool_t *_pool,
                             bool (*worker_fn) (read_stream_t *, write_stream_t *),
                             signal_t *_user_interruptor) :
    pool(_pool),
    user_error(false),
    user_interruptor(_user_interruptor),
    combined_interruptor(pool->get_shutdown_signal())
{
    if (user_interruptor != NULL) {
        combined_interruptor.add(user_interruptor);
    }

    worker_lock.create(pool->get_worker_semaphore(), &combined_interruptor);

    worker_lock.get()->get_value()->acquired(&combined_interruptor);
    worker_lock.get()->get_value()->run_job(worker_fn);
}

extproc_job_t::~extproc_job_t() {
    assert_thread();
    worker_lock.get()->get_value()->released(user_error, user_interruptor);
}

// All data written and read by the user must be accounted for, or things will break
read_stream_t *extproc_job_t::read_stream() {
    assert_thread();
    return worker_lock.get()->get_value()->get_read_stream();
}

write_stream_t *extproc_job_t::write_stream() {
    assert_thread();
    return worker_lock.get()->get_value()->get_write_stream();
}

void extproc_job_t::worker_error() {
    user_error = true;
}
<commit_msg>fixed extprocs breaking if interrupted during construction<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "extproc/extproc_job.hpp"
#include "extproc/extproc_pool.hpp"
#include "extproc/extproc_worker.hpp"

extproc_job_t::extproc_job_t(extproc_pool_t *_pool,
                             bool (*worker_fn) (read_stream_t *, write_stream_t *),
                             signal_t *_user_interruptor) :
    pool(_pool),
    user_error(false),
    user_interruptor(_user_interruptor),
    combined_interruptor(pool->get_shutdown_signal())
{
    if (user_interruptor != NULL) {
        combined_interruptor.add(user_interruptor);
    }

    worker_lock.create(pool->get_worker_semaphore(), &combined_interruptor);

    try {
        worker_lock.get()->get_value()->acquired(&combined_interruptor);
        worker_lock.get()->get_value()->run_job(worker_fn);
    } catch (...) {
        worker_lock.get()->get_value()->released(user_error, user_interruptor);
        throw;
    }
}

extproc_job_t::~extproc_job_t() {
    assert_thread();
    worker_lock.get()->get_value()->released(user_error, user_interruptor);
}

// All data written and read by the user must be accounted for, or things will break
read_stream_t *extproc_job_t::read_stream() {
    assert_thread();
    return worker_lock.get()->get_value()->get_read_stream();
}

write_stream_t *extproc_job_t::write_stream() {
    assert_thread();
    return worker_lock.get()->get_value()->get_write_stream();
}

void extproc_job_t::worker_error() {
    user_error = true;
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File FilterBenchmark.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Outputs time when solution first exceeds a threshold value.
//
///////////////////////////////////////////////////////////////////////////////

#include <CardiacEPSolver/Filters/FilterBenchmark.h>

namespace Nektar
{
    namespace SolverUtils
    {
        std::string FilterBenchmark::className = GetFilterFactory().RegisterCreatorFunction("Benchmark", FilterBenchmark::create);

        FilterBenchmark::FilterBenchmark(
            const LibUtilities::SessionReaderSharedPtr &pSession,
            const std::map<std::string, std::string> &pParams) :
            Filter(pSession)
        {
            ASSERTL0(pParams.find("ThresholdValue") != pParams.end(),
                     "Missing parameter 'ThresholdValue'.");
            m_thresholdValue = atof(pParams.find("ThresholdValue")->second.c_str());
            ASSERTL0(pParams.find("InitialValue") != pParams.end(),
                     "Missing parameter 'InitialValue'.");
            m_initialValue = atof(pParams.find("InitialValue")->second.c_str());
            ASSERTL0(!(pParams.find("OutputFile")->second.empty()),
                     "Missing parameter 'OutputFile'.");
            m_outputFile = pParams.find("OutputFile")->second;

            if (pParams.find("StartTime") != pParams.end())
            {
                m_startTime = atof(pParams.find("StartTime")->second.c_str());
            }

            m_fld = MemoryManager<LibUtilities::FieldIO>::AllocateSharedPtr(pSession->GetComm());

        }

        FilterBenchmark::~FilterBenchmark()
        {

        }

        void FilterBenchmark::v_Initialise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
        {
            //m_threshold = Array<OneD, NekDouble> (pFields[0]->GetNpoints(), m_initialValue);
            m_idx = Array<OneD, int> (pFields[0]->GetNpoints(), 0);
            m_polarity = Array<OneD, int> (pFields[0]->GetNpoints(), -1);
        }

        void FilterBenchmark::v_Update(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
        {
            if (time < m_startTime)
            {
                return;
            }

            int i;
            NekDouble timestep = pFields[0]->GetSession()->GetParameter("TimeStep");

            for (i = 0; i < pFields[0]->GetNpoints(); ++i)
            {
                if ((m_polarity[i] == -1 &&
                        pFields[0]->GetPhys()[i] > m_thresholdValue) ||
                    (m_polarity[i] == 1 &&
                        pFields[0]->GetPhys()[i] < m_thresholdValue))
                {
                    if (m_idx[i] == m_threshold.size())
                    {
                        m_threshold.push_back(Array<OneD, NekDouble>(
                                    pFields[0]->GetNpoints(), m_initialValue));
                    }
                    m_threshold[m_idx[i]][i] = time;
                    m_idx[i]++;
                    m_polarity[i] *= -1;
                }
            }

            int max_idx = Vmath::Vmax(pFields[0]->GetNpoints(), m_idx, 1);
            pFields[0]->GetSession()->GetComm()->AllReduce(max_idx,
                                    LibUtilities::ReduceMax);
            if (m_threshold.size() == max_idx)
            {
                m_threshold.push_back(Array<OneD, NekDouble>(
                                    pFields[0]->GetNpoints(), m_initialValue));
            }

        }

        void FilterBenchmark::v_Finalise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
        {
            for (int i = 0; i < m_threshold.size(); ++i)
            {
            std::stringstream vOutputFilename;
            vOutputFilename << m_outputFile << "_" << i << ".fld";

            std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef
                = pFields[0]->GetFieldDefinitions();
            std::vector<std::vector<NekDouble> > FieldData(FieldDef.size());

            Array<OneD, NekDouble> vCoeffs(pFields[0]->GetNcoeffs());
            pFields[0]->FwdTrans_IterPerExp(m_threshold[i], vCoeffs);

            // copy Data into FieldData and set variable
            for(int i = 0; i < FieldDef.size(); ++i)
            {
                // Could do a search here to find correct variable
                FieldDef[i]->m_fields.push_back("m");
                pFields[0]->AppendFieldData(FieldDef[i], FieldData[i], vCoeffs);
            }

            m_fld->Write(vOutputFilename.str(),FieldDef,FieldData);
            }
        }

        bool FilterBenchmark::v_IsTimeDependent()
        {
            return true;
        }
    }
}
<commit_msg>Minor changes to benchmark filter.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File FilterBenchmark.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Outputs time when solution first exceeds a threshold value.
//
///////////////////////////////////////////////////////////////////////////////

#include <CardiacEPSolver/Filters/FilterBenchmark.h>

namespace Nektar
{
    namespace SolverUtils
    {
        std::string FilterBenchmark::className = GetFilterFactory().RegisterCreatorFunction("Benchmark", FilterBenchmark::create);

        FilterBenchmark::FilterBenchmark(
            const LibUtilities::SessionReaderSharedPtr &pSession,
            const std::map<std::string, std::string> &pParams) :
            Filter(pSession)
        {
            ASSERTL0(pParams.find("ThresholdValue") != pParams.end(),
                     "Missing parameter 'ThresholdValue'.");
            m_thresholdValue = atof(pParams.find("ThresholdValue")->second.c_str());
            ASSERTL0(pParams.find("InitialValue") != pParams.end(),
                     "Missing parameter 'InitialValue'.");
            m_initialValue = atof(pParams.find("InitialValue")->second.c_str());
            ASSERTL0(!(pParams.find("OutputFile")->second.empty()),
                     "Missing parameter 'OutputFile'.");
            m_outputFile = pParams.find("OutputFile")->second;

            if (pParams.find("StartTime") != pParams.end())
            {
                m_startTime = atof(pParams.find("StartTime")->second.c_str());
            }

            m_fld = MemoryManager<LibUtilities::FieldIO>::AllocateSharedPtr(pSession->GetComm());

        }

        FilterBenchmark::~FilterBenchmark()
        {

        }

        void FilterBenchmark::v_Initialise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
        {
            m_threshold.push_back(Array<OneD, NekDouble>(
                                    pFields[0]->GetNpoints(), m_initialValue));
            m_idx = Array<OneD, int> (pFields[0]->GetNpoints(), 0);
            m_polarity = Array<OneD, int> (pFields[0]->GetNpoints(), -1);
        }

        void FilterBenchmark::v_Update(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
        {
            if (time < m_startTime)
            {
                return;
            }

            int i;
            NekDouble timestep = pFields[0]->GetSession()->GetParameter("TimeStep");

            for (i = 0; i < pFields[0]->GetNpoints(); ++i)
            {
                if ((m_polarity[i] == -1 &&
                        pFields[0]->GetPhys()[i] > m_thresholdValue) ||
                    (m_polarity[i] == 1 &&
                        pFields[0]->GetPhys()[i] < m_thresholdValue))
                {
                    m_threshold[m_idx[i]][i] = time;
                    m_idx[i]++;
                    m_polarity[i] *= -1;
                }
            }

            int max_idx = Vmath::Vmax(pFields[0]->GetNpoints(), m_idx, 1);
            pFields[0]->GetSession()->GetComm()->AllReduce(max_idx,
                                    LibUtilities::ReduceMax);
            if (m_threshold.size() == max_idx)
            {
                m_threshold.push_back(Array<OneD, NekDouble>(
                                    pFields[0]->GetNpoints(), m_initialValue));
            }

        }

        void FilterBenchmark::v_Finalise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
        {
            for (int i = 0; i < m_threshold.size() - 1; ++i)
            {
            std::stringstream vOutputFilename;
            vOutputFilename << m_outputFile << "_" << i << ".fld";

            std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef
                = pFields[0]->GetFieldDefinitions();
            std::vector<std::vector<NekDouble> > FieldData(FieldDef.size());

            Array<OneD, NekDouble> vCoeffs(pFields[0]->GetNcoeffs());
            pFields[0]->FwdTrans_IterPerExp(m_threshold[i], vCoeffs);

            // copy Data into FieldData and set variable
            for(int i = 0; i < FieldDef.size(); ++i)
            {
                // Could do a search here to find correct variable
                FieldDef[i]->m_fields.push_back("m");
                pFields[0]->AppendFieldData(FieldDef[i], FieldData[i], vCoeffs);
            }

            m_fld->Write(vOutputFilename.str(),FieldDef,FieldData);
            }
        }

        bool FilterBenchmark::v_IsTimeDependent()
        {
            return true;
        }
    }
}
<|endoftext|>


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

#include "chrome/browser/component_updater/component_updater_service.h"

#include <algorithm>
#include <string>
#include <vector>

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/metrics/histogram.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "net/url_request/url_request_context_getter.h"

namespace {
// Default time constants.
const int kDelayOneMinute = 60;
const int kDelayOneHour = kDelayOneMinute * 60;

// Debug values you can pass to --component-updater-debug=<value>.
const char kDebugFastUpdate[] = "fast-update";
const char kDebugOutOfProcess[] = "out-of-process";

bool HasDebugValue(const std::vector<std::string>& vec, const char* test) {
  if (vec.empty())
    return 0;
  return (std::find(vec.begin(), vec.end(), test) != vec.end());
}

// The request extra information is the OS and architecture, this helps
// the server select the right package to be delivered.
const char kExtraInfo[] =
#if defined(OS_MACOSX)
  #if defined(__amd64__)
    "os=mac&arch=x64";
  #elif defined(__i386__)
     "os=mac&arch=x86";
  #else
     #error "unknown mac architecture"
  #endif
#elif defined(OS_WIN)
  #if defined(_WIN64)
    "os=win&arch=x64";
  #elif defined(_WIN32)
    "os=win&arch=x86";
  #else
    #error "unknown windows architecture"
  #endif
#elif defined(OS_LINUX)
  #if defined(__amd64__)
    "os=linux&arch=x64";
  #elif defined(__i386__)
    "os=linux&arch=x86";
  #else
    "os=linux&arch=unknown";
  #endif
#elif defined(OS_CHROMEOS)
  #if defined(__i386__)
    "os=cros&arch=x86";
  #else
    // TODO(cpu): Fix this for ARM.
    "os=cros&arch=unknown";
  #endif
#else
    #error "unknown os or architecture"
#endif

}  // namespace

class ChromeConfigurator : public ComponentUpdateService::Configurator {
 public:
  ChromeConfigurator(const CommandLine* cmdline,
                     net::URLRequestContextGetter* url_request_getter);

  virtual ~ChromeConfigurator() {}

  virtual int InitialDelay() OVERRIDE;
  virtual int NextCheckDelay() OVERRIDE;
  virtual int StepDelay() OVERRIDE;
  virtual int MinimumReCheckWait() OVERRIDE;
  virtual GURL UpdateUrl() OVERRIDE;
  virtual const char* ExtraRequestParams() OVERRIDE;
  virtual size_t UrlSizeLimit() OVERRIDE;
  virtual net::URLRequestContextGetter* RequestContext() OVERRIDE;
  virtual bool InProcess() OVERRIDE;
  virtual void OnEvent(Events event, int val) OVERRIDE;

 private:
  net::URLRequestContextGetter* url_request_getter_;
  bool fast_update_;
  bool out_of_process_;
  std::string extra_info_;
};

ChromeConfigurator::ChromeConfigurator(const CommandLine* cmdline,
    net::URLRequestContextGetter* url_request_getter)
      : url_request_getter_(url_request_getter) {
  // Parse comma-delimited debug flags.
  std::vector<std::string> debug_values;
  Tokenize(cmdline->GetSwitchValueASCII(switches::kComponentUpdaterDebug),
      ",", &debug_values);
  fast_update_ = HasDebugValue(debug_values, kDebugFastUpdate);
  out_of_process_ = HasDebugValue(debug_values, kDebugOutOfProcess);
}

int ChromeConfigurator::InitialDelay() {
  return  fast_update_ ? 1 : (6 * kDelayOneMinute);
}

int ChromeConfigurator::NextCheckDelay() {
  return fast_update_ ? 3 : (4 * kDelayOneHour);
}

int ChromeConfigurator::StepDelay() {
  return fast_update_ ? 1 : 4;
}

int ChromeConfigurator::MinimumReCheckWait() {
  return fast_update_ ? 30 : (6 * kDelayOneHour);
}

GURL ChromeConfigurator::UpdateUrl() {
  return GURL("http://clients2.google.com/service/update2/crx");
}

const char* ChromeConfigurator::ExtraRequestParams() {
  return kExtraInfo;
}

size_t ChromeConfigurator::UrlSizeLimit() {
  return 1024ul;
}

net::URLRequestContextGetter* ChromeConfigurator::RequestContext() {
  return url_request_getter_;
}

bool ChromeConfigurator::InProcess() {
  return !out_of_process_;
}

void ChromeConfigurator::OnEvent(Events event, int val) {
  switch (event) {
    case kManifestCheck:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ManifestCheck", val, 100);
      break;
    case kComponentUpdated:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ComponentUpdated", val, 100);
      break;
    case kManifestError:
      UMA_HISTOGRAM_COUNTS_100("ComponentUpdater.ManifestError", val);
      break;
    case kNetworkError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.NetworkError", val, 100);
      break;
    case kUnpackError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.UnpackError", val, 100);
      break;
    case kInstallerError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.InstallError", val, 100);
      break;
    default:
      NOTREACHED();
      break;
  }
}

ComponentUpdateService::Configurator* MakeChromeComponentUpdaterConfigurator(
    const CommandLine* cmdline, net::URLRequestContextGetter* context_getter) {
  return new ChromeConfigurator(cmdline, context_getter);
}
<commit_msg>Adding more request parameters to component updater.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/component_updater/component_updater_service.h"

#include <algorithm>
#include <string>
#include <vector>

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/metrics/histogram.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "net/url_request/url_request_context_getter.h"

namespace {
// Default time constants.
const int kDelayOneMinute = 60;
const int kDelayOneHour = kDelayOneMinute * 60;

// Debug values you can pass to --component-updater-debug=value1,value2.
// Speed up component checking.
const char kDebugFastUpdate[] = "fast-update";
// Force out-of-process-xml parsing.
const char kDebugOutOfProcess[] = "out-of-process";
// Add "testrequest=1" parameter to the update check query.
const char kDebugRequestParam[] = "test-request";

bool HasDebugValue(const std::vector<std::string>& vec, const char* test) {
  if (vec.empty())
    return 0;
  return (std::find(vec.begin(), vec.end(), test) != vec.end());
}

// The request extra information is the OS and architecture, this helps
// the server select the right package to be delivered.
const char kExtraInfo[] =
#if defined(OS_MACOSX)
  #if defined(__amd64__)
    "os=mac&arch=x64&prod=chrome&prodversion=";
  #elif defined(__i386__)
     "os=mac&arch=x86&prod=chrome&prodversion=";
  #else
     #error "unknown mac architecture"
  #endif
#elif defined(OS_WIN)
  #if defined(_WIN64)
    "os=win&arch=x64&prod=chrome&prodversion=";
  #elif defined(_WIN32)
    "os=win&arch=x86&prod=chrome&prodversion=";
  #else
    #error "unknown windows architecture"
  #endif
#elif defined(OS_LINUX)
  #if defined(__amd64__)
    "os=linux&arch=x64&prod=chrome&prodversion=";
  #elif defined(__i386__)
    "os=linux&arch=x86&prod=chrome&prodversion=";
  #else
    "os=linux&arch=unknown&prod=chrome&prodversion=";
  #endif
#elif defined(OS_CHROMEOS)
  #if defined(__i386__)
    "os=cros&arch=x86&prod=chrome&prodversion=";
  #else
    // TODO(cpu): Fix this for ARM.
    "os=cros&arch=unknown&prod=chrome&prodversion=";
  #endif
#else
    #error "unknown os or architecture"
#endif

}  // namespace

class ChromeConfigurator : public ComponentUpdateService::Configurator {
 public:
  ChromeConfigurator(const CommandLine* cmdline,
                     net::URLRequestContextGetter* url_request_getter);

  virtual ~ChromeConfigurator() {}

  virtual int InitialDelay() OVERRIDE;
  virtual int NextCheckDelay() OVERRIDE;
  virtual int StepDelay() OVERRIDE;
  virtual int MinimumReCheckWait() OVERRIDE;
  virtual GURL UpdateUrl() OVERRIDE;
  virtual const char* ExtraRequestParams() OVERRIDE;
  virtual size_t UrlSizeLimit() OVERRIDE;
  virtual net::URLRequestContextGetter* RequestContext() OVERRIDE;
  virtual bool InProcess() OVERRIDE;
  virtual void OnEvent(Events event, int val) OVERRIDE;

 private:
  net::URLRequestContextGetter* url_request_getter_;
  std::string extra_info_;
  bool fast_update_;
  bool out_of_process_;
};

ChromeConfigurator::ChromeConfigurator(const CommandLine* cmdline,
    net::URLRequestContextGetter* url_request_getter)
      : url_request_getter_(url_request_getter),
        extra_info_(kExtraInfo) {
  // Parse comma-delimited debug flags.
  std::vector<std::string> debug_values;
  Tokenize(cmdline->GetSwitchValueASCII(switches::kComponentUpdaterDebug),
      ",", &debug_values);
  fast_update_ = HasDebugValue(debug_values, kDebugFastUpdate);
  out_of_process_ = HasDebugValue(debug_values, kDebugOutOfProcess);
  // Make the extra request params, they are necessary so omaha does
  // not deliver components that are going to be rejected at install time.
  extra_info_ += chrome::VersionInfo().Version();
  if (HasDebugValue(debug_values, kDebugRequestParam))
    extra_info_ += "&testrequest=1";
}

int ChromeConfigurator::InitialDelay() {
  return  fast_update_ ? 1 : (6 * kDelayOneMinute);
}

int ChromeConfigurator::NextCheckDelay() {
  return fast_update_ ? 3 : (4 * kDelayOneHour);
}

int ChromeConfigurator::StepDelay() {
  return fast_update_ ? 1 : 4;
}

int ChromeConfigurator::MinimumReCheckWait() {
  return fast_update_ ? 30 : (6 * kDelayOneHour);
}

GURL ChromeConfigurator::UpdateUrl() {
  return GURL("http://clients2.google.com/service/update2/crx");
}

const char* ChromeConfigurator::ExtraRequestParams() {
  return extra_info_.c_str();
}

size_t ChromeConfigurator::UrlSizeLimit() {
  return 1024ul;
}

net::URLRequestContextGetter* ChromeConfigurator::RequestContext() {
  return url_request_getter_;
}

bool ChromeConfigurator::InProcess() {
  return !out_of_process_;
}

void ChromeConfigurator::OnEvent(Events event, int val) {
  switch (event) {
    case kManifestCheck:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ManifestCheck", val, 100);
      break;
    case kComponentUpdated:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ComponentUpdated", val, 100);
      break;
    case kManifestError:
      UMA_HISTOGRAM_COUNTS_100("ComponentUpdater.ManifestError", val);
      break;
    case kNetworkError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.NetworkError", val, 100);
      break;
    case kUnpackError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.UnpackError", val, 100);
      break;
    case kInstallerError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.InstallError", val, 100);
      break;
    default:
      NOTREACHED();
      break;
  }
}

ComponentUpdateService::Configurator* MakeChromeComponentUpdaterConfigurator(
    const CommandLine* cmdline, net::URLRequestContextGetter* context_getter) {
  return new ChromeConfigurator(cmdline, context_getter);
}
<|endoftext|>