<commit_before>#ifndef DSE_H
#define DSE_H

#include <memory>
#include <Spark/Spmv.hpp>
#include <Spark/SimpleSpmv.hpp>
#include <Spark/Utils.hpp>
#include <Spark/Io.hpp>
#include <chrono>
#include <stdexcept>
#include <sstream>

namespace spark {
  namespace dse {

    // a benchmark to use for the DSE
    class Benchmark {
      std::vector<std::string> paths;
      public:
        std::string get_matrix_path(int id) const {
          if (id < paths.size())
            return paths[id];
          std::stringstream ss;
          ss << "Benchmark::Index out of range " << id;
          throw std::invalid_argument(ss.str());
        }

        void add_matrix_path(std::string path) {
          paths.push_back(path);
        }

        int get_benchmark_size() const {
          return paths.size();
        }
    };

    inline std::ostream& operator<<(std::ostream& s, Benchmark& b) {
      s << "Benchmark(" << std::endl;
      for (int i = 0; i < b.get_benchmark_size(); i++)
        s << "  " << b.get_matrix_path(i) << std::endl;
      s << ")" << std::endl;
      return s;
    }

    // the parameters and ranges to use for DSE
    class DseParameters {
      public:
        bool gflopsOnly;
        spark::utils::Range numPipesRange{1, 4, 1};
        spark::utils::Range inputWidthRange{1, 3, 1};
        spark::utils::Range cacheSizeRange{1024, 2048, 1024};
    };

    inline std::ostream& operator<<(std::ostream& s, DseParameters& d) {
      s << "DseParams(" << std::endl;
      s << "  numPipes = " << d.numPipesRange << std::endl;
      s << ")" << std::endl;
      return s;
    }

    class DseResult {
      public:
        std::shared_ptr<spark::spmv::SpmvArchitecture> bestArchitecture;
        std::vector<std::string> matrices;

        DseResult(std::string path, std::shared_ptr<spark::spmv::SpmvArchitecture> arch) {
          matrices.push_back(path);
          bestArchitecture = arch;
        }
        DseResult(std::shared_ptr<spark::spmv::SpmvArchitecture> arch) {
          bestArchitecture = arch;
        }
    };

    class SparkDse {
      public:
        SparkDse() {}
        void runDse();
        // returns the best architecture
        std::vector<DseResult> run (
            const Benchmark& benchmark,
            const DseParameters& dseParams);
    };
  }
}

#endif /* end of include guard: DSE_H */
<commit_msg>Print more dse params<commit_after>#ifndef DSE_H
#define DSE_H

#include <memory>
#include <Spark/Spmv.hpp>
#include <Spark/SimpleSpmv.hpp>
#include <Spark/Utils.hpp>
#include <Spark/Io.hpp>
#include <chrono>
#include <stdexcept>
#include <sstream>

namespace spark {
  namespace dse {

    // a benchmark to use for the DSE
    class Benchmark {
      std::vector<std::string> paths;
      public:
        std::string get_matrix_path(int id) const {
          if (id < paths.size())
            return paths[id];
          std::stringstream ss;
          ss << "Benchmark::Index out of range " << id;
          throw std::invalid_argument(ss.str());
        }

        void add_matrix_path(std::string path) {
          paths.push_back(path);
        }

        int get_benchmark_size() const {
          return paths.size();
        }
    };

    inline std::ostream& operator<<(std::ostream& s, Benchmark& b) {
      s << "Benchmark(" << std::endl;
      for (int i = 0; i < b.get_benchmark_size(); i++)
        s << "  " << b.get_matrix_path(i) << std::endl;
      s << ")" << std::endl;
      return s;
    }

    // the parameters and ranges to use for DSE
    class DseParameters {
      public:
        bool gflopsOnly;
        spark::utils::Range numPipesRange{1, 4, 1};
        spark::utils::Range inputWidthRange{1, 3, 1};
        spark::utils::Range cacheSizeRange{1024, 2048, 1024};
    };

    inline std::ostream& operator<<(std::ostream& s, DseParameters& d) {
      s << "DseParams(" << std::endl;
      s << "  numPipes   = " << d.numPipesRange << std::endl;
      s << "  inputWidth = " << d.inputWidthRange << std::endl;
      s << "  cacheSize  = " << d.cacheSizeRange << std::endl;
      s << ")" << std::endl;
      return s;
    }

    class DseResult {
      public:
        std::shared_ptr<spark::spmv::SpmvArchitecture> bestArchitecture;
        std::vector<std::string> matrices;

        DseResult(std::string path, std::shared_ptr<spark::spmv::SpmvArchitecture> arch) {
          matrices.push_back(path);
          bestArchitecture = arch;
        }
        DseResult(std::shared_ptr<spark::spmv::SpmvArchitecture> arch) {
          bestArchitecture = arch;
        }
    };

    class SparkDse {
      public:
        SparkDse() {}
        void runDse();
        // returns the best architecture
        std::vector<DseResult> run (
            const Benchmark& benchmark,
            const DseParameters& dseParams);
    };
  }
}

#endif /* end of include guard: DSE_H */
<|endoftext|>


<commit_before>#ifndef VSMC_CORE_MONITOR_HPP
#define VSMC_CORE_MONITOR_HPP

#include <vsmc/internal/common.hpp>

namespace vsmc {

/// \brief A simple GEMV functor for Monitor
///
/// \details
/// The actual GEMV used by Monitor<T> is based in GEMVTypeTrait<T>::type,
/// which default to this one. A replacement shall provide the same interface
/// documented below. The functor does not have to be \c const. However it
/// does need to have a default constructor
class GEMVSimple
{
    public :

    typedef VSMC_SIZE_TYPE size_type;

    /// \brief Simple GEMV operator
    ///
    /// \param N Number of columns of A and elements of X (number of particles)
    /// \param M Number of rows of A (Monitor's dimension)
    /// \param A [in] The matrix
    /// \param X [in] The vector
    /// \param res [out] Results
    ///
    /// \note \c A and \c X are assumed to be column major.
    void operator() (size_type N, size_type M,
            const double *A, const double *X, double *res) const
    {
        for (size_type m = 0; m != M; ++m) {
            double r = 0;
            const double *a = &A[m];
            const double *x = X;
            for (size_type n = 0; n != N; ++n, ++x, a += M)
                r += (*a) * (*x);
            res[m] = r;
        }
    }
}; // class GEMVSimple

} // namespace vsmc

VSMC_DEFINE_TYPE_DISPATCH_TRAIT(GEMVType, gemv_type, GEMVSimple);

namespace vsmc {

/// \brief Monitor for Monte Carlo integration
/// \ingroup Core
///
/// \tparam T Particle<T>::value_type
///
/// The primary use of Monitor is to record the importance sampling integration
/// along the way of iterations. So say one want to monitor two parameters,
/// \f$x = E[g(\theta)]\f$ and \f$y = E[h(\theta)]\f$, and this is done through
/// importance sampling integration. Then one need first compute two vectors,
/// \f$\{x_i\}\f$ and \f$\{y_i\}\f$ where \f$x_i = g(\theta_i)\f$ and
/// \f$y_i = h(\theta_i)\f$, and then compute the weighted sum. With Monitor
/// one can create a 2 dimension monitor with an evaluation functor. When the
/// evaluation functro is called, the last output arguments, say \c buffer will
/// be a row major matrix of dimension N by 2 where N is the number of
/// particles. That is, <tt>buffer[i * 2] = xi</tt> and <tt>buffer[i * 2 + 1] =
/// yi</tt>. After that, the Monitor will take care of the imporatance
/// sampling.
template <typename T>
class Monitor
{
    public :

    /// The type of the particle values
    typedef T value_type;

    /// The type of evaluation functor
    typedef cxx11::function<void (
            unsigned, unsigned, const Particle<T> &, double *)> eval_type;

    /// The type of the GEMV functor
    typedef typename GEMVTypeTrait<T>::type gemv_type;

    /// \brief Construct a Monitor with an evaluation functor
    ///
    /// \param dim The dimension of the monitor, i.e., the number of variables
    /// \param eval The functor used to evaluate the results
    explicit Monitor (unsigned dim = 1, const eval_type &eval = VSMC_NULLPTR) :
        dim_(dim), eval_(eval) {}

    Monitor (const Monitor<T> &other) :
        dim_(other.dim_), eval_(other.eval_),
        index_(other.index_), record_(other.record_) {}

    Monitor<T> &operator= (const Monitor<T> &other)
    {
        if (&other != this) {
            dim_    = other.dim_;
            eval_   = other.eval_;
            index_  = other.index_;
            record_ = other.record_;
        }

        return *this;
    }

    /// Dimension of the monitor
    unsigned dim () const
    {
        return dim_;
    }

    /// The size of records
    unsigned iter_size () const
    {
        return static_cast<unsigned>(index_.size());
    }

    /// \brief Test if the monitor is valid
    ///
    /// \note This operator will be \c explicit if the C++11 feature is enabled
#if VSMC_HAS_CXX11_EXPLICIT_CONVERSIONS
    explicit
#endif
        operator bool () const
    {
        return bool(eval_);
    }

    unsigned index (unsigned iter) const
    {
        VSMC_RUNTIME_ASSERT((iter >= 0 && iter < iter_size()),
                ("CALL **Monitor::index** WITH AN INVALID "
                 "ITERATION NUMBER"));

        return index_[iter];
    }

    double record (unsigned id, unsigned iter) const
    {
        VSMC_RUNTIME_ASSERT((id >= 0 && id < dim()),
                ("CALL **Monitor::record** WITH AN INVALID "
                 "ID NUMBER"));
        VSMC_RUNTIME_ASSERT((iter >= 0 && iter < iter_size()),
                ("CALL **Monitor::record** WITH AN INVALID "
                 "ITERATION NUMBER"));

        return record_[iter * dim_ + id];
    }

    /// \brief Read only access to iteration index
    ///
    /// \param first The beginning of the destination range
    ///
    /// \return Output iterator to the element in the destination range, one
    /// past the last element copied
    template <typename OutputIter>
    OutputIter read_index (OutputIter first) const
    {
        return std::copy(index_.begin(), index_.end(), first);
    }

    /// \brief Read only access to record of a specific variable
    ///
    /// \param id The ID of the variable, 0 to dim() - 1
    /// \param first The beginning of the destination range
    ///
    /// \return Output iterator to the element in the destination range, one
    /// past the last element copied
    template <typename OutputIter>
    OutputIter read_record (unsigned id, OutputIter first) const
    {
        const double *riter = &record_[id];
        for (unsigned i = 0; i != iter_size(); ++i, ++first, riter += dim_)
            *first = *riter;

        return first;
    }

    /// \brief Read only access to record of all variables
    ///
    /// \param first A pointer to an array of the beginning of the destination
    /// range. For example, say \c OutpuIiter is \c double \c *, then
    /// first[c][r] will be the r'th record of the c'th variable. In general,
    /// first[c] will be the begin of the reading of the record of the c'th
    /// variable.
    template <typename OutputIter>
    void read_record_matrix (OutputIter *first) const
    {
        for (unsigned d = 0; d != dim_; ++d)
            read_record(d, first[d]);
    }

    /// \brief Read only access to record of all variables
    ///
    /// \param order Either vsmc::ColumnMajor or vsmc::RowMajor. With any other
    /// value, this method does nothing and simply return the original \c
    /// first. In debug mode an assert also will be issued.
    /// \param first The beginning of the destination range
    ///
    /// \return Output iterator to the element in the destination range, one
    /// past the last element copied
    ///
    /// \note The record is considered as a iter_size() by dim() matrix
    template <typename OutputIter>
    OutputIter read_record_matrix (MatrixOrder order, OutputIter first) const
    {
        VSMC_RUNTIME_ASSERT((order == ColumnMajor || order == RowMajor),
                "CALL **Monitor::read_record_matrix** with and INVALID "
                "MatrixOrder");

        if (order == ColumnMajor)
            for (unsigned d = 0; d != dim_; ++d)
                first = read_record(d, first);

        if (order == RowMajor)
            first = std::copy(record_.begin(), record_.end(), first);

        return first;
    }

    /// Set a new evaluation functor
    void set_eval (const eval_type &new_eval)
    {
        eval_ = new_eval;
    }

    /// \brief Evaluate
    ///
    /// \param iter The iteration number
    /// \param particle The particle set to be operated on by eval()
    ///
    /// \pre A matrix of size Dim by N is passed to the evaluation functor used
    /// to construct this monitor or set by set_eval() as its last output
    /// parameter, where N is the number of particles. The array of matrix
    /// elements is of column major.
    void eval (unsigned iter, const Particle<T> &particle)
    {
        VSMC_RUNTIME_ASSERT((bool(eval_)),
                ("CALL **Monitor::eval** WITH AN INVALID "
                 "EVALUATION FUNCTOR"));

        buffer_.resize(dim_ * particle.size());
        result_.resize(dim_);
        weight_.resize(particle.size());
        eval_(iter, dim_, particle, &buffer_[0]);
        particle.read_weight(weight_.begin());
        gemv_(particle.size(), dim_, &buffer_[0], &weight_[0], &result_[0]);

        index_.push_back(iter);
        for (unsigned d = 0; d != dim_; ++d)
            record_.push_back(result_[d]);
    }

    /// \brief Clear all recorded data
    ///
    /// \note The evaluation functor is not reset
    void clear ()
    {
        index_.clear();
        record_.clear();
    }

    private :

    std::vector<double> buffer_;
    std::vector<double> result_;
    std::vector<double> weight_;
    unsigned dim_;
    eval_type eval_;
    std::vector<unsigned> index_;
    std::vector<double> record_;

    gemv_type gemv_;
}; // class Monitor

} // namespace vsmc

#endif // VSMC_CORE_MONITOR_HPP
<commit_msg>documentation improvement<commit_after>#ifndef VSMC_CORE_MONITOR_HPP
#define VSMC_CORE_MONITOR_HPP

#include <vsmc/internal/common.hpp>

namespace vsmc {

/// \brief A simple GEMV functor for Monitor
///
/// \details
/// The actual GEMV used by Monitor<T> is based in GEMVTypeTrait<T>::type,
/// which default to this one. A replacement shall provide the same interface
/// documented below. The functor does not have to be \c const. However it
/// does need to have a default constructor
class GEMVSimple
{
    public :

    typedef VSMC_SIZE_TYPE size_type;

    /// \brief Simple GEMV operator
    ///
    /// \param N Number of columns of A and elements of X (number of particles)
    /// \param M Number of rows of A (Monitor's dimension)
    /// \param A [in] The matrix
    /// \param X [in] The vector
    /// \param res [out] Results
    ///
    /// \note `A` is assumed to be column major in the sense that `A[0]` is
    /// A_{0,0}, `A[1]` is A_{1,0}, etc. That is, the if you iterate over
    /// pointer `A` linearly with increments `1`, then it will first travese
    /// column one, then column two, and so on. If you want to think `A` as an
    /// `N` by `M` instead of `M` by `N` matrix, then `A` is assumed to be row
    /// major.
    void operator() (size_type N, size_type M,
            const double *A, const double *X, double *res) const
    {
        for (size_type m = 0; m != M; ++m) {
            double r = 0;
            const double *a = &A[m];
            const double *x = X;
            for (size_type n = 0; n != N; ++n, ++x, a += M)
                r += (*a) * (*x);
            res[m] = r;
        }
    }
}; // class GEMVSimple

} // namespace vsmc

VSMC_DEFINE_TYPE_DISPATCH_TRAIT(GEMVType, gemv_type, GEMVSimple);

namespace vsmc {

/// \brief Monitor for Monte Carlo integration
/// \ingroup Core
///
/// \tparam T Particle<T>::value_type
///
/// The primary use of Monitor is to record the importance sampling integration
/// along the way of iterations. So say one want to monitor two parameters,
/// \f$x = E[g(\theta)]\f$ and \f$y = E[h(\theta)]\f$, and this is done through
/// importance sampling integration. Then one need first compute two vectors,
/// \f$\{x_i\}\f$ and \f$\{y_i\}\f$ where \f$x_i = g(\theta_i)\f$ and \f$y_i =
/// h(\theta_i)\f$, and then compute the weighted sum. With Monitor one can
/// create a 2 dimension monitor with an evaluation functor. When the
/// evaluation functor is called, the last output arguments, say \c buffer,
/// shall be a row major matrix of dimension N by 2 where N is the number of
/// particles. That is, <tt>buffer[i * 2] = xi</tt> and <tt>buffer[i * 2 + 1] =
/// yi</tt>. After that, the Monitor will take care of the imporatance
/// sampling.
///
/// A Monitor is sually not used as a standalone object, but added to a
/// Sampler. It is possible to have the monitor only exist for parts of the
/// iterations of a Sampler. Therefore, the iteration in a monitor is not the
/// same as the iteration number of a Sampler. Which itertions of the Sampler
/// are recored with a particular Monitor can be queried by `index()`. For each
/// `i`, `index(i)` is the iteration number of the Sampler being monitored.
template <typename T>
class Monitor
{
    public :

    /// The type of the particle values
    typedef T value_type;

    /// The type of evaluation functor
    typedef cxx11::function<void (
            unsigned, unsigned, const Particle<T> &, double *)> eval_type;

    /// The type of the GEMV functor
    typedef typename GEMVTypeTrait<T>::type gemv_type;

    /// \brief Construct a Monitor with an evaluation functor
    ///
    /// \param dim The dimension of the monitor, i.e., the number of variables
    /// \param eval The functor used to evaluate the results
    explicit Monitor (unsigned dim = 1, const eval_type &eval = VSMC_NULLPTR) :
        dim_(dim), eval_(eval) {}

    Monitor (const Monitor<T> &other) :
        dim_(other.dim_), eval_(other.eval_),
        index_(other.index_), record_(other.record_) {}

    Monitor<T> &operator= (const Monitor<T> &other)
    {
        if (&other != this) {
            dim_    = other.dim_;
            eval_   = other.eval_;
            index_  = other.index_;
            record_ = other.record_;
        }

        return *this;
    }

    /// Dimension of the monitor
    unsigned dim () const
    {
        return dim_;
    }

    /// The size of records
    unsigned iter_size () const
    {
        return static_cast<unsigned>(index_.size());
    }

    /// \brief Test if the monitor is valid
    ///
    /// \note This operator will be \c explicit if the C++11 feature is enabled
#if VSMC_HAS_CXX11_EXPLICIT_CONVERSIONS
    explicit
#endif
        operator bool () const
    {
        return bool(eval_);
    }

    unsigned index (unsigned iter) const
    {
        VSMC_RUNTIME_ASSERT((iter >= 0 && iter < iter_size()),
                ("CALL **Monitor::index** WITH AN INVALID "
                 "ITERATION NUMBER"));

        return index_[iter];
    }

    double record (unsigned id, unsigned iter) const
    {
        VSMC_RUNTIME_ASSERT((id >= 0 && id < dim()),
                ("CALL **Monitor::record** WITH AN INVALID "
                 "ID NUMBER"));
        VSMC_RUNTIME_ASSERT((iter >= 0 && iter < iter_size()),
                ("CALL **Monitor::record** WITH AN INVALID "
                 "ITERATION NUMBER"));

        return record_[iter * dim_ + id];
    }

    /// \brief Read only access to iteration index
    ///
    /// \param first The beginning of the destination range
    ///
    /// \return Output iterator to the element in the destination range, one
    /// past the last element copied
    template <typename OutputIter>
    OutputIter read_index (OutputIter first) const
    {
        return std::copy(index_.begin(), index_.end(), first);
    }

    /// \brief Read only access to record of a specific variable
    ///
    /// \param id The ID of the variable, 0 to dim() - 1
    /// \param first The beginning of the destination range
    ///
    /// \return Output iterator to the element in the destination range, one
    /// past the last element copied
    template <typename OutputIter>
    OutputIter read_record (unsigned id, OutputIter first) const
    {
        const double *riter = &record_[id];
        for (unsigned i = 0; i != iter_size(); ++i, ++first, riter += dim_)
            *first = *riter;

        return first;
    }

    /// \brief Read only access to record of all variables
    ///
    /// \param first A pointer to an array of the beginning of the destination
    /// range. For example, say \c OutpuIiter is \c double \c *, then
    /// first[c][r] will be the r'th record of the c'th variable. In general,
    /// first[c] will be the begin of the reading of the record of the c'th
    /// variable.
    template <typename OutputIter>
    void read_record_matrix (OutputIter *first) const
    {
        for (unsigned d = 0; d != dim_; ++d)
            read_record(d, first[d]);
    }

    /// \brief Read only access to record of all variables
    ///
    /// \param order Either vsmc::ColumnMajor or vsmc::RowMajor. With any other
    /// value, this method does nothing and simply return the original \c
    /// first. In debug mode an assert will also be issued. This parameter
    /// affects how values are stored in the output array. In either case, the
    /// records are considered as an `iter_size()` by `dim()` matrix. That is
    /// if `order = vsmc::RowMajor`, and `first` is a random access iterator
    /// (e.g., a pointer), then `first[0] = record(0, 0)`,
    /// `first[1] = record(1, 0)`, ... ,
    /// `first[dim() - 1] = record(dim() - 1, 0)`,
    /// `first[dim()] = record[0, 1]`, ...
    /// \param first The beginning of the destination range
    ///
    /// \return Output iterator to the element in the destination range, one
    /// past the last element copied
    ///
    /// \note The record is considered as a iter_size() by dim() matrix
    template <typename OutputIter>
    OutputIter read_record_matrix (MatrixOrder order, OutputIter first) const
    {
        VSMC_RUNTIME_ASSERT((order == ColumnMajor || order == RowMajor),
                "CALL **Monitor::read_record_matrix** with and INVALID "
                "MatrixOrder");

        if (order == ColumnMajor)
            for (unsigned d = 0; d != dim_; ++d)
                first = read_record(d, first);

        if (order == RowMajor)
            first = std::copy(record_.begin(), record_.end(), first);

        return first;
    }

    /// Set a new evaluation functor
    void set_eval (const eval_type &new_eval)
    {
        eval_ = new_eval;
    }

    /// \brief Evaluate
    ///
    /// \param iter The iteration number
    /// \param particle The particle set to be operated on by eval()
    ///
    /// \pre The user has to provide the evaluation functor, which will be
    /// called in this member function. The signature of the evaluation functor
    /// is as defined by `eval_type`. The first argument is the iteration
    /// number (`iter`), the second is the dimension of this monitor (`dim()`),
    /// the third is the particle set. The last is the output array, described
    /// below.
    ///
    /// \pre A matrix of size `dim()` by `N` is passed to the evaluation
    /// functor used to construct this monitor or set by set_eval() as its last
    /// output parameter, where N is the number of particles. The array of
    /// matrix elements is of column major. Another interpretation is that the
    /// passed array is a row major `N` by `dim()` matrix, each row stores the
    /// results of a particle. Either way, results for the same particle are
    /// stored in a contiguous memory segment.
    void eval (unsigned iter, const Particle<T> &particle)
    {
        VSMC_RUNTIME_ASSERT((bool(eval_)),
                ("CALL **Monitor::eval** WITH AN INVALID "
                 "EVALUATION FUNCTOR"));

        buffer_.resize(dim_ * particle.size());
        result_.resize(dim_);
        weight_.resize(particle.size());
        eval_(iter, dim_, particle, &buffer_[0]);
        particle.read_weight(weight_.begin());
        gemv_(particle.size(), dim_, &buffer_[0], &weight_[0], &result_[0]);

        index_.push_back(iter);
        for (unsigned d = 0; d != dim_; ++d)
            record_.push_back(result_[d]);
    }

    /// \brief Clear all recorded data
    ///
    /// \note The evaluation functor is not reset
    void clear ()
    {
        index_.clear();
        record_.clear();
    }

    private :

    std::vector<double> buffer_;
    std::vector<double> result_;
    std::vector<double> weight_;
    unsigned dim_;
    eval_type eval_;
    std::vector<unsigned> index_;
    std::vector<double> record_;

    gemv_type gemv_;
}; // class Monitor

} // namespace vsmc

#endif // VSMC_CORE_MONITOR_HPP
<|endoftext|>


<commit_before>/*
 * LCALifLayer.cpp
 *
 *  Created on: Jun 26, 2012
 *      Author: slundquist & dpaiton
 */

#include "LCALIFLayer.hpp"

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

#ifdef __cplusplus
extern "C" {
#endif
void LCALIF_update_state(
   const int numNeurons,
   const float time,
   const float dt,

   const int nx,
   const int ny,
   const int nf,
   const int nb,

   const float tauLCA,
   const float tauTHR,
   const float targetRate,

   pvdata_t * integratedSpikeCount,

   CL_MEM_CONST LIF_params * params,
   CL_MEM_GLOBAL uint4 * rnd,
   CL_MEM_GLOBAL float * V,
   CL_MEM_GLOBAL float * Vth,
   CL_MEM_GLOBAL float * G_E,
   CL_MEM_GLOBAL float * G_I,
   CL_MEM_GLOBAL float * G_IB,
   CL_MEM_GLOBAL float * GSynHead,
   CL_MEM_GLOBAL float * activity,

   const float sum_gap,
   CL_MEM_GLOBAL float * G_Gap
);
#ifdef __cplusplus
}
#endif

namespace PV {
LCALIFLayer::LCALIFLayer() {
   initialize_base();
  // initialize(arguments) should *not* be called by the protected constructor.
}

LCALIFLayer::LCALIFLayer(const char * name, HyPerCol * hc) {
   initialize_base();
   initialize(name, hc, MAX_CHANNELS + 1, "LCALIF_update_state");
}

int LCALIFLayer::initialize_base(){
   tauLCA = 2000;
   tauTHR = 20000;
   targetRate = 1;
   dynVthRest = VthRest;
   integratedSpikeCount = NULL;
   return PV_SUCCESS;
}

int LCALIFLayer::initialize(const char * name, HyPerCol * hc, int num_channels, const char * kernel_name){
   LIFGap::initialize(name, hc, TypeLCA, num_channels, kernel_name);
   PVParams * params = hc->parameters();

   tauLCA     = params->value(name, "tauLCA", tauLCA);
   tauTHR     = params->value(name, "tauTHR", tauTHR);
   targetRate = params->value(name, "targetRate", targetRate);

   return PV_SUCCESS;
}

LCALIFLayer::~LCALIFLayer()
{
   free(integratedSpikeCount);
}

int LCALIFLayer::allocateBuffers() {
   const size_t numNeurons = getNumNeurons();
   //Allocate data to keep track of trace
   integratedSpikeCount = (pvdata_t *) calloc(numNeurons, sizeof(pvdata_t));
   assert(integratedSpikeCount != NULL);
   return LIFGap::allocateBuffers();
}

int LCALIFLayer::updateState(float time, float dt)
{
   //Call update_state kernel
   LCALIF_update_state(getNumNeurons(), time, dt, clayer->loc.nx, clayer->loc.ny, clayer->loc.nf,
         clayer->loc.nb, dynVthRest, tauLCA, tauTHR, targetRate, integratedSpikeCount, &lParams,
         rand_state, clayer->V, Vth, G_E, G_I, G_IB, GSyn[0], clayer->activity->data, sumGap, G_Gap);
 //  std::cout << clayer->activity->data[50] << " " << integratedSpikeCount[50] << "\n";
   return PV_SUCCESS;
}

//////////////////////////////////////////////////////
//
// implementation of LIF kernels
//

#ifdef __cplusplus
extern "C" {
#endif

#ifndef PV_USE_OPENCL
#  include "../kernels/LCALIF_update_state.cl"
#else
#  undef PV_USE_OPENCL
#  undef USE_CLRANDOM
#  include "../kernels/LCALIF_update_state.cl"
#  define PV_USE_OPENCL
#endif

#ifdef __cplusplus
}
#endif

}
<commit_msg>moved some lines of code around, changed default values, added comments<commit_after>/*
 * LCALifLayer.cpp
 *
 *  Created on: Jun 26, 2012
 *      Author: slundquist & dpaiton
 */

#include "LCALIFLayer.hpp"

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

//////////////////////////////////////////////////////
// implementation of LIF kernels
//////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif
#ifndef PV_USE_OPENCL
#  include "../kernels/LCALIF_update_state.cl"
#else
#  undef PV_USE_OPENCL
#  undef USE_CLRANDOM
#  include "../kernels/LCALIF_update_state.cl"
#  define PV_USE_OPENCL
#endif
#ifdef __cplusplus
}
#endif

//Kernel update state implementation receives all necessary variables
//for required computation. File is included above.
#ifdef __cplusplus
extern "C" {
#endif
void LCALIF_update_state(
   const int numNeurons,
   const float time,
   const float dt,

   const int nx,
   const int ny,
   const int nf,
   const int nb,

   const float tauLCA,
   const float tauTHR,
   const float targetRate,

   pvdata_t * integratedSpikeCount,

   CL_MEM_CONST LIF_params * params,
   CL_MEM_GLOBAL uint4 * rnd,
   CL_MEM_GLOBAL float * V,
   CL_MEM_GLOBAL float * Vth,
   CL_MEM_GLOBAL float * G_E,
   CL_MEM_GLOBAL float * G_I,
   CL_MEM_GLOBAL float * G_IB,
   CL_MEM_GLOBAL float * GSynHead,
   CL_MEM_GLOBAL float * activity,

   const float sum_gap,
   CL_MEM_GLOBAL float * G_Gap
);
#ifdef __cplusplus
}
#endif

namespace PV {
LCALIFLayer::LCALIFLayer() {
   initialize_base();
  // initialize(arguments) should *not* be called by the protected constructor.
}

LCALIFLayer::LCALIFLayer(const char * name, HyPerCol * hc) {
   initialize_base();
   initialize(name, hc, MAX_CHANNELS + 1, "LCALIF_update_state");
}

int LCALIFLayer::initialize_base(){
   tauLCA = 200;
   tauTHR = 1000;
   targetRate = 50;
   dynVthRest = VthRest;
   integratedSpikeCount = NULL;
   return PV_SUCCESS;
}

int LCALIFLayer::initialize(const char * name, HyPerCol * hc, int num_channels, const char * kernel_name){
   LIFGap::initialize(name, hc, TypeLCA, num_channels, kernel_name);
   PVParams * params = hc->parameters();

   tauLCA     = params->value(name, "tauLCA", tauLCA);
   tauTHR     = params->value(name, "tauTHR", tauTHR);
   targetRate = params->value(name, "targetRate", targetRate);

   return PV_SUCCESS;
}

LCALIFLayer::~LCALIFLayer()
{
   free(integratedSpikeCount);
}

int LCALIFLayer::allocateBuffers() {
   const size_t numNeurons = getNumNeurons();
   //Allocate data to keep track of trace
   integratedSpikeCount = (pvdata_t *) calloc(numNeurons, sizeof(pvdata_t));
   assert(integratedSpikeCount != NULL);
   return LIFGap::allocateBuffers();
}

int LCALIFLayer::updateState(float time, float dt)
{
   //Call update_state kernel
   LCALIF_update_state(getNumNeurons(), time, dt, clayer->loc.nx, clayer->loc.ny, clayer->loc.nf,
         clayer->loc.nb, dynVthRest, tauLCA, tauTHR, targetRate, integratedSpikeCount, &lParams,
         rand_state, clayer->V, Vth, G_E, G_I, G_IB, GSyn[0], clayer->activity->data, sumGap, G_Gap);
 //  std::cout << clayer->activity->data[50] << " " << integratedSpikeCount[50] << "\n";
   return PV_SUCCESS;
}
}
<|endoftext|>


<commit_before>#ifndef VSMC_CXX11_CHRONO_HPP
#define VSMC_CXX11_CHRONO_HPP

#include <vsmc/internal/config.hpp>

#if VSMC_HAS_CXX11LIB_CHRONO
#include <chrono>
namespace vsmc { namespace cxx11 { namespace chrono {
using std::chrono::system_clock;
using std::chrono::duration;
} } }
#else
#include <boost/chrono.hpp>
namespace vsmc { namespace cxx11 { namespace chrono {
using boost::chrono::system_clock;
using boost::chrono::duration;
} } }
#endif // VSMC_HAS_CXX11LIB_CHRONO

#endif // VSMC_CXX11_CHRONO_HPP
<commit_msg>update chrono to include all C++11 names<commit_after>#ifndef VSMC_CXX11_CHRONO_HPP
#define VSMC_CXX11_CHRONO_HPP

#include <vsmc/internal/config.hpp>

#if VSMC_HAS_CXX11LIB_CHRONO
#include <chrono>
namespace vsmc { namespace cxx11 { namespace chrono {
using std::chrono::duration;
using std::chrono::time_point;
using std::chrono::treat_as_floating_point;
using std::chrono::duration_values;
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
using std::chrono::microseconds;
using std::chrono::milliseconds;
using std::chrono::seconds;
using std::chrono::minutes;
using std::chrono::hours;
using std::chrono::time_point_cast;
using std::chrono::system_clock;
using std::chrono::steady_clock;
using std::chrono::high_resolution_clock;
} } }
#else
#include <boost/chrono.hpp>
namespace vsmc { namespace cxx11 { namespace chrono {
using boost::chrono::duration;
using boost::chrono::time_point;
using boost::chrono::treat_as_floating_point;
using boost::chrono::duration_values;
using boost::chrono::duration_cast;
using boost::chrono::nanoseconds;
using boost::chrono::microseconds;
using boost::chrono::milliseconds;
using boost::chrono::seconds;
using boost::chrono::minutes;
using boost::chrono::hours;
using boost::chrono::time_point_cast;
using boost::chrono::system_clock;
using boost::chrono::steady_clock;
using boost::chrono::high_resolution_clock;
} } }
#endif // VSMC_HAS_CXX11LIB_CHRONO

#endif // VSMC_CXX11_CHRONO_HPP
<|endoftext|>


<commit_before>#ifndef MANIFOLDS_FUNCTIONS_FUNCTION_MATRIX_HH
#define MANIFOLDS_FUNCTIONS_FUNCTION_MATRIX_HH

#include "function.hh"
#include "matrix.hh"

namespace manifolds {

  template <class ... Functions>
  struct RowHolder
  {
    RowHolder(Functions...fs):functions(fs...){}
    std::tuple<Functions...> functions;
    auto GetFunctions() const
    {
      return functions;
    }
  };

  template <class ... Functions>
  auto Row(Functions...fs)
  {
    return RowHolder<Functions...>(fs...);
  }

  template <class rows, class cols,
	    class ... Functions>
  struct FunctionMatrixImpl :
    Function<max<Functions::input_dim...>::value,
	     max<Functions::output_dim...>::value>
  {
    std::tuple<Functions...> functions;

    template <class ... Rows>
    FunctionMatrixImpl(Rows...rs):
      functions(std::tuple_cat(rs.GetFunctions()...)){}

    FunctionMatrixImpl(std::tuple<Functions...> f):
      functions(f){}

    template <class ... Args, std::size_t ... indices>
    auto eval(std::integer_sequence<std::size_t,indices...>,
	      Args...args) const
    {
      return GetMatrix<rows::value,cols::value>
	(std::get<indices>(functions)(args...)...);
    }

    template <class ... Args>
    auto operator()(Args...args) const
    {
      return eval(std::index_sequence_for<Functions...>(), args...);
    }

    auto GetFunctions() const
    {
      return functions;
    }

    auto GetOutputs() const
    {
      return functions;
    }
  };

  DEF_FF_TEMPLATE(FunctionMatrix)

  template <std::size_t rows, std::size_t cols,
	    class ... Functions>
  auto GetFunctionMatrix(std::tuple<Functions...> functions)
  {
    return FunctionMatrix<
      int_<rows>,int_<cols>,Functions...>(functions);
  }

  template <class ... Rows>
  auto GetFunctionMatrix(Rows...rows)
  {
    return GetFunctionMatrix<
      sizeof...(Rows),
      std::tuple_size<
	decltype(std::declval<
		 typename first<Rows...>::type>().
		 GetFunctions())>::value>
      (std::tuple_cat(rows.GetFunctions()...));
  }

  template <class rows, class cols, class ... Functions>
  std::ostream & operator<<
  (std::ostream & s,
   FunctionMatrix<rows, cols, Functions...> f)
  {
    s << "FunctionMatrix<" << rows::value << ", "
      << cols::value << ">";
    StreamVariadic("", f, s);
    return s;
  }

  template <class ... Functions>
  auto GetRow(Functions ... functions)
  {
    return Row<Functions...>(functions...);
  }
}

#endif
<commit_msg>Added simplifications<commit_after>#ifndef MANIFOLDS_FUNCTIONS_FUNCTION_MATRIX_HH
#define MANIFOLDS_FUNCTIONS_FUNCTION_MATRIX_HH

#include "function.hh"
#include "matrix.hh"

namespace manifolds {

  template <class ... Functions>
  struct RowHolder
  {
    RowHolder(Functions...fs):functions(fs...){}
    std::tuple<Functions...> functions;
    auto GetFunctions() const
    {
      return functions;
    }
  };

  template <class ... Functions>
  auto Row(Functions...fs)
  {
    return RowHolder<Functions...>(fs...);
  }

  template <class rows, class cols,
	    class ... Functions>
  struct FunctionMatrixImpl :
    Function<max<Functions::input_dim...>::value,
	     max<Functions::output_dim...>::value>
  {
    static const int num_rows = rows::value;
    static const int num_cols = cols::value;
    std::tuple<Functions...> functions;

    template <class ... Rows>
    FunctionMatrixImpl(Rows...rs):
      functions(std::tuple_cat(rs.GetFunctions()...)){}

    FunctionMatrixImpl(std::tuple<Functions...> f):
      functions(f){}

    template <class ... Args, std::size_t ... indices>
    auto eval(std::integer_sequence<std::size_t,indices...>,
	      Args...args) const
    {
      return GetMatrix<rows::value,cols::value>
	(std::get<indices>(functions)(args...)...);
    }

    template <class ... Args>
    auto operator()(Args...args) const
    {
      return eval(std::index_sequence_for<Functions...>(), args...);
    }

    auto GetFunctions() const
    {
      return functions;
    }

    auto GetOutputs() const
    {
      return functions;
    }
  };

  DEF_FF_TEMPLATE(FunctionMatrix)

  template <std::size_t rows, std::size_t cols,
	    class ... Functions>
  auto GetFunctionMatrix(std::tuple<Functions...> functions)
  {
    return FunctionMatrix<
      int_<rows>,int_<cols>,Functions...>(functions);
  }

  template <class ... Rows>
  auto GetFunctionMatrix(Rows...rows)
  {
    return GetFunctionMatrix<
      sizeof...(Rows),
      std::tuple_size<
	decltype(std::declval<
		 typename first<Rows...>::type>().
		 GetFunctions())>::value>
      (std::tuple_cat(rows.GetFunctions()...));
  }

  template <class rows, class cols, class ... Functions>
  std::ostream & operator<<
  (std::ostream & s,
   FunctionMatrix<rows, cols, Functions...> f)
  {
    s << "FunctionMatrix<" << rows::value << ", "
      << cols::value << ">";
    StreamVariadic("", f, s);
    return s;
  }

  template <class ... Functions>
  auto GetRow(Functions ... functions)
  {
    return Row<Functions...>(functions...);
  }

}

#include "variables.hh"
#include "trig.hh"
#include "polynomial.hh"

namespace manifolds {

  template <class r1, class c1, class r2, class c2,
	    class ... F1s, class ... F2s>
  struct Simplification<
    Composition<FunctionMatrix<r1,c1,F1s...>,
		FunctionMatrix<r2,c2,F2s...>>>
  {
    typedef FunctionMatrix<r1,c1,F1s...> FMOut;
    typedef FunctionMatrix<r2,c2,F2s...> FMIn;
    static_assert(r2::value == 1 || c2::value == 1,
		  "Inner function of composition must "
		  "be a row or column vector.");
    static const int dims =
      r2::value == 1 ? c2::value : r2::value;
    static_assert(dims == FMOut::input_dim,
		  "Dimensionality of inner vector "
		  "must match input dimensionality of "
		  "outer vector.");

    template <class TupleO, class TupleI,
	      std::size_t ... iouts,
	      std::size_t ... iins>
    static auto CombineHelper(TupleO t1, TupleI t2,
			      std::integer_sequence<
			      std::size_t, iouts...>,
			      std::integer_sequence<
			      std::size_t, iins...>)
    {
      return std::make_tuple(std::get<iouts>(t1)
			     (std::get<iins>(t2)...)...);
    }

    typedef Composition<FunctionMatrix<r1,c1,F1s...>,
			FunctionMatrix<r2,c2,F2s...>> in_type;

    static auto Combine(in_type c)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying composition of function matrices\n";
#endif
      auto t = c.GetFunctions();
      return GetFunctionMatrix<r1::value, c1::value>
	(CombineHelper(std::get<0>(t).GetFunctions(),
		       std::get<1>(t).GetFunctions(),
		       std::index_sequence_for<F1s...>(),
		       std::index_sequence_for<F2s...>()));
    }

    typedef decltype(Combine(std::declval<in_type>())) type;
  };

  template <int i, bool a, class ... FMFuncs>
  struct Simplification<
    Composition<Variable<i,a>,
		FunctionMatrix<FMFuncs...>>>
  {
    typedef typename nth<i+2,FMFuncs...>::type type;

    static type Combine(Composition<Variable<i,a>,
			FunctionMatrix<FMFuncs...>> c)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying composition of "
	"variable and function matrix\n";
#endif
      return std::get<i>(std::get<1>(c.GetFunctions()).
			 GetFunctions());
    }
  };

  template <class r, class c, class ... Fs>
  struct Simplification<
    FunctionMatrix<r,c, Fs...>, 1>
  {
    typedef FunctionMatrix<r,c, Fs...> in_type;
    static auto Combine(in_type m)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying individual elements "
	"of function matrix\n";
#endif
      auto t = m.GetFunctions();
      return GetFunctionMatrix<r::value, c::value>
	(SimplifyIndividuals(t,
			     std::make_index_sequence<
			     std::tuple_size<
			     decltype(t)>::value>()));
    }

    typedef decltype(Combine(std::declval<in_type>())) type;
  };

  template <class F, class P, class r, class c>
  struct Simplification<
    Multiplication<
    F, Composition<Pow,
		   FunctionMatrix<r,c,F,P>>>, 0,
    typename std::enable_if<is_stateless<F>::value>::type>
  {
    typedef Multiplication<
      F, Composition<Pow,
		     FunctionMatrix<r,c,F,P>>> in_type;
    static auto Combine(in_type f)
    {
      auto p = std::get<1>(std::get<1>
			   (std::get<1>(f.GetFunctions()).
			    GetFunctions()).GetFunctions());
      return Pow()(F(), Add(p, 1_c));
    }

    typedef decltype(Combine(std::declval<in_type>())) type;
  };
}

#endif
<|endoftext|>


<commit_before>#include "svgf/svgf.h"

#include "kernel/compaction.h"

#include <cuda_runtime.h>
#include <device_launch_parameters.h>

#include "cuda/helper_math.h"
#include "cuda/cudautil.h"
#include "cuda/cudamemory.h"

#include "aten4idaten.h"

namespace idaten
{
	void SVGFPathTracing::update(
		GLuint gltex,
		int width, int height,
		const aten::CameraParameter& camera,
		const std::vector<aten::GeomParameter>& shapes,
		const std::vector<aten::MaterialParameter>& mtrls,
		const std::vector<aten::LightParameter>& lights,
		const std::vector<std::vector<aten::GPUBvhNode>>& nodes,
		const std::vector<aten::PrimitiveParamter>& prims,
		const std::vector<aten::vertex>& vtxs,
		const std::vector<aten::mat4>& mtxs,
		const std::vector<TextureResource>& texs,
		const EnvmapResource& envmapRsc)
	{
		idaten::Renderer::update(
			gltex,
			width, height,
			camera,
			shapes,
			mtrls,
			lights,
			nodes,
			prims,
			vtxs,
			mtxs,
			texs, envmapRsc);

		m_sobolMatrices.init(AT_COUNTOF(sobol::Matrices::matrices));
		m_sobolMatrices.writeByNum(sobol::Matrices::matrices, m_sobolMatrices.maxNum());

		auto& r = aten::getRandom();
		m_random.init(width * height);
		m_random.writeByNum(&r[0], width * height);

		for (int i = 0; i < 2; i++) {
			m_aovNormalDepth[i].init(width * height);
			m_aovTexclrTemporalWeight[i].init(width * height);
			m_aovColorVariance[i].init(width * height);
			m_aovMomentMeshid[i].init(width * height);
		}

		for (int i = 0; i < AT_COUNTOF(m_atrousClrVar); i++) {
			m_atrousClrVar[i].init(width * height);
		}

		m_tmpBuf.init(width * height);
	}

	void SVGFPathTracing::update(
		const std::vector<aten::GeomParameter>& geoms,
		const std::vector<std::vector<aten::GPUBvhNode>>& nodes,
		const std::vector<aten::mat4>& mtxs)
	{
		m_shapeparam.reset();
		m_shapeparam.writeByNum(&geoms[0], geoms.size());

		// Only for top layer...
		m_nodeparam[0].init(
			(aten::vec4*)&nodes[0][0],
			sizeof(aten::GPUBvhNode) / sizeof(float4),
			nodes[0].size());

		if (!mtxs.empty()) {
			m_mtxparams.reset();
			m_mtxparams.writeByNum(&mtxs[0], mtxs.size());
		}
	}

	void SVGFPathTracing::setGBuffer(
		GLuint gltexGbuffer,
		GLuint gltexMotionDepthbuffer)
	{
		m_gbuffer.init(gltexGbuffer, idaten::CudaGLRscRegisterType::ReadOnly);
		m_motionDepthBuffer.init(gltexMotionDepthbuffer, idaten::CudaGLRscRegisterType::ReadOnly);
	}

	static bool doneSetStackSize = false;

	void SVGFPathTracing::render(
		int width, int height,
		int maxSamples,
		int maxBounce)
	{
#ifdef __AT_DEBUG__
		if (!doneSetStackSize) {
			size_t val = 0;
			cudaThreadGetLimit(&val, cudaLimitStackSize);
			cudaThreadSetLimit(cudaLimitStackSize, val * 4);
			doneSetStackSize = true;
		}
#endif

		int bounce = 0;

		m_isects.init(width * height);
		m_rays.init(width * height);

		m_shadowRays.init(width * height * ShadowRayNum);

		onInit(width, height);

		CudaGLResourceMapper rscmap(&m_glimg);
		auto outputSurf = m_glimg.bind();

		auto vtxTexPos = m_vtxparamsPos.bind();
		auto vtxTexNml = m_vtxparamsNml.bind();

		{
			std::vector<cudaTextureObject_t> tmp;
			for (int i = 0; i < m_nodeparam.size(); i++) {
				auto nodeTex = m_nodeparam[i].bind();
				tmp.push_back(nodeTex);
			}
			m_nodetex.writeByNum(&tmp[0], tmp.size());
		}

		if (!m_texRsc.empty())
		{
			std::vector<cudaTextureObject_t> tmp;
			for (int i = 0; i < m_texRsc.size(); i++) {
				auto cudaTex = m_texRsc[i].bind();
				tmp.push_back(cudaTex);
			}
			m_tex.writeByNum(&tmp[0], tmp.size());
		}

		if (width > 1280 || height > 720) {
			int w = (width + 1) / 2;
			int h = (height + 1) / 2;

			int compactionW = std::max(w, width - w);
			int compactionH = std::max(h, height - h);

			m_hitbools.init(compactionW * compactionH);
			m_hitidx.init(compactionW * compactionH);

			Compaction::init(
				compactionW * compactionH,
				1024);

			for (int nx = 0; nx < 2; nx++) {
				for (int ny = 0; ny < 2; ny++) {
					int x = nx * w;
					int y = ny * h;

					onClear();

					onRender(
						TileDomain(x, y, w, h),
						width, height, maxSamples, maxBounce,
						outputSurf,
						vtxTexPos,
						vtxTexNml);
				}
			}

#if 1
			for (int nx = 0; nx < 2; nx++) {
				for (int ny = 0; ny < 2; ny++) {
					int x = nx * w;
					int y = ny * h;

					onDenoise(
						TileDomain(x, y, w, h),
						width, height, maxSamples, maxBounce,
						outputSurf);
				}
			}

			if (m_mode == Mode::SVGF) {
				static const int ITER = 5;

				for (int i = 0; i < ITER; i++) {
					for (int nx = 0; nx < 2; nx++) {
						for (int ny = 0; ny < 2; ny++) {
							int x = nx * w;
							int y = ny * h;

							m_tileDomain = TileDomain(x, y, w, h);

							onAtrousFilterIter(
								i, ITER,
								outputSurf,
								width, height);
						}
					}
				}

				onCopyFromTmpBufferToAov(width, height);
			}
#endif
		}
		else {
			m_hitbools.init(width * height);
			m_hitidx.init(width * height);

			Compaction::init(
				width * height,
				1024);

			onClear();

			TileDomain tileDomain(0, 0, width, height);

			onRender(
				tileDomain,
				width, height, maxSamples, maxBounce,
				outputSurf,
				vtxTexPos,
				vtxTexNml);

			onDenoise(
				tileDomain,
				width, height, maxSamples, maxBounce,
				outputSurf);

			if (m_mode == Mode::SVGF)
			{
				onAtrousFilter(outputSurf, width, height);
				onCopyFromTmpBufferToAov(width, height);
			}
		}

		{
			m_mtxPrevW2V = m_mtxW2V;

			pick(
				m_pickedInfo.ix, m_pickedInfo.iy,
				width, height,
				vtxTexPos);

			//checkCudaErrors(cudaDeviceSynchronize());

			// Toggle aov buffer pos.
			m_curAOVPos = 1 - m_curAOVPos;

			m_frame++;

			{
				m_vtxparamsPos.unbind();
				m_vtxparamsNml.unbind();

				for (int i = 0; i < m_nodeparam.size(); i++) {
					m_nodeparam[i].unbind();
				}
				m_nodetex.reset();

				for (int i = 0; i < m_texRsc.size(); i++) {
					m_texRsc[i].unbind();
				}
				m_tex.reset();
			}
		}
	}

	void SVGFPathTracing::onRender(
		const TileDomain& tileDomain,
		int width, int height,
		int maxSamples,
		int maxBounce,
		cudaSurfaceObject_t outputSurf,
		cudaTextureObject_t vtxTexPos,
		cudaTextureObject_t vtxTexNml)
	{
		m_tileDomain = tileDomain;

		static const int rrBounce = 3;

		// Set bounce count to 1 forcibly, aov render mode.
		maxBounce = (m_mode == Mode::AOVar ? 1 : maxBounce);

		auto time = AT_NAME::timer::getSystemTime();

		for (int i = 0; i < maxSamples; i++) {
			int seed = time.milliSeconds;
			//int seed = 0;

			onGenPath(
				width, height,
				i, maxSamples,
				seed,
				vtxTexPos,
				vtxTexNml);

			int bounce = 0;

			while (bounce < maxBounce) {
				onHitTest(
					width, height,
					bounce,
					vtxTexPos);

				onShadeMiss(width, height, bounce);

				int hitcount = 0;
				idaten::Compaction::compact(
					m_hitidx,
					m_hitbools);

				//AT_PRINTF("%d\n", hitcount);

				onShade(
					outputSurf,
					width, height,
					bounce, rrBounce,
					vtxTexPos, vtxTexNml);

				bounce++;
			}
		}

		if (m_mode == Mode::PT) {
			onGather(outputSurf, width, height, maxSamples);
		}
		else if (m_mode == Mode::AOVar) {
			onDisplayAOV(outputSurf, width, height, vtxTexPos);
		}
		else {
			if (isFirstFrame()) {
				onGather(outputSurf, width, height, maxSamples);
			}
			else {
				onCopyBufferForTile(width, height);
			}
		}
	}

	void SVGFPathTracing::onDenoise(
		const TileDomain& tileDomain,
		int width, int height,
		int maxSamples,
		int maxBounce,
		cudaSurfaceObject_t outputSurf)
	{
		m_tileDomain = tileDomain;

		if (m_mode == Mode::SVGF
			|| m_mode == Mode::TF
			|| m_mode == Mode::VAR)
		{
			if (isFirstFrame()) {
				// Nothing is done...
			}
			else {
				onTemporalReprojection(
					outputSurf,
					width, height);
			}
		}

		if (m_mode == Mode::SVGF
			|| m_mode == Mode::VAR)
		{
			onVarianceEstimation(outputSurf, width, height);
		}
	}
}
<commit_msg>Avoid unnecessary memcpy.<commit_after>#include "svgf/svgf.h"

#include "kernel/compaction.h"

#include <cuda_runtime.h>
#include <device_launch_parameters.h>

#include "cuda/helper_math.h"
#include "cuda/cudautil.h"
#include "cuda/cudamemory.h"

#include "aten4idaten.h"

//#pragma optimize( "", off)

namespace idaten
{
	void SVGFPathTracing::update(
		GLuint gltex,
		int width, int height,
		const aten::CameraParameter& camera,
		const std::vector<aten::GeomParameter>& shapes,
		const std::vector<aten::MaterialParameter>& mtrls,
		const std::vector<aten::LightParameter>& lights,
		const std::vector<std::vector<aten::GPUBvhNode>>& nodes,
		const std::vector<aten::PrimitiveParamter>& prims,
		const std::vector<aten::vertex>& vtxs,
		const std::vector<aten::mat4>& mtxs,
		const std::vector<TextureResource>& texs,
		const EnvmapResource& envmapRsc)
	{
		idaten::Renderer::update(
			gltex,
			width, height,
			camera,
			shapes,
			mtrls,
			lights,
			nodes,
			prims,
			vtxs,
			mtxs,
			texs, envmapRsc);

		m_sobolMatrices.init(AT_COUNTOF(sobol::Matrices::matrices));
		m_sobolMatrices.writeByNum(sobol::Matrices::matrices, m_sobolMatrices.maxNum());

		auto& r = aten::getRandom();
		m_random.init(width * height);
		m_random.writeByNum(&r[0], width * height);

		for (int i = 0; i < 2; i++) {
			m_aovNormalDepth[i].init(width * height);
			m_aovTexclrTemporalWeight[i].init(width * height);
			m_aovColorVariance[i].init(width * height);
			m_aovMomentMeshid[i].init(width * height);
		}

		for (int i = 0; i < AT_COUNTOF(m_atrousClrVar); i++) {
			m_atrousClrVar[i].init(width * height);
		}

		m_tmpBuf.init(width * height);
	}

	void SVGFPathTracing::update(
		const std::vector<aten::GeomParameter>& geoms,
		const std::vector<std::vector<aten::GPUBvhNode>>& nodes,
		const std::vector<aten::mat4>& mtxs)
	{
		m_shapeparam.reset();
		m_shapeparam.writeByNum(&geoms[0], geoms.size());

		// Only for top layer...
		m_nodeparam[0].init(
			(aten::vec4*)&nodes[0][0],
			sizeof(aten::GPUBvhNode) / sizeof(float4),
			nodes[0].size());

		if (!mtxs.empty()) {
			m_mtxparams.reset();
			m_mtxparams.writeByNum(&mtxs[0], mtxs.size());
		}
	}

	void SVGFPathTracing::setGBuffer(
		GLuint gltexGbuffer,
		GLuint gltexMotionDepthbuffer)
	{
		m_gbuffer.init(gltexGbuffer, idaten::CudaGLRscRegisterType::ReadOnly);
		m_motionDepthBuffer.init(gltexMotionDepthbuffer, idaten::CudaGLRscRegisterType::ReadOnly);
	}

	static bool doneSetStackSize = false;

	void SVGFPathTracing::render(
		int width, int height,
		int maxSamples,
		int maxBounce)
	{
#ifdef __AT_DEBUG__
		if (!doneSetStackSize) {
			size_t val = 0;
			cudaThreadGetLimit(&val, cudaLimitStackSize);
			cudaThreadSetLimit(cudaLimitStackSize, val * 4);
			doneSetStackSize = true;
		}
#endif

		int bounce = 0;

		m_isects.init(width * height);
		m_rays.init(width * height);

		m_shadowRays.init(width * height * ShadowRayNum);

		onInit(width, height);

		CudaGLResourceMapper rscmap(&m_glimg);
		auto outputSurf = m_glimg.bind();

		auto vtxTexPos = m_vtxparamsPos.bind();
		auto vtxTexNml = m_vtxparamsNml.bind();

		// TODO
		// TexturẽoChɂ擾cudaTextureObject_t͕ωȂ̂,lxێĂ΂.
		// _ł͍ŏɐݒ肳ꂽ̂ωȂOł邪AւȂǂ̕ύXꍇ͂̌ł͂Ȃ̂ŁȂΉKv.

		static bool isListedTextureObject = false;

		if (!isListedTextureObject)
		{
			{
				std::vector<cudaTextureObject_t> tmp;
				for (int i = 0; i < m_nodeparam.size(); i++) {
					auto nodeTex = m_nodeparam[i].bind();
					tmp.push_back(nodeTex);
				}
				m_nodetex.writeByNum(&tmp[0], tmp.size());
			}

			if (!m_texRsc.empty())
			{
				std::vector<cudaTextureObject_t> tmp;
				for (int i = 0; i < m_texRsc.size(); i++) {
					auto cudaTex = m_texRsc[i].bind();
					tmp.push_back(cudaTex);
				}
				m_tex.writeByNum(&tmp[0], tmp.size());
			}

			isListedTextureObject = true;
		}
		else {
			for (int i = 0; i < m_nodeparam.size(); i++) {
				auto nodeTex = m_nodeparam[i].bind();
			}
			for (int i = 0; i < m_texRsc.size(); i++) {
				auto cudaTex = m_texRsc[i].bind();
			}
		}

		if (width > 1280 || height > 720) {
			int w = (width + 1) / 2;
			int h = (height + 1) / 2;

			int compactionW = std::max(w, width - w);
			int compactionH = std::max(h, height - h);

			m_hitbools.init(compactionW * compactionH);
			m_hitidx.init(compactionW * compactionH);

			Compaction::init(
				compactionW * compactionH,
				1024);

			for (int nx = 0; nx < 2; nx++) {
				for (int ny = 0; ny < 2; ny++) {
					int x = nx * w;
					int y = ny * h;

					onClear();

					onRender(
						TileDomain(x, y, w, h),
						width, height, maxSamples, maxBounce,
						outputSurf,
						vtxTexPos,
						vtxTexNml);
				}
			}

#if 1
			for (int nx = 0; nx < 2; nx++) {
				for (int ny = 0; ny < 2; ny++) {
					int x = nx * w;
					int y = ny * h;

					onDenoise(
						TileDomain(x, y, w, h),
						width, height, maxSamples, maxBounce,
						outputSurf);
				}
			}

			if (m_mode == Mode::SVGF) {
				static const int ITER = 5;

				for (int i = 0; i < ITER; i++) {
					for (int nx = 0; nx < 2; nx++) {
						for (int ny = 0; ny < 2; ny++) {
							int x = nx * w;
							int y = ny * h;

							m_tileDomain = TileDomain(x, y, w, h);

							onAtrousFilterIter(
								i, ITER,
								outputSurf,
								width, height);
						}
					}
				}

				onCopyFromTmpBufferToAov(width, height);
			}
#endif
		}
		else {
			m_hitbools.init(width * height);
			m_hitidx.init(width * height);

			Compaction::init(
				width * height,
				1024);

			onClear();

			TileDomain tileDomain(0, 0, width, height);

			onRender(
				tileDomain,
				width, height, maxSamples, maxBounce,
				outputSurf,
				vtxTexPos,
				vtxTexNml);

			onDenoise(
				tileDomain,
				width, height, maxSamples, maxBounce,
				outputSurf);

			if (m_mode == Mode::SVGF)
			{
				onAtrousFilter(outputSurf, width, height);
				onCopyFromTmpBufferToAov(width, height);
			}
		}

		{
			m_mtxPrevW2V = m_mtxW2V;

			pick(
				m_pickedInfo.ix, m_pickedInfo.iy,
				width, height,
				vtxTexPos);

			//checkCudaErrors(cudaDeviceSynchronize());

			// Toggle aov buffer pos.
			m_curAOVPos = 1 - m_curAOVPos;

			m_frame++;

			{
				m_vtxparamsPos.unbind();
				m_vtxparamsNml.unbind();

				for (int i = 0; i < m_nodeparam.size(); i++) {
					m_nodeparam[i].unbind();
				}
				m_nodetex.reset();

				for (int i = 0; i < m_texRsc.size(); i++) {
					m_texRsc[i].unbind();
				}
				m_tex.reset();
			}
		}
	}

	void SVGFPathTracing::onRender(
		const TileDomain& tileDomain,
		int width, int height,
		int maxSamples,
		int maxBounce,
		cudaSurfaceObject_t outputSurf,
		cudaTextureObject_t vtxTexPos,
		cudaTextureObject_t vtxTexNml)
	{
		m_tileDomain = tileDomain;

		static const int rrBounce = 3;

		// Set bounce count to 1 forcibly, aov render mode.
		maxBounce = (m_mode == Mode::AOVar ? 1 : maxBounce);

		auto time = AT_NAME::timer::getSystemTime();

		for (int i = 0; i < maxSamples; i++) {
			int seed = time.milliSeconds;
			//int seed = 0;

			onGenPath(
				width, height,
				i, maxSamples,
				seed,
				vtxTexPos,
				vtxTexNml);

			int bounce = 0;

			while (bounce < maxBounce) {
				onHitTest(
					width, height,
					bounce,
					vtxTexPos);

				onShadeMiss(width, height, bounce);

				int hitcount = 0;
				idaten::Compaction::compact(
					m_hitidx,
					m_hitbools);

				//AT_PRINTF("%d\n", hitcount);

				onShade(
					outputSurf,
					width, height,
					bounce, rrBounce,
					vtxTexPos, vtxTexNml);

				bounce++;
			}
		}

		if (m_mode == Mode::PT) {
			onGather(outputSurf, width, height, maxSamples);
		}
		else if (m_mode == Mode::AOVar) {
			onDisplayAOV(outputSurf, width, height, vtxTexPos);
		}
		else {
			if (isFirstFrame()) {
				onGather(outputSurf, width, height, maxSamples);
			}
			else {
				onCopyBufferForTile(width, height);
			}
		}
	}

	void SVGFPathTracing::onDenoise(
		const TileDomain& tileDomain,
		int width, int height,
		int maxSamples,
		int maxBounce,
		cudaSurfaceObject_t outputSurf)
	{
		m_tileDomain = tileDomain;

		if (m_mode == Mode::SVGF
			|| m_mode == Mode::TF
			|| m_mode == Mode::VAR)
		{
			if (isFirstFrame()) {
				// Nothing is done...
			}
			else {
				onTemporalReprojection(
					outputSurf,
					width, height);
			}
		}

		if (m_mode == Mode::SVGF
			|| m_mode == Mode::VAR)
		{
			onVarianceEstimation(outputSurf, width, height);
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>linguistic: Use appropriate OUString functions on string constants<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlistimp.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-25 12:22:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _LINGUISTIC_DLISTIMP_HXX_
#define _LINGUISTIC_DLISTIMP_HXX_

#ifndef _COM_SUN_STAR_LINGUISTIC2_XSEARCHABLEDICTIONARYLIST_HPP_
#include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#include <uno/lbnames.h>            // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase1.hxx> // helper for implementations
#include <cppuhelper/implbase3.hxx> // helper for implementations
#include <cppuhelper/interfacecontainer.h>

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif

#include "misc.hxx"
#include "lngopt.hxx"

class DicEvtListenerHelper;

///////////////////////////////////////////////////////////////////////////

class ActDic
{
public:
    const ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XDictionary >    xDic;

    ActDic() {}
    ActDic(const ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XDictionary > &rDic) : xDic(rDic) {}
};
SV_DECL_OBJARR( ActDicArray, ActDic, 16, 16 )

class DicList :
    public cppu::WeakImplHelper3
    <
        ::com::sun::star::linguistic2::XSearchableDictionaryList,
        ::com::sun::star::lang::XComponent,
        ::com::sun::star::lang::XServiceInfo
    >
{
    class MyAppExitListener : public linguistic::AppExitListener
    {
        DicList & rMyDicList;

    public:
        MyAppExitListener( DicList &rDicList ) : rMyDicList( rDicList ) {}
        virtual void    AtExit();
    };

    LinguOptions    aOpt;

    ::cppu::OInterfaceContainerHelper       aEvtListeners;
    ActDicArray*                            pDicList;

    ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::
                XDictionaryEventListener >  xDicEvtLstnrHelper;
    DicEvtListenerHelper                    *pDicEvtLstnrHelper;

    ::com::sun::star::uno::Reference< ::com::sun::star::frame::
                XTerminateListener >        xExitListener;
    MyAppExitListener                       *pExitListener;

    BOOL    bDisposing;

    // disallow copy-constructor and assignment-operator for now
    DicList( const DicList & );
    DicList & operator = (const DicList &);

    void            _CreateDicList();
    ActDicArray&    GetDicList()
                        {
                            if( !pDicList )
                                _CreateDicList();
                            return *pDicList;
                        }

    void            launchEvent(INT16 nEvent, com::sun::star::uno::Sequence<
                            ::com::sun::star::linguistic2::XDictionary > xDic);
    void            searchForDictionaries( ActDicArray &rDicList,
                                            const String &rDicDir );
    INT32           getDicPos(const com::sun::star::uno::Reference<
                            ::com::sun::star::linguistic2::XDictionary > &xDic);

public:
    DicList();
    virtual ~DicList();

    // XDictionaryList
    virtual sal_Int16 SAL_CALL
        getCount()
            throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence<
            ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XDictionary > > SAL_CALL
        getDictionaries()
            throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::linguistic2::XDictionary > SAL_CALL
        getDictionaryByName( const ::rtl::OUString& aDictionaryName )
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
        addDictionary( const ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XDictionary >& xDictionary )
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
        removeDictionary( const ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XDictionary >& xDictionary )
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
        addDictionaryListEventListener( const ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XDictionaryListEventListener >& xListener,
                sal_Bool bReceiveVerbose )
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
        removeDictionaryListEventListener(
                const ::com::sun::star::uno::Reference<
                    ::com::sun::star::linguistic2::XDictionaryListEventListener >& xListener )
                throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Int16 SAL_CALL
        beginCollectEvents()
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Int16 SAL_CALL
        endCollectEvents()
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Int16 SAL_CALL
        flushEvents()
            throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::linguistic2::XDictionary > SAL_CALL
        createDictionary( const ::rtl::OUString& aName,
                const ::com::sun::star::lang::Locale& aLocale,
                ::com::sun::star::linguistic2::DictionaryType eDicType,
                const ::rtl::OUString& aURL )
            throw(::com::sun::star::uno::RuntimeException);

    // XSearchableDictionaryList
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::linguistic2::XDictionaryEntry > SAL_CALL
        queryDictionaryEntry( const ::rtl::OUString& aWord,
                const ::com::sun::star::lang::Locale& aLocale,
                sal_Bool bSearchPosDics, sal_Bool bSpellEntry )
            throw(::com::sun::star::uno::RuntimeException);

    // XComponent
    virtual void SAL_CALL
        dispose()
            throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        addEventListener( const ::com::sun::star::uno::Reference<
                ::com::sun::star::lang::XEventListener >& xListener )
            throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        removeEventListener( const ::com::sun::star::uno::Reference<
                ::com::sun::star::lang::XEventListener >& aListener )
            throw(::com::sun::star::uno::RuntimeException);

    ////////////////////////////////////////////////////////////
    // Service specific part
    //

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL
        getImplementationName()
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
        supportsService( const ::rtl::OUString& ServiceName )
            throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
        getSupportedServiceNames()
            throw(::com::sun::star::uno::RuntimeException);

    static inline ::rtl::OUString
        getImplementationName_Static() throw();
    static com::sun::star::uno::Sequence< ::rtl::OUString >
        getSupportedServiceNames_Static() throw();

    // non UNO-specific
    void    SaveDics();
};

inline ::rtl::OUString DicList::getImplementationName_Static() throw()
{
    return A2OU( "com.sun.star.lingu2.DicList" );
}

///////////////////////////////////////////////////////////////////////////

#endif

<commit_msg>INTEGRATION: CWS tl41_DEV300 (1.5.10); FILE MERGED 2008/02/14 15:31:05 tl 1.5.10.1: #i80286# make dictionaries read-only if not in writeable path<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlistimp.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2008-03-25 16:26:35 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _LINGUISTIC_DLISTIMP_HXX_
#define _LINGUISTIC_DLISTIMP_HXX_

#ifndef _COM_SUN_STAR_LINGUISTIC2_XSEARCHABLEDICTIONARYLIST_HPP_
#include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#include <uno/lbnames.h>            // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase1.hxx> // helper for implementations
#include <cppuhelper/implbase3.hxx> // helper for implementations
#include <cppuhelper/interfacecontainer.h>

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif

#include "misc.hxx"
#include "lngopt.hxx"

class DicEvtListenerHelper;

///////////////////////////////////////////////////////////////////////////

class ActDic
{
public:
    const ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XDictionary >    xDic;

    ActDic() {}
    ActDic(const ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XDictionary > &rDic) : xDic(rDic) {}
};
SV_DECL_OBJARR( ActDicArray, ActDic, 16, 16 )

class DicList :
    public cppu::WeakImplHelper3
    <
        ::com::sun::star::linguistic2::XSearchableDictionaryList,
        ::com::sun::star::lang::XComponent,
        ::com::sun::star::lang::XServiceInfo
    >
{
    class MyAppExitListener : public linguistic::AppExitListener
    {
        DicList & rMyDicList;

    public:
        MyAppExitListener( DicList &rDicList ) : rMyDicList( rDicList ) {}
        virtual void    AtExit();
    };

    LinguOptions    aOpt;

    ::cppu::OInterfaceContainerHelper       aEvtListeners;
    ActDicArray*                            pDicList;

    ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::
                XDictionaryEventListener >  xDicEvtLstnrHelper;
    DicEvtListenerHelper                    *pDicEvtLstnrHelper;

    ::com::sun::star::uno::Reference< ::com::sun::star::frame::
                XTerminateListener >        xExitListener;
    MyAppExitListener                       *pExitListener;

    BOOL    bDisposing;

    // disallow copy-constructor and assignment-operator for now
    DicList( const DicList & );
    DicList & operator = (const DicList &);

    void            _CreateDicList();
    ActDicArray&    GetDicList()
                        {
                            if( !pDicList )
                                _CreateDicList();
                            return *pDicList;
                        }

    void            launchEvent(INT16 nEvent, com::sun::star::uno::Sequence<
                            ::com::sun::star::linguistic2::XDictionary > xDic);
    void            searchForDictionaries( ActDicArray &rDicList,
                                            const String &rDicDir, BOOL bIsWritePath );
    INT32           getDicPos(const com::sun::star::uno::Reference<
                            ::com::sun::star::linguistic2::XDictionary > &xDic);

public:
    DicList();
    virtual ~DicList();

    // XDictionaryList
    virtual sal_Int16 SAL_CALL
        getCount()
            throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence<
            ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XDictionary > > SAL_CALL
        getDictionaries()
            throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::linguistic2::XDictionary > SAL_CALL
        getDictionaryByName( const ::rtl::OUString& aDictionaryName )
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
        addDictionary( const ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XDictionary >& xDictionary )
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
        removeDictionary( const ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XDictionary >& xDictionary )
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
        addDictionaryListEventListener( const ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XDictionaryListEventListener >& xListener,
                sal_Bool bReceiveVerbose )
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
        removeDictionaryListEventListener(
                const ::com::sun::star::uno::Reference<
                    ::com::sun::star::linguistic2::XDictionaryListEventListener >& xListener )
                throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Int16 SAL_CALL
        beginCollectEvents()
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Int16 SAL_CALL
        endCollectEvents()
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Int16 SAL_CALL
        flushEvents()
            throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::linguistic2::XDictionary > SAL_CALL
        createDictionary( const ::rtl::OUString& aName,
                const ::com::sun::star::lang::Locale& aLocale,
                ::com::sun::star::linguistic2::DictionaryType eDicType,
                const ::rtl::OUString& aURL )
            throw(::com::sun::star::uno::RuntimeException);

    // XSearchableDictionaryList
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::linguistic2::XDictionaryEntry > SAL_CALL
        queryDictionaryEntry( const ::rtl::OUString& aWord,
                const ::com::sun::star::lang::Locale& aLocale,
                sal_Bool bSearchPosDics, sal_Bool bSpellEntry )
            throw(::com::sun::star::uno::RuntimeException);

    // XComponent
    virtual void SAL_CALL
        dispose()
            throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        addEventListener( const ::com::sun::star::uno::Reference<
                ::com::sun::star::lang::XEventListener >& xListener )
            throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        removeEventListener( const ::com::sun::star::uno::Reference<
                ::com::sun::star::lang::XEventListener >& aListener )
            throw(::com::sun::star::uno::RuntimeException);

    ////////////////////////////////////////////////////////////
    // Service specific part
    //

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL
        getImplementationName()
            throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL
        supportsService( const ::rtl::OUString& ServiceName )
            throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
        getSupportedServiceNames()
            throw(::com::sun::star::uno::RuntimeException);

    static inline ::rtl::OUString
        getImplementationName_Static() throw();
    static com::sun::star::uno::Sequence< ::rtl::OUString >
        getSupportedServiceNames_Static() throw();

    // non UNO-specific
    void    SaveDics();
};

inline ::rtl::OUString DicList::getImplementationName_Static() throw()
{
    return A2OU( "com.sun.star.lingu2.DicList" );
}

///////////////////////////////////////////////////////////////////////////

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: urp_dispatch.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: jbu $ $Date: 2000-11-28 14:42:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifdef SOLARIS
#include <alloca.h>
#elif MACOSX
#include <sys/types.h>
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif

#include <osl/mutex.hxx>
#include <osl/diagnose.h>

#include <rtl/alloc.h>
#include <rtl/ustrbuf.hxx>

#include <vos/timer.hxx>

#include <uno/mapping.hxx>
#include <uno/threadpool.h>

#include <bridges/remote/remote.h>
#include <bridges/remote/stub.hxx>
#include <bridges/remote/proxy.hxx>
#include <bridges/remote/remote.hxx>

#include "urp_bridgeimpl.hxx"
#include "urp_marshal.hxx"
#include "urp_dispatch.hxx"
#include "urp_job.hxx"
#include "urp_writer.hxx"
#include "urp_log.hxx"

using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;

namespace bridges_urp
{

void SAL_CALL urp_sendCloseConnection( uno_Environment *pEnvRemote )
{
    remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
    urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );

    {
        MutexGuard guard( pImpl->m_marshalingMutex );
        sal_uInt8 nBitfield = 0;

        // send immeadiatly
        if( ! pImpl->m_blockMarshaler.empty() )
        {
            pImpl->m_pWriter->touch( sal_True );
        }

        pImpl->m_pWriter->sendEmptyMessage();
        // no more data via this connection !
        pImpl->m_pWriter->abort();
    }
}
void SAL_CALL urp_sendRequest(
    uno_Environment *pEnvRemote,
    typelib_TypeDescription * pMemberType,
    rtl_uString *pOid,
    typelib_InterfaceTypeDescription *pInterfaceType,
    void *pReturn,
    void *ppArgs[],
    uno_Any **ppException )
{
    remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
    urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );

    ClientJob job(pEnvRemote, pImpl, pOid, pMemberType, pInterfaceType, pReturn, ppArgs, ppException);

    if( job.pack() && ! job.isOneway() )
    {
        job.wait();
    }
}

}

<commit_msg>#80673# in the ForceSynchronous case, the releases are now sent by the writer thread<commit_after>/*************************************************************************
 *
 *  $RCSfile: urp_dispatch.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: jbu $ $Date: 2001-01-31 16:41:23 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifdef SOLARIS
#include <alloca.h>
#elif MACOSX
#include <sys/types.h>
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif

#include <osl/mutex.hxx>
#include <osl/diagnose.h>

#include <rtl/alloc.h>
#include <rtl/ustrbuf.hxx>

#include <vos/timer.hxx>

#include <uno/mapping.hxx>
#include <uno/threadpool.h>

#include <bridges/remote/remote.h>
#include <bridges/remote/stub.hxx>
#include <bridges/remote/proxy.hxx>
#include <bridges/remote/remote.hxx>

#include "urp_bridgeimpl.hxx"
#include "urp_marshal.hxx"
#include "urp_dispatch.hxx"
#include "urp_job.hxx"
#include "urp_writer.hxx"
#include "urp_log.hxx"

using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;

namespace bridges_urp
{

void SAL_CALL urp_sendCloseConnection( uno_Environment *pEnvRemote )
{
    remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
    urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );

    {
        MutexGuard guard( pImpl->m_marshalingMutex );
        sal_uInt8 nBitfield = 0;

        // send immeadiatly
        if( ! pImpl->m_blockMarshaler.empty() )
        {
            pImpl->m_pWriter->touch( sal_True );
        }

        pImpl->m_pWriter->sendEmptyMessage();
        // no more data via this connection !
        pImpl->m_pWriter->abort();
    }
}
void SAL_CALL urp_sendRequest(
    uno_Environment *pEnvRemote,
    typelib_TypeDescription * pMemberType,
    rtl_uString *pOid,
    typelib_InterfaceTypeDescription *pInterfaceType,
    void *pReturn,
    void *ppArgs[],
    uno_Any **ppException )
{
    remote_Context *pContext = (remote_Context *) pEnvRemote->pContext;
    urp_BridgeImpl *pImpl = (urp_BridgeImpl*) ( pContext->m_pBridgeImpl );

    ClientJob job(pEnvRemote, pImpl, pOid, pMemberType, pInterfaceType, pReturn, ppArgs, ppException);

    if( pImpl->m_properties.bForceSynchronous &&
        REMOTE_RELEASE_METHOD_INDEX ==
        ((typelib_InterfaceMemberTypeDescription*)pMemberType)->nPosition &&
        pImpl->m_pWriter->getIdentifier() != ::vos::OThread::getCurrentIdentifier() )
    {
        // all release calls in the FORCE SYNCHRONOUS case are delegated to the writer thread to avoid
        // multiple synchron calls with the same thread id.
        pImpl->m_pWriter->insertReleaseRemoteCall( pOid, pInterfaceType->aBase.pWeakRef );
    }
    else
    {
        if( job.pack() && ! job.isOneway() )
        {
            job.wait();
        }
    }
}

}

<|endoftext|>


<commit_before>/*
 *  SimpleRenderEngine (https://github.com/mortennobel/SimpleRenderEngine)
 *
 *  Created by Morten Nobel-Jørgensen ( http://www.nobel-joergensen.com/ )
 *  License: MIT
 */

#pragma once

#include <glm/glm.hpp>

namespace sre {

    // The color class represent a sRGBA color, (this means that RGB is in gamma space, whereas alpha is in linear space)
    class Color {
    public:
        Color() = default;
        Color(float r, float g, float b, float a = 1.0f);
        explicit Color(glm::vec4 linearColor);

        float& operator[] (int index);

        glm::vec4 toLinear();             // Return color values in linear space
        void setFromLinear(glm::vec4 linear); // Set sRGBA values from linear space

        float r = 0;
        float g = 0;
        float b = 0;
        float a = 1;
    };
}<commit_msg>Simplify documentation of Color<commit_after>/*
 *  SimpleRenderEngine (https://github.com/mortennobel/SimpleRenderEngine)
 *
 *  Created by Morten Nobel-Jørgensen ( http://www.nobel-joergensen.com/ )
 *  License: MIT
 */

#pragma once

#include <glm/glm.hpp>

namespace sre {

    // The color class represent a sRGBA color, (RGB is in gamma space, whereas alpha is in linear space)
    class Color {
    public:
        Color() = default;
        Color(float r, float g, float b, float a = 1.0f);
        explicit Color(glm::vec4 linearColor);

        float& operator[] (int index);

        glm::vec4 toLinear();             // Return color values in linear space
        void setFromLinear(glm::vec4 linear); // Set sRGBA values from linear space

        float r = 0;
        float g = 0;
        float b = 0;
        float a = 1;
    };
}<|endoftext|>


<commit_before>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);
	// Read galaxies
    /*
	Gals G;
    if(F.Ascii){
        G=read_galaxies_ascii(F);}
    else{
        G = read_galaxies(F);
    }
	F.Ngal = G.size();
	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
    std::vector<int> count;
    count=count_galaxies(G);
    printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
    for(int i=0;i<8;i++){printf (" type %d number  %d  \n",i, count[i]);}
    // make MTL
    //MTL Min=make_MTL(G,F);
    //write_MTLfile(Min);
     */
    MTL M=read_MTLfile(F);
    F.Ngal = M.size();
    assign_priority_class(M);
    //find available SS and SF galaxies on each petal

    std::vector <int> count_class(M.priority_list.size(),0);

    printf("Number in each priority class.  The last two are SF and SS.\n");
    for(int i;i<M.size();++i){
        count_class[M[i].priority_class]+=1;
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }

    printf(" number of MTL galaxies  %d\n",M.size());

	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
    F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F); pp.compute_fibsofsp(F);
	Plates P = read_plate_centers(F);
    F.Nplate=P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

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

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

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(M,T,P,pp,F);

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

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

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
	Assignment A(M,F);
	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
	//new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars
                                   // assumes maximum number of observations needed for QSOs, LRGs
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);

    simple_assign(M,P,pp,F,A);

    //diagnostic for skeleton
    std::vector<int> countj(F.Nplate,0);
    int count_total=0;
    for (int j=0;j<F.Nplate;++j){
        int nj=0;
        for(int k=0;k<F.Nfiber;++k){
            if (A.TF[j][k]!=-1){
            nj++;
            count_total++;
            }
        }
        if(nj>0) printf(" j = %d  number assigned= %d\n",j,nj);
    }
    printf(" total assigned = %d\n",count_total);

    //diagnostic(M,G,F,A);
                               /*
    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
                                    // Want to have even distribution of unused fibers
                                    // so we can put in sky fibers and standard stars

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

	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
	for (int i=0; i<1; i++) {                           // more iterations will improve performance slightly
		improve(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
	}
	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
    //try assigning SF and SS before real time assignment
    for (int j=0;j<F.Nplate;++j){
        A.next_plate=j;
        assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation
        assign_unused(j,M,P,pp,F,A);
    }
    if(F.diagnose){
    init_time_at(time,"# Begin real time assignment",t);

	// Still not updated, so all QSO targets have multiple observations etc
	// Apply and update the plan --------------------------------------
    //int pass_intervals[6] {0,500,1000,2000,4000,F.Nplate};
    printf(" pass_intervals  %d %d %d %d %d\n",F.pass_intervals[0],F.pass_intervals[1],F.pass_intervals[2],F.pass_intervals[3],F.pass_intervals[4]);

    for(int i=0;i<F.pass_intervals.size();++i){
        printf(" before pass = %d  at %d  tiles\n",i,F.pass_intervals[i]);
        //display_results("doc/figs/",G,P,pp,F,A,true);
        A.next_plate=F.pass_intervals[i];
        for (int jj=F.pass_intervals[i]; jj<F.Nplate; jj++) {
            int j = A.next_plate;
            //printf(" - Plate %d :\n",j);
            //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl();
            assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation

            assign_unused(j,M,P,pp,F,A);

            A.next_plate++;
        }

        A.next_plate=F.pass_intervals[i];
        for (int jj=F.pass_intervals[i]; jj<F.pass_intervals[i+1]&&jj<F.Nplate; jj++) {
            int j = A.next_plate;

            // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
            if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n");
            A.next_plate++;
        }
        if(A.next_plate<F.Nplate){
        redistribute_tf(M,P,pp,F,A);
        redistribute_tf(M,P,pp,F,A);
        improve(M,P,pp,F,A);
        redistribute_tf(M,P,pp,F,A);
        }
        diagnostic(M,G,F,A);
    }
    }
	// Results -------------------------------------------------------*/
    if (F.Output) for (int j=0; j<F.Nplate; j++){
        write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
    }

    if (F.Output) for (int j=0; j<F.Nplate; j++){
        fa_write(j,F.outDir,M,P,pp,F,A); // Write output
    }
    /*
	display_results("doc/figs/",G,M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
     */

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

	return(0);

}
<commit_msg>not writing ascii out<commit_after>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);
	// Read galaxies
    /*
	Gals G;
    if(F.Ascii){
        G=read_galaxies_ascii(F);}
    else{
        G = read_galaxies(F);
    }
	F.Ngal = G.size();
	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
    std::vector<int> count;
    count=count_galaxies(G);
    printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
    for(int i=0;i<8;i++){printf (" type %d number  %d  \n",i, count[i]);}
    // make MTL
    //MTL Min=make_MTL(G,F);
    //write_MTLfile(Min);
     */
    MTL M=read_MTLfile(F);
    F.Ngal = M.size();
    assign_priority_class(M);
    //find available SS and SF galaxies on each petal

    std::vector <int> count_class(M.priority_list.size(),0);

    printf("Number in each priority class.  The last two are SF and SS.\n");
    for(int i;i<M.size();++i){
        count_class[M[i].priority_class]+=1;
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }

    printf(" number of MTL galaxies  %d\n",M.size());

	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F); pp.compute_fibsofsp(F);
	Plates P = read_plate_centers(F);
	F.Nplate=P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

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

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

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(M,T,P,pp,F);

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

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

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
	Assignment A(M,F);
	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
	//new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars
                                   // assumes maximum number of observations needed for QSOs, LRGs
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);

    simple_assign(M,P,pp,F,A);

    //diagnostic for skeleton
    std::vector<int> countj(F.Nplate,0);
    int count_total=0;
    for (int j=0;j<F.Nplate;++j){
        int nj=0;
        for(int k=0;k<F.Nfiber;++k){
            if (A.TF[j][k]!=-1){
            nj++;
            count_total++;
            }
        }
        if(nj>0) printf(" j = %d  number assigned= %d\n",j,nj);
    }
    printf(" total assigned = %d\n",count_total);

	// Results -------------------------------------------------------*/
    //    if (F.Output) for (int j=0; j<F.Nplate; j++){
    //        write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
    //    }

    if (F.Output) for (int j=0; j<F.Nplate; j++){
        fa_write(j,F.outDir,M,P,pp,F,A); // Write output
    }
    /*
	display_results("doc/figs/",G,M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
     */

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

    return(0);
}
<|endoftext|>