<commit_before>#include <iostream>
#include <stdint.h>
#include <map>
#include <vector>
#include <string>
#include <sys/stat.h>

#include "boost/program_options.hpp"
#include "api/BamReader.h"
#include "utils/bamtools_pileup_engine.h"
#include "utils/bamtools_fasta.h"

#include "model.h"
#include "parsers.h"

using namespace std;
using namespace BamTools;

class VariantVisitor : public PileupVisitor{
    public:
        VariantVisitor(const RefVector& bam_references,
                       const SamHeader& header,
                       const Fasta& idx_ref,
                       const SampleMap& samples,
                       BamAlignment& ali,
                       int qual_cut,
                       int mapping_cut,
                       vector<uint64_t> &denoms) :

            PileupVisitor(), m_idx_ref(idx_ref), m_bam_ref(bam_references),
                             m_header(header), m_samples(samples),
                             m_qual_cut(qual_cut), m_ali(ali),
                             m_denoms(denoms),
                             m_mapping_cut(mapping_cut)
                              { }
        ~VariantVisitor(void) { }
    public:
         void Visit(const PileupPosition& pileupData) {
             uint64_t pos  = pileupData.Position;
             m_idx_ref.GetBase(pileupData.RefId, pos, current_base);
             ReadDataVector fwd_calls (m_samples.size(), ReadData{{ 0,0,0,0 }});
             ReadDataVector rev_calls (m_samples.size(), ReadData{{ 0,0,0,0 }});
             for(auto it = begin(pileupData.PileupAlignments);
                      it !=  end(pileupData.PileupAlignments);
                      ++it){
                 if( include_site(*it, m_mapping_cut, m_qual_cut) ){
                    it->Alignment.GetTag("RG", tag_id);
                    uint32_t sindex = m_samples[tag_id]; //TODO check samples existed!
                    uint16_t bindex  = base_index(it->Alignment.QueryBases[it->PositionInAlignment]);
                    if (bindex < 4 ){
                        if(it->Alignment.IsReverseStrand() ){
                            fwd_calls[sindex].reads[bindex] += 1;
                        }
                        else{
                            rev_calls[sindex].reads[bindex]+= 1;
                        }
                    }
                }
            }
            uint16_t ref_base_idx = base_index(current_base);
            if (ref_base_idx < 4  ){ //TODO Model for bases at which reference is 'N'

                ReadDataVector all_calls (m_samples.size(), ReadData{{ 0,0,0,0 }});
                uint64_t total_depth = 0;
                for(size_t i = 1; i < m_samples.size(); i ++){
                    for(size_t j =0; j < 4; j++){
                        uint16_t sum_calls = fwd_calls[i].reads[j] + rev_calls[i].reads[j];
                        all_calls[i].reads[j] = sum_calls;
                        total_depth += total_depth;
                    }
                }
                uint32_t major_alleles = 0;
                for(auto it = begin(all_calls); it != end(all_calls); ++it){
                    major_alleles +=  *max_element(it->reads, it->reads + 4);
                }
                double major_freq = major_alleles / (double)total_depth;
                if(major_freq < 0.95){
                    return;
                }

                for(size_t i  = 1; i < m_samples.size(); i++){
                   auto Fm = max_element(fwd_calls[i].reads, fwd_calls[i].reads+4);
                   if (*Fm < 3){
                       continue;
                   }
                   auto Rm = max_element(rev_calls[i].reads, rev_calls[i].reads+4);
                   if (*Rm < 3){
                       continue;
                   }
                   if(distance(rev_calls[i].reads, Rm) == distance(fwd_calls[i].reads, Fm)){
                       m_denoms[i] += 1;
                   }
                }
            }
         }

//                ModelInput d = {ref_base_idx, bcalls};
//                double prob_one = TetMAProbOneMutation(m_params,d);
//                double prob = TetMAProbability(m_params, d);
//                if(prob >= m_prob_cut){
//                     *m_ostream << m_bam_ref[pileupData.RefId].RefName << '\t'
//                                << pos << '\t'
//                                << current_base << '\t'
//                                << prob << '\t'
//                                << prob_one << '\t'
//                                << endl;
//                }
//            }
    private:
        RefVector m_bam_ref;
        SamHeader m_header;
        Fasta m_idx_ref;
        SampleMap m_samples;
        BamAlignment& m_ali;
        int m_qual_cut;
        int m_mapping_cut;
        char current_base;
        string tag_id;
        uint64_t chr_index;
        vector<uint64_t>& m_denoms;
};

int main(int argc, char** argv){

    namespace po = boost::program_options;
    string ref_file;
    string config_path;
    po::options_description cmd("Command line options");
    cmd.add_options()
        ("help,h", "Print a help message")
        ("bam,b", po::value<string>()->required(), "Path to BAM file")
        ("bam-index,x", po::value<string>()->default_value(""), "Path to BAM index, (defalult is <bam_path>.bai")
        ("reference,r", po::value<string>(&ref_file)->required(),  "Path to reference genome")
//       ("ancestor,a", po::value<string>(&anc_tag), "Ancestor RG sample ID")
//        ("sample-name,s", po::value<vector <string> >()->required(), "Sample tags")
        ("qual,q", po::value<int>()->default_value(13),
                   "Base quality cuttoff")

        ("mapping-qual,m", po::value<int>()->default_value(13),
                    "Mapping quality cuttoff")

        ("intervals,i", po::value<string>(), "Path to bed file");

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, cmd), vm);

    if (vm.count("help")){
        cout << cmd << endl;
        return 0;
    }

    vm.notify();
    string bam_path = vm["bam"].as<string>();
    string index_path = vm["bam-index"].as<string>();
    if(index_path == ""){
        index_path = bam_path + ".bai";
    }

    BamReader experiment;
    experiment.Open(bam_path);
    experiment.OpenIndex(index_path);
    RefVector references = experiment.GetReferenceData();
    SamHeader header = experiment.GetHeader();

    //Fasta reference
    Fasta reference_genome; // BamTools::Fasta
    struct stat file_info;
    string faidx_path = ref_file + ".fai";
    if (stat(faidx_path.c_str(), &file_info) != 0){
        reference_genome.CreateIndex(faidx_path);
    }
    reference_genome.Open(ref_file, faidx_path);

    // Map readgroups to samples
    // TODO: this presumes first sample is ancestor. True for our data, not for
    // others.
    // First map all sample names to an index for ReadDataVectors
    SampleMap name_map;
    uint16_t sindex = 0;
    for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){
        if(it->HasSample()){
            auto s  = name_map.find(it->Sample);
            if( s == name_map.end()){ // not in there yet
                name_map[it->Sample] = sindex;
                sindex += 1;
            }
        }
    }
    // And now, go back over the read groups to map RG:sample index
    SampleMap samples;
    for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){
        if(it->HasSample()){
            samples[it->ID] = name_map[it->Sample];
        }
    }

    PileupEngine pileup;
    BamAlignment ali;

    vector<uint64_t> denoms (sindex, 0);

    VariantVisitor *v = new VariantVisitor(
            references,
            header,
            reference_genome,
//            vm["sample-name"].as<vector< string> >(),
            samples,
            ali,
            vm["qual"].as<int>(),
            vm["mapping-qual"].as<int>(),
            denoms
        );
    pileup.AddVisitor(v);

    if (vm.count("intervals")){
        BedFile bed (vm["intervals"].as<string>());
        BedInterval region;
        while(bed.get_interval(region) == 0){
            int ref_id = experiment.GetReferenceID(region.chr);
            experiment.SetRegion(ref_id, region.start, ref_id, region.end);
            while( experiment.GetNextAlignment(ali) ){
                pileup.AddAlignment(ali);
            }
        }
    }
    else{
        while( experiment.GetNextAlignment(ali)){
            pileup.AddAlignment(ali);
        }
    }
    pileup.Flush();
    for(size_t i = 0; i < sindex; i++){
        cerr << denoms[i] << '\t';
    }
    cerr << endl;
    return 0;
}

<commit_msg>Calculate denom for a/c/t/g<commit_after>#include <iostream>
#include <stdint.h>
#include <map>
#include <vector>
#include <string>
#include <sys/stat.h>

#include "boost/program_options.hpp"
#include "api/BamReader.h"
#include "utils/bamtools_pileup_engine.h"
#include "utils/bamtools_fasta.h"

#include "model.h"
#include "parsers.h"

using namespace std;
using namespace BamTools;

ModelParams params = {
        0.0001,
        {0.388, 0.112, 0.112, 0.338},
        1e-8,
        0.01,
        0.01,
        0.005
};

void call_ancestor(const ModelParams &params, int ref_allele, const ReadData &d){
	DiploidProbs genotypes = DiploidSequencing(params, ref_allele, d);
    Eigen::Array33d::Index idx;
    //std::cerr << genotypes.maxCoeff() << std::endl;
    genotypes.maxCoeff(&idx);
    uint16_t result[2];
    result[1] = idx / 4;
    result[2] = idx % 4;
    std::cerr << result[1] << '\t' << result[2] << '\t';
}

class VariantVisitor : public PileupVisitor{
    public:
        VariantVisitor(const RefVector& bam_references,
                       const SamHeader& header,
                       const Fasta& idx_ref,
                       const SampleMap& samples,
                       BamAlignment& ali,
                       int qual_cut,
                       int mapping_cut,
                       vector<uint64_t> &denoms) :

            PileupVisitor(), m_idx_ref(idx_ref), m_bam_ref(bam_references),
                             m_header(header), m_samples(samples),
                             m_qual_cut(qual_cut), m_ali(ali),
                             m_denoms(denoms),
                             m_mapping_cut(mapping_cut)
                              { }
        ~VariantVisitor(void) { }
    public:
         void Visit(const PileupPosition& pileupData) {
             uint64_t pos  = pileupData.Position;
             m_idx_ref.GetBase(pileupData.RefId, pos, current_base);
             ReadDataVector fwd_calls (m_samples.size(), ReadData{{ 0,0,0,0 }});
             ReadDataVector rev_calls (m_samples.size(), ReadData{{ 0,0,0,0 }});
             vector<int> keepers (m_samples.size(), 0);
             for(auto it = begin(pileupData.PileupAlignments);
                      it !=  end(pileupData.PileupAlignments);
                      ++it){
                 if( include_site(*it, m_mapping_cut, m_qual_cut) ){
                    it->Alignment.GetTag("RG", tag_id);
                    uint32_t sindex = m_samples[tag_id]; //TODO check samples existed!
                    uint16_t bindex  = base_index(it->Alignment.QueryBases[it->PositionInAlignment]);
                    if (bindex < 4 ){
                        if(it->Alignment.IsReverseStrand() ){
                            fwd_calls[sindex].reads[bindex] += 1;
                        }
                        else{
                            rev_calls[sindex].reads[bindex]+= 1;
                        }
                    }
                }
            }
            uint16_t ref_base_idx = base_index(current_base);
            if (ref_base_idx < 4  ){ //TODO Model for bases at which reference is 'N'

                ReadDataVector all_calls (m_samples.size(), ReadData{{ 0,0,0,0 }});
                uint64_t total_depth = 0;
                for(size_t i = 0; i < m_samples.size(); i ++){
                    for(size_t j =0; j < 4; j++){
                        uint16_t sum_calls = fwd_calls[i].reads[j] + rev_calls[i].reads[j];
                        all_calls[i].reads[j] = sum_calls;
                        total_depth += total_depth;
                    }
                }
                call_ancestor(params, ref_base_idx, all_calls[0]);
                uint32_t major_alleles = 0;
                for(auto it = begin(all_calls); it != end(all_calls); ++it){
                    major_alleles +=  *max_element(it->reads, it->reads + 4);
                }
                double major_freq = major_alleles / (double)total_depth;
                if(major_freq < 0.95){
                    return;
                }

                for(size_t i  = 1; i < m_samples.size(); i++){
                   auto Fm = max_element(fwd_calls[i].reads, fwd_calls[i].reads+4);
                   if (*Fm < 3){
                       continue;
                   }
                   auto Rm = max_element(rev_calls[i].reads, rev_calls[i].reads+4);
                   if (*Rm < 3){
                       continue;
                   }
                   if(distance(rev_calls[i].reads, Rm) == distance(fwd_calls[i].reads, Fm)){
                       m_denoms[i] += 1;
                       keepers[i] = 1;
                   }
                }
            }
         for(size_t i = 0; i < m_samples.size(); i++){
             cerr << keepers[i] << '\t';
         }
         cerr << endl;

         }

//                ModelInput d = {ref_base_idx, bcalls};
//                double prob_one = TetMAProbOneMutation(m_params,d);
//                double prob = TetMAProbability(m_params, d);
//                if(prob >= m_prob_cut){
//                     *m_ostream << m_bam_ref[pileupData.RefId].RefName << '\t'
//                                << pos << '\t'
//                                << current_base << '\t'
//                                << prob << '\t'
//                                << prob_one << '\t'
//                                << endl;
//                }
//            }
    private:
        RefVector m_bam_ref;
        SamHeader m_header;
        Fasta m_idx_ref;
        SampleMap m_samples;
        BamAlignment& m_ali;
        int m_qual_cut;
        int m_mapping_cut;
        char current_base;
        string tag_id;
        uint64_t chr_index;
        vector<uint64_t>& m_denoms;
};

int main(int argc, char** argv){

    namespace po = boost::program_options;
    string ref_file;
    string config_path;
    po::options_description cmd("Command line options");
    cmd.add_options()
        ("help,h", "Print a help message")
        ("bam,b", po::value<string>()->required(), "Path to BAM file")
        ("bam-index,x", po::value<string>()->default_value(""), "Path to BAM index, (defalult is <bam_path>.bai")
        ("reference,r", po::value<string>(&ref_file)->required(),  "Path to reference genome")
//       ("ancestor,a", po::value<string>(&anc_tag), "Ancestor RG sample ID")
//        ("sample-name,s", po::value<vector <string> >()->required(), "Sample tags")
        ("qual,q", po::value<int>()->default_value(13),
                   "Base quality cuttoff")

        ("mapping-qual,m", po::value<int>()->default_value(13),
                    "Mapping quality cuttoff")

        ("intervals,i", po::value<string>(), "Path to bed file");

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, cmd), vm);

    if (vm.count("help")){
        cout << cmd << endl;
        return 0;
    }

    vm.notify();
    string bam_path = vm["bam"].as<string>();
    string index_path = vm["bam-index"].as<string>();
    if(index_path == ""){
        index_path = bam_path + ".bai";
    }

    BamReader experiment;
    experiment.Open(bam_path);
    experiment.OpenIndex(index_path);
    RefVector references = experiment.GetReferenceData();
    SamHeader header = experiment.GetHeader();

    //Fasta reference
    Fasta reference_genome; // BamTools::Fasta
    struct stat file_info;
    string faidx_path = ref_file + ".fai";
    if (stat(faidx_path.c_str(), &file_info) != 0){
        reference_genome.CreateIndex(faidx_path);
    }
    reference_genome.Open(ref_file, faidx_path);

    // Map readgroups to samples
    // TODO: this presumes first sample is ancestor. True for our data, not for
    // others.
    // First map all sample names to an index for ReadDataVectors
    SampleMap name_map;
    uint16_t sindex = 0;
    for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){
        if(it->HasSample()){
            auto s  = name_map.find(it->Sample);
            if( s == name_map.end()){ // not in there yet
                name_map[it->Sample] = sindex;
                sindex += 1;
            }
        }
    }
    // And now, go back over the read groups to map RG:sample index
    SampleMap samples;
    for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){
        if(it->HasSample()){
            cout << it->Sample<< endl;
            samples[it->ID] = name_map[it->Sample];
        }
    }

    PileupEngine pileup;
    BamAlignment ali;

    vector<uint64_t> denoms (sindex, 0);

    VariantVisitor *v = new VariantVisitor(
            references,
            header,
            reference_genome,
//            vm["sample-name"].as<vector< string> >(),
            samples,
            ali,
            vm["qual"].as<int>(),
            vm["mapping-qual"].as<int>(),
            denoms
        );
    pileup.AddVisitor(v);

    if (vm.count("intervals")){
        BedFile bed (vm["intervals"].as<string>());
        BedInterval region;
        while(bed.get_interval(region) == 0){
            int ref_id = experiment.GetReferenceID(region.chr);
            experiment.SetRegion(ref_id, region.start, ref_id, region.end);
            while( experiment.GetNextAlignment(ali) ){
                pileup.AddAlignment(ali);
            }
        }
    }
    else{
        while( experiment.GetNextAlignment(ali)){
            pileup.AddAlignment(ali);
        }
    }
    pileup.Flush();
//    for(size_t i = 0; i < sindex; i++){
//        cerr << denoms[i] << '\t';
//    }
//    cerr << endl;
    return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007, 2008, 2009, 2010, 2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file urbi/uvar.hh
#ifndef URBI_UVAR_HH
# define URBI_UVAR_HH

# include <iosfwd>
# include <string>

# include <libport/fwd.hh>
# include <libport/ufloat.hh>

# include <urbi/ucontext.hh>
# include <urbi/uvalue.hh>
# include <urbi/uprop.hh>
# include <urbi/uproperty.hh>

namespace urbi
{
  /** UVar class definition

     Each UVar instance corresponds to one URBI variable. The class
     provides access to the variable properties, and reading/writing
     the value to/from all known types.  */
  class URBI_SDK_API UVar: public UContext
  {
  public:
    /// Creates an unbound UVar. Call init() to bind it.
    UVar();
    UVar(const std::string&, impl::UContextImpl* = 0);
    UVar(const std::string&, const std::string&, impl::UContextImpl* = 0);
    UVar(UObject&, const std::string&, impl::UContextImpl* = 0);
    UVar(const UVar&);
  private:
    UVar& operator=(const UVar&);
  public:
    ~UVar();

    // Bind to \a object.slot.
    void init(const std::string& varname, impl::UContextImpl* = 0);
    void init(const std::string& object, const std::string& slot,
              impl::UContextImpl* = 0);
    void setOwned();

    /// The type of the current content.
    UDataType type() const;

    /// Request the current value, wait until it is available.
    void syncValue();

    /// Keep this UVar synchronized with kernel value.
    void keepSynchronized();

    void reset (ufloat);

    UVar& operator=(ufloat);
    UVar& operator=(const std::string&);
    /// Deep copy.
    UVar& operator=(const UBinary&);
    /// Deep copy.
    UVar& operator=(const UImage& i);
    /// Deep copy.
    UVar& operator=(const USound& s);

    UVar& operator=(const UList& l);

    UVar& operator=(const UDictionary& d);

    UVar& operator=(const UValue& v);

    template<typename T>
    UVar& operator=(const T&);

    template<typename T>
    bool operator ==(const T&) const;

    /// Cast operator taking a dummy value of the target type.
    template<typename T> T as(T*) const;
    /// Generic cast operator using the extensible uvalue_cast mechanism.
    template<typename T> T as() const;
    /// Conveniance wrapper on as().
    template<typename T> T& fill(T&) const;

    operator int() const;
    operator bool() const;

    // Cast to a UBinary to make copy through this operator.
    operator const UBinary&() const;

    /// Deep copy, binary will have to be deleted by the user.
    operator UBinary*() const;

    /// In plugin mode, gives direct access to the buffer, which may
    /// not be valid after the calling function returns. Changes to
    /// the other fields of the structure have no effect.
    operator UImage() const;

    /// In plugin mode, gives direct access to the buffer, which may
    /// not be valid after the calling function returns. Changes to
    /// the other fields of the structure have no effect.
    operator USound() const;

    operator ufloat() const;
    operator std::string() const;
    operator UList() const;
    operator UDictionary() const;

    /// Deactivate all callbacks associated with this UVar and stop synchro.
    void unnotify();

    /// Kernel operators.
    ufloat& in();
    ufloat& out();

    /// Is the variable owned by the module?
    bool owned;

    /// Property accessors.
    UProp rangemin;
    UProp rangemax;
    UProp speedmin;
    UProp speedmax;
    UProp delta;
    UProp blend;
    UProp constant;

    UValue getProp(UProperty prop);
    void setProp(UProperty prop, const UValue& v);
    void setProp(UProperty prop, ufloat v);
    void setProp(UProperty prop, const char* v);
    void setProp(UProperty prop, const std::string& v)
    {
      setProp(prop, v.c_str());
    }

    /// Enable bypass-mode for this UVar. Plugin-mode only.
    /// In bypass mode, if the UVar contains binary data, the data is never
    /// copied. The consequence is that the data is only accessible from
    /// notifyChange callbacks (urbiScript or C++): it is invalidated as soon
    /// as all callbacks have returned.
    bool setBypass(bool enable=true);

    /// Use RTP mode to transmit this variable if possible.
    void useRTP(bool enable=true);
    impl::UVarImpl* impl_;
    const UValue& val() const;
    ATTRIBUTE_PURE
    libport::utime_t timestamp() const;

    enum RtpMode
    {
      RTP_DEFAULT, ///< Use RTP if it is the default mode
      RTP_YES,     ///< Force RTP
      RTP_NO       ///< Do not use RTP
    };

     /// Check that impl_ is set or throw a runtime error.
    void check() const;

  private:
    /// Pointer to internal data specifics.
    UVardata* vardata;
    void __init();

/// Define an attribute and its accessors.
# define PRIVATE(Type, Name)			\
  public:					\
    Type get_ ##  Name ()			\
    {						\
      return Name;				\
    }						\
    Type get_ ##  Name () const		        \
    {						\
      return Name;				\
    }						\
    void set_ ##  Name (const Type& v)		\
    {						\
      Name = v;					\
    }						\
  private:					\
    Type Name;

    /// Full name of the variable as seen in URBI.
    PRIVATE(std::string, name)

    /// True if the variable is a temporary and must not be stored in callbacks
    PRIVATE(bool, temp);

    PRIVATE(RtpMode, rtp);

    /// If set, this variable will never export its content remotely.
    PRIVATE(bool, local);
# undef PRIVATE

    // Check that the invariants of this class are verified.
    bool invariant() const;
    friend class impl::UVarImpl;
  };

  /*-------------------------.
  | Inline implementations.  |
  `-------------------------*/

  /// Helper macro to initialize UProps in UVar constructors.
#  define VAR_PROP_INIT                         \
  rangemin(*this, PROP_RANGEMIN),		\
  rangemax(*this, PROP_RANGEMAX),		\
  speedmin(*this, PROP_SPEEDMIN),		\
  speedmax(*this, PROP_SPEEDMAX),		\
  delta(*this, PROP_DELTA),			\
  blend(*this, PROP_BLEND),                     \
  constant(*this, PROP_CONSTANT)

  /// Report \a u on \a o for debugging.
  URBI_SDK_API
  std::ostream& operator<< (std::ostream& o, const UVar& u);

} // end namespace urbi

# include <urbi/uvar.hxx>

#endif // ! URBI_UVAR_HH
<commit_msg>UObject: Prevent "*UVar".<commit_after>/*
 * Copyright (C) 2007, 2008, 2009, 2010, 2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file urbi/uvar.hh
#ifndef URBI_UVAR_HH
# define URBI_UVAR_HH

# include <iosfwd>
# include <string>

# include <libport/fwd.hh>
# include <libport/ufloat.hh>

# include <urbi/ucontext.hh>
# include <urbi/uvalue.hh>
# include <urbi/uprop.hh>
# include <urbi/uproperty.hh>

namespace urbi
{
  /** UVar class definition

     Each UVar instance corresponds to one URBI variable. The class
     provides access to the variable properties, and reading/writing
     the value to/from all known types.  */
  class URBI_SDK_API UVar: public UContext
  {
  public:
    /// Creates an unbound UVar. Call init() to bind it.
    UVar();
    UVar(const std::string&, impl::UContextImpl* = 0);
    UVar(const std::string&, const std::string&, impl::UContextImpl* = 0);
    UVar(UObject&, const std::string&, impl::UContextImpl* = 0);
    UVar(const UVar&);
  private:
    UVar& operator=(const UVar&);
  public:
    ~UVar();

    // Bind to \a object.slot.
    void init(const std::string& varname, impl::UContextImpl* = 0);
    void init(const std::string& object, const std::string& slot,
              impl::UContextImpl* = 0);
    void setOwned();

    /// The type of the current content.
    UDataType type() const;

    /// Request the current value, wait until it is available.
    void syncValue();

    /// Keep this UVar synchronized with kernel value.
    void keepSynchronized();

    void reset (ufloat);

    UVar& operator=(ufloat);
    UVar& operator=(const std::string&);
    /// Deep copy.
    UVar& operator=(const UBinary&);
    /// Deep copy.
    UVar& operator=(const UImage& i);
    /// Deep copy.
    UVar& operator=(const USound& s);

    UVar& operator=(const UList& l);

    UVar& operator=(const UDictionary& d);

    UVar& operator=(const UValue& v);

    template<typename T>
    UVar& operator=(const T&);

    template<typename T>
    bool operator ==(const T&) const;

    /// Cast operator taking a dummy value of the target type.
    template<typename T> T as(T*) const;
    /// Generic cast operator using the extensible uvalue_cast mechanism.
    template<typename T> T as() const;
    /// Conveniance wrapper on as().
    template<typename T> T& fill(T&) const;

    operator int() const;
    operator bool() const;

    // Cast to a UBinary to make copy through this operator.
    operator const UBinary&() const;

    /// Deep copy, binary will have to be deleted by the user.
    operator UBinary*() const;

    /// In plugin mode, gives direct access to the buffer, which may
    /// not be valid after the calling function returns. Changes to
    /// the other fields of the structure have no effect.
    operator UImage() const;

    /// In plugin mode, gives direct access to the buffer, which may
    /// not be valid after the calling function returns. Changes to
    /// the other fields of the structure have no effect.
    operator USound() const;

    operator ufloat() const;
    operator std::string() const;
    operator UList() const;
    operator UDictionary() const;

    /// Deactivate all callbacks associated with this UVar and stop synchro.
    void unnotify();

    /// Kernel operators.
    ufloat& in();
    ufloat& out();

    /// Is the variable owned by the module?
    bool owned;

    /// Property accessors.
    UProp rangemin;
    UProp rangemax;
    UProp speedmin;
    UProp speedmax;
    UProp delta;
    UProp blend;
    UProp constant;

    UValue getProp(UProperty prop);
    void setProp(UProperty prop, const UValue& v);
    void setProp(UProperty prop, ufloat v);
    void setProp(UProperty prop, const char* v);
    void setProp(UProperty prop, const std::string& v)
    {
      setProp(prop, v.c_str());
    }

    /// Enable bypass-mode for this UVar. Plugin-mode only.
    /// In bypass mode, if the UVar contains binary data, the data is never
    /// copied. The consequence is that the data is only accessible from
    /// notifyChange callbacks (urbiScript or C++): it is invalidated as soon
    /// as all callbacks have returned.
    bool setBypass(bool enable=true);

    /// Use RTP mode to transmit this variable if possible.
    void useRTP(bool enable=true);
    impl::UVarImpl* impl_;
    const UValue& val() const;
    ATTRIBUTE_PURE
    libport::utime_t timestamp() const;

    enum RtpMode
    {
      RTP_DEFAULT, ///< Use RTP if it is the default mode
      RTP_YES,     ///< Force RTP
      RTP_NO,      ///< Do not use RTP
    };

     /// Check that impl_ is set or throw a runtime error.
    void check() const;

  private:
    /// Pointer to internal data specifics.
    UVardata* vardata;
    void __init();
    /// Check that the invariants of this class are verified.
    bool invariant() const;
    friend class impl::UVarImpl;

    // C++ allows "*uvar", it makes it "*(uvar.operator UBinary*())".
    // This operator is there to avoid this.
    void operator*() const;

/// Define an attribute and its accessors.
# define PRIVATE(Type, Name)			\
  public:					\
    Type get_ ##  Name ()			\
    {						\
      return Name;				\
    }						\
    Type get_ ##  Name () const		        \
    {						\
      return Name;				\
    }						\
    void set_ ##  Name (const Type& v)		\
    {						\
      Name = v;					\
    }						\
  private:					\
    Type Name;

    /// Full name of the variable as seen in URBI.
    PRIVATE(std::string, name)

    /// True if the variable is a temporary and must not be stored in callbacks
    PRIVATE(bool, temp);

    PRIVATE(RtpMode, rtp);

    /// If set, this variable will never export its content remotely.
    PRIVATE(bool, local);
# undef PRIVATE
  };

  /*-------------------------.
  | Inline implementations.  |
  `-------------------------*/

  /// Helper macro to initialize UProps in UVar constructors.
#  define VAR_PROP_INIT                         \
  rangemin(*this, PROP_RANGEMIN),		\
  rangemax(*this, PROP_RANGEMAX),		\
  speedmin(*this, PROP_SPEEDMIN),		\
  speedmax(*this, PROP_SPEEDMAX),		\
  delta(*this, PROP_DELTA),			\
  blend(*this, PROP_BLEND),                     \
  constant(*this, PROP_CONSTANT)

  /// Report \a u on \a o for debugging.
  URBI_SDK_API
  std::ostream& operator<< (std::ostream& o, const UVar& u);

} // end namespace urbi

# include <urbi/uvar.hxx>

#endif // ! URBI_UVAR_HH
<|endoftext|>


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

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <memory>
#include <type_traits>

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

#include <dune/grid/io/file/vtk.hh>

#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/spaces/interface.hh>

#include "local.hh"

namespace Dune {
namespace GDT {

template <class SpaceImp, class VectorImp>
class ConstDiscreteFunction
    : public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                                 SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                                 SpaceImp::dimRange, SpaceImp::dimRangeCols>
{
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
                "Types do not match!");
  typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                              SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                              SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType;
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  static const unsigned int dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainFieldType DomainFieldType;
  typedef typename BaseType::DomainType DomainType;

  static const unsigned int dimRange     = BaseType::dimRange;
  static const unsigned int dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeFieldType RangeFieldType;
  typedef typename BaseType::RangeType RangeType;
  typedef typename BaseType::JacobianRangeType JacobianRangeType;

  typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType;

  ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(sp)
    , vector_(vec)
    , name_(nm)
  {
    assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
  }

  ConstDiscreteFunction(const ThisType& other)
    : space_(other.space_)
    , vector_(other.vector_)
    , name_(other.name_)
  {
  }

  ConstDiscreteFunction(ThisType&& source)
    : space_(source.space_)
    , vector_(source.vector_)
    , name_(std::move(source.name_))
  {
  }

  virtual ~ConstDiscreteFunction()
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  virtual std::string name() const DS_OVERRIDE
  {
    return name_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const VectorType& vector() const
  {
    return vector_;
  }

  ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const
  {
    assert(space_.grid_view()->indexSet().contains(entity));
    return ConstLocalDiscreteFunctionType(space_, vector_, entity);
  }

  virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const DS_OVERRIDE
  {
    return std::unique_ptr<ConstLocalDiscreteFunctionType>(
        new ConstLocalDiscreteFunctionType(local_discrete_function(entity)));
  }

  void visualize(const std::string filename, const bool subsampling = (SpaceType::polOrder > 1),
                 VTK::OutputType vtk_output_type = VTK::appendedraw) const
  {
    BaseType::template visualize<typename SpaceType::GridViewType>(
        *(space().grid_view()), filename, subsampling, vtk_output_type);
  }

protected:
  const SpaceType& space_;

private:
  const VectorType& vector_;
  const std::string name_;
}; // class ConstDiscreteFunction

template <class SpaceImp, class VectorImp>
class DiscreteFunction : public ConstDiscreteFunction<SpaceImp, VectorImp>
{
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef DiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;

  DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction")
    : BaseType(sp, vec, nm)
    , vector_(vec)
  {
  }

  DiscreteFunction(const ThisType& other)
    : BaseType(other)
    , vector_(other.vector_)
  {
  }

  DiscreteFunction(ThisType&& source)
    : BaseType(std::move(source))
    , vector_(source.vector_)
  {
  }

  ~DiscreteFunction()
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  VectorType& vector()
  {
    return vector_;
  }

  using BaseType::local_discrete_function;

  LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
  {
    assert(space_.grid_view()->indexSet().contains(entity));
    return LocalDiscreteFunctionType(space_, vector_, entity);
  }

private:
  using BaseType::space_;
  VectorType& vector_;
}; // class DiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<commit_msg>[df] adds new DiscreteFunction with internal vector storage<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <memory>
#include <type_traits>

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

#include <dune/grid/io/file/vtk.hh>

#include <dune/stuff/la/container/interfaces.hh>
#include <dune/stuff/functions/interfaces.hh>

#include <dune/gdt/spaces/interface.hh>

#include "local.hh"

namespace Dune {
namespace GDT {

template <class SpaceImp, class VectorImp>
class ConstDiscreteFunction
    : public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                                 SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                                 SpaceImp::dimRange, SpaceImp::dimRangeCols>
{
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
                "Types do not match!");
  typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                              SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                              SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType;
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  static const unsigned int dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainFieldType DomainFieldType;
  typedef typename BaseType::DomainType DomainType;

  static const unsigned int dimRange     = BaseType::dimRange;
  static const unsigned int dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeFieldType RangeFieldType;
  typedef typename BaseType::RangeType RangeType;
  typedef typename BaseType::JacobianRangeType JacobianRangeType;

  typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType;

  ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(sp)
    , vector_(vec)
    , name_(nm)
  {
    assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
  }

  ConstDiscreteFunction(const ThisType& other)
    : space_(other.space_)
    , vector_(other.vector_)
    , name_(other.name_)
  {
  }

  ConstDiscreteFunction(ThisType&& source)
    : space_(source.space_)
    , vector_(source.vector_)
    , name_(std::move(source.name_))
  {
  }

  virtual ~ConstDiscreteFunction()
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  virtual std::string name() const DS_OVERRIDE
  {
    return name_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const VectorType& vector() const
  {
    return vector_;
  }

  ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const
  {
    assert(space_.grid_view()->indexSet().contains(entity));
    return ConstLocalDiscreteFunctionType(space_, vector_, entity);
  }

  virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const DS_OVERRIDE
  {
    return std::unique_ptr<ConstLocalDiscreteFunctionType>(
        new ConstLocalDiscreteFunctionType(local_discrete_function(entity)));
  }

  void visualize(const std::string filename, const bool subsampling = (SpaceType::polOrder > 1),
                 VTK::OutputType vtk_output_type = VTK::appendedraw) const
  {
    BaseType::template visualize<typename SpaceType::GridViewType>(
        *(space().grid_view()), filename, subsampling, vtk_output_type);
  }

protected:
  const SpaceType& space_;

private:
  const VectorType& vector_;
  const std::string name_;
}; // class ConstDiscreteFunction

template <class SpaceImp, class VectorImp>
class DiscreteFunction : public ConstDiscreteFunction<SpaceImp, VectorImp>
{
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef DiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;

  DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction")
    : BaseType(sp, vec, nm)
    , vector_(vec)
  {
  }

  DiscreteFunction(const ThisType& other)
    : BaseType(other)
    , vector_(other.vector_)
  {
  }

  DiscreteFunction(ThisType&& source)
    : BaseType(std::move(source))
    , vector_(source.vector_)
  {
  }

  ~DiscreteFunction()
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  VectorType& vector()
  {
    return vector_;
  }

  using BaseType::local_discrete_function;

  LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
  {
    assert(space_.grid_view()->indexSet().contains(entity));
    return LocalDiscreteFunctionType(space_, vector_, entity);
  }

private:
  using BaseType::space_;
  VectorType& vector_;
}; // class DiscreteFunction

template <class SpaceImp, class VectorImp>
class StoredDiscreteFunction : public DiscreteFunction<SpaceImp, VectorImp>
{
  typedef DiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef StoredDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;

  StoredDiscreteFunction(const SpaceType& sp, const std::string nm = "dune.gdt.discretefunction")
    : BaseType(sp, vector_, nm)
    , vector_(sp.mapper().size())
  {
  }

  ~StoredDiscreteFunction()
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  VectorType& vector()
  {
    return vector_;
  }

  LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
  {
    return LocalDiscreteFunctionType(BaseType::space(), vector_, entity);
  }

  bool dofsValid() const
  {
    for (const auto& val : vector_) {
      if (std::isnan(val) || std::isinf(val))
        return false;
    }
    return true;
  }

private:
  VectorType vector_;
}; // class DiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<|endoftext|>


<commit_before>#include "PackTexture.h"
#include "check_params.h"
#include "utility.h"

#include <ee/FileHelper.h>
#include <ee/SettingData.h>
#include <ee/Config.h>
#include <ee/StringHelper.h>
#include <ee/SymbolFile.h>

#include <easytexpacker.h>
#include <easyimage.h>

#include <gimg_typedef.h>
#include <gimg_import.h>
#include <sprite2/SymType.h>
#include <gum/Config.h>

#include <wx/filefn.h>

#include <fstream>

namespace edb
{

std::string PackTexture::Command() const
{
	return "pack-tex";
}

std::string PackTexture::Description() const
{
	return "pack texture";
}

std::string PackTexture::Usage() const
{
	std::string cmd0 = Command() + " [json str]";
	std::string cmd1 = Command() + " [src dir] [dst dir] [min size] [max size] [trim file] [extrude]";
	return cmd0 + " or " + cmd1;
}

int PackTexture::Run(int argc, char *argv[])
{
	if (!check_number(this, argc, 3)) return -1;

	int ret = init_gl();
	if (ret < 0) {
		return ret;
	}

	// one param
	if (argc == 3)
	{
		Pack(argv[2]);
	}
	// multi params
	else
	{
		Package pkg;

		pkg.sources.push_back(argv[2]);
		pkg.format = "png";

		pkg.size_min = atof(argv[4]);
		pkg.size_max = atof(argv[5]);

		if (argc > 6) {
			if (strcmp(argv[6], "null") != 0) {
				pkg.trim = new etexpacker::ImageTrimData(argv[6]);
			}
		}

		int extrude = 1;
		if (argc > 7) {
			extrude = atoi(argv[7]);
		}
		pkg.extrude_min = pkg.extrude_max = extrude;

		std::vector<Package> packages;
		packages.push_back(pkg);
		std::string dst_file = argv[3];
		Pack(packages, argv[2], dst_file);

		delete pkg.trim;
	}

	return 0;
}

void PackTexture::Pack(const std::string& str_val)
{
	std::vector<Package> packages;
	std::string src_dir, dst_file;
	etexpacker::ImageTrimData* trim = PreparePackages(str_val, packages, src_dir, dst_file);
	Pack(packages, src_dir, dst_file);
	delete trim;
}

void PackTexture::Pack(const std::vector<Package>& packages, const std::string& src_dir, const std::string& dst_file)
{
	std::string dst_dir = ee::FileHelper::GetFileDir(dst_file);
	ee::FileHelper::MkDir(dst_dir);

	ee::SettingData& sd = ee::Config::Instance()->GetSettings();
	bool ori_cfg = sd.open_image_edge_clip;
	sd.open_image_edge_clip = false;

	int start_id = 1;
	for (int i = 0, n = packages.size(); i < n; ++i) {
		PackPackage(packages[i], src_dir, dst_file, start_id);
	}

	sd.open_image_edge_clip = ori_cfg;
}

void PackTexture::CompressPackedTex(const etexpacker::NormalPack& tp, int& start_id,
									const std::string& file, const std::string& fmt, bool fast)
{
	int begin = start_id;
	start_id += tp.DstTexCount();
	int end = start_id;
	if (fmt == "pvr")
	{
		for (int i = begin; i < end; ++i)
		{
			std::string src = file + ee::StringHelper::ToString(i) + ".png";
			std::string dst = file + ee::StringHelper::ToString(i) + ".pvr";

			int w, h, fmt;
			uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt);
			if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) {
				gimg_pre_mul_alpha(pixels, w, h);
			}

			int c = fmt == GPF_RGB ? 3 : 4;

			eimage::TransToPVR trans(pixels, w, h, c, false, fast);
			delete[] pixels;

			trans.OutputFile(dst);
//			wxRemoveFile(src);
		}
	}
	else if (fmt == "etc1")
	{
		for (int i = begin; i < end; ++i)
		{
			std::string src = file + ee::StringHelper::ToString(i) + ".png";
			std::string dst = file + ee::StringHelper::ToString(i);

			int w, h, fmt;
			uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt);
			if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) {
				gimg_pre_mul_alpha(pixels, w, h);
			}

			int c = fmt == GPF_RGB ? 3 : 4;

			eimage::TransToETC1 trans(pixels, w, h, c, false, fast);
			delete[] pixels;

			trans.OutputFile(dst);
//			wxRemoveFile(src);
		}
	}
	else if (fmt == "etc2")
	{
		for (int i = begin; i < end; ++i)
		{
			std::string src = file + ee::StringHelper::ToString(i) + ".png";
			std::string dst = file + ee::StringHelper::ToString(i) + ".pkm";

			int w, h, fmt;
			uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt);
			if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) {
				gimg_pre_mul_alpha(pixels, w, h);
			}

			int c = fmt == GPF_RGB ? 3 : 4;

			eimage::TransToETC2 trans(pixels, w, h, c, eimage::TransToETC2::RGBA, false, fast);
			delete[] pixels;

			trans.OutputFile(dst);
//			wxRemoveFile(src);
		}
	}
}

etexpacker::ImageTrimData* PackTexture::PreparePackages(const std::string& str, std::vector<Package>& packages,
														std::string& src_dir, std::string& dst_file)
{
	Json::Value value;
	Json::Reader reader;
	reader.parse(str, value);

	src_dir = value["src"].asString();
	dst_file = value["dst"].asString();
	etexpacker::ImageTrimData* trim = NULL;
	if (!value["trim_file"].isNull()) {
		std::string trim_file = value["trim_file"].asString();
		trim = new etexpacker::ImageTrimData(trim_file);
	}

	const Json::Value& pkgs_val = value["packages"];
	for (int i = 0, n = pkgs_val.size(); i < n; ++i)
	{
		const Json::Value& v = pkgs_val[i];
		Package pkg;
		if (v["src"].isString()) {
			pkg.sources.push_back(v["src"].asString());
		} else {
			assert(v["src"].isArray());
			for (int i = 0, n = v["src"].size(); i < n; ++i) {
				pkg.sources.push_back(v["src"][i].asString());
			}
		}
		pkg.format = v["format"].asString();
		pkg.quality = v["quality"].asString();
		pkg.size_max = v["size_max"].asInt();
		pkg.size_min = v["size_min"].asInt();
		pkg.trim = trim;
		pkg.extrude_min = v["extrude_min"].asInt();
		pkg.extrude_max = v["extrude_max"].asInt();
		packages.push_back(pkg);
	}

	for (int i = 0, n = packages.size(); i < n; ++i) {
		Package& pkg0 = packages[i];
		if (pkg0.sources.size() == 1 && pkg0.sources[0] == "others")
		{
			for (int j = 0; j < n; ++j)
			{
				if (j == i) continue;
				const Package& pkg1 = packages[j];
				if (pkg1.sources.size() == 1 && pkg1.sources[0] == "others")  {
					continue;
				}
				for (int k = 0, m = pkg1.sources.size(); k < m; ++k) {
					const std::string& path = pkg1.sources[k];
					if (path != "others" && path != src_dir) {
						pkg0.ignores.push_back(path);
					}
				}
			}
			pkg0.sources[0] = src_dir;
		}
	}

	return trim;
}

void PackTexture::PackPackage(const Package& pkg, const std::string& src_dir,
							  const std::string& dst_file, int& start_id)
{
	std::vector<std::string> images;

	wxArrayString files;
	if (pkg.ignores.empty()) {
		for (int i = 0, n = pkg.sources.size(); i < n; ++i) {
			ee::FileHelper::FetchAllFiles(pkg.sources[i], files);
		}
	} else {
		for (int i = 0, n = pkg.sources.size(); i < n; ++i) {
			ee::FileHelper::FetchAllFiles(pkg.sources[i], pkg.ignores, files);
		}
	}
	for (int i = 0, n = files.size(); i < n; ++i) {
		if (ee::SymbolFile::Instance()->Type(files[i].ToStdString()) == s2::SYM_IMAGE) {
			std::string filepath = ee::FileHelper::FormatFilepathAbsolute(files[i].ToStdString());
			images.push_back(filepath);
		}
	}

	etexpacker::NormalPack tex_packer(images, pkg.trim, pkg.extrude_min, pkg.extrude_max, start_id);
	tex_packer.Pack(0, pkg.size_max, pkg.size_min);
	tex_packer.OutputInfo(src_dir, dst_file + ".json", pkg.format);
	tex_packer.OutputImage(dst_file + ".png");

	CompressPackedTex(tex_packer, start_id, dst_file, pkg.format, pkg.quality == "fastest");
}

}<commit_msg>[FIXED] pack compressed texture should not pre mul alpha, because it is read from png, already pre mul alpha.<commit_after>#include "PackTexture.h"
#include "check_params.h"
#include "utility.h"

#include <ee/FileHelper.h>
#include <ee/SettingData.h>
#include <ee/Config.h>
#include <ee/StringHelper.h>
#include <ee/SymbolFile.h>

#include <easytexpacker.h>
#include <easyimage.h>

#include <gimg_typedef.h>
#include <gimg_import.h>
#include <sprite2/SymType.h>
#include <gum/Config.h>

#include <wx/filefn.h>

#include <fstream>

namespace edb
{

std::string PackTexture::Command() const
{
	return "pack-tex";
}

std::string PackTexture::Description() const
{
	return "pack texture";
}

std::string PackTexture::Usage() const
{
	std::string cmd0 = Command() + " [json str]";
	std::string cmd1 = Command() + " [src dir] [dst dir] [min size] [max size] [trim file] [extrude]";
	return cmd0 + " or " + cmd1;
}

int PackTexture::Run(int argc, char *argv[])
{
	if (!check_number(this, argc, 3)) return -1;

	int ret = init_gl();
	if (ret < 0) {
		return ret;
	}

	// one param
	if (argc == 3)
	{
		Pack(argv[2]);
	}
	// multi params
	else
	{
		Package pkg;

		pkg.sources.push_back(argv[2]);
		pkg.format = "png";

		pkg.size_min = atof(argv[4]);
		pkg.size_max = atof(argv[5]);

		if (argc > 6) {
			if (strcmp(argv[6], "null") != 0) {
				pkg.trim = new etexpacker::ImageTrimData(argv[6]);
			}
		}

		int extrude = 1;
		if (argc > 7) {
			extrude = atoi(argv[7]);
		}
		pkg.extrude_min = pkg.extrude_max = extrude;

		std::vector<Package> packages;
		packages.push_back(pkg);
		std::string dst_file = argv[3];
		Pack(packages, argv[2], dst_file);

		delete pkg.trim;
	}

	return 0;
}

void PackTexture::Pack(const std::string& str_val)
{
	std::vector<Package> packages;
	std::string src_dir, dst_file;
	etexpacker::ImageTrimData* trim = PreparePackages(str_val, packages, src_dir, dst_file);
	Pack(packages, src_dir, dst_file);
	delete trim;
}

void PackTexture::Pack(const std::vector<Package>& packages, const std::string& src_dir, const std::string& dst_file)
{
	std::string dst_dir = ee::FileHelper::GetFileDir(dst_file);
	ee::FileHelper::MkDir(dst_dir);

	ee::SettingData& sd = ee::Config::Instance()->GetSettings();
	bool ori_cfg = sd.open_image_edge_clip;
	sd.open_image_edge_clip = false;

	int start_id = 1;
	for (int i = 0, n = packages.size(); i < n; ++i) {
		PackPackage(packages[i], src_dir, dst_file, start_id);
	}

	sd.open_image_edge_clip = ori_cfg;
}

void PackTexture::CompressPackedTex(const etexpacker::NormalPack& tp, int& start_id,
									const std::string& file, const std::string& fmt, bool fast)
{
	int begin = start_id;
	start_id += tp.DstTexCount();
	int end = start_id;
	if (fmt == "pvr")
	{
		for (int i = begin; i < end; ++i)
		{
			std::string src = file + ee::StringHelper::ToString(i) + ".png";
			std::string dst = file + ee::StringHelper::ToString(i) + ".pvr";

			int w, h, fmt;
			uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt);
// 			if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) {
// 				gimg_pre_mul_alpha(pixels, w, h);
// 			}

			int c = fmt == GPF_RGB ? 3 : 4;

			eimage::TransToPVR trans(pixels, w, h, c, false, fast);
			delete[] pixels;

			trans.OutputFile(dst);
//			wxRemoveFile(src);
		}
	}
	else if (fmt == "etc1")
	{
		for (int i = begin; i < end; ++i)
		{
			std::string src = file + ee::StringHelper::ToString(i) + ".png";
			std::string dst = file + ee::StringHelper::ToString(i);

			int w, h, fmt;
			uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt);
// 			if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) {
// 				gimg_pre_mul_alpha(pixels, w, h);
// 			}

			int c = fmt == GPF_RGB ? 3 : 4;

			eimage::TransToETC1 trans(pixels, w, h, c, false, fast);
			delete[] pixels;

			trans.OutputFile(dst);
//			wxRemoveFile(src);
		}
	}
	else if (fmt == "etc2")
	{
		for (int i = begin; i < end; ++i)
		{
			std::string src = file + ee::StringHelper::ToString(i) + ".png";
			std::string dst = file + ee::StringHelper::ToString(i) + ".pkm";

			int w, h, fmt;
			uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt);
// 			if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) {
// 				gimg_pre_mul_alpha(pixels, w, h);
// 			}

			int c = fmt == GPF_RGB ? 3 : 4;

			eimage::TransToETC2 trans(pixels, w, h, c, eimage::TransToETC2::RGBA, false, fast);
			delete[] pixels;

			trans.OutputFile(dst);
//			wxRemoveFile(src);
		}
	}
}

etexpacker::ImageTrimData* PackTexture::PreparePackages(const std::string& str, std::vector<Package>& packages,
														std::string& src_dir, std::string& dst_file)
{
	Json::Value value;
	Json::Reader reader;
	reader.parse(str, value);

	src_dir = value["src"].asString();
	dst_file = value["dst"].asString();
	etexpacker::ImageTrimData* trim = NULL;
	if (!value["trim_file"].isNull()) {
		std::string trim_file = value["trim_file"].asString();
		trim = new etexpacker::ImageTrimData(trim_file);
	}

	const Json::Value& pkgs_val = value["packages"];
	for (int i = 0, n = pkgs_val.size(); i < n; ++i)
	{
		const Json::Value& v = pkgs_val[i];
		Package pkg;
		if (v["src"].isString()) {
			pkg.sources.push_back(v["src"].asString());
		} else {
			assert(v["src"].isArray());
			for (int i = 0, n = v["src"].size(); i < n; ++i) {
				pkg.sources.push_back(v["src"][i].asString());
			}
		}
		pkg.format = v["format"].asString();
		pkg.quality = v["quality"].asString();
		pkg.size_max = v["size_max"].asInt();
		pkg.size_min = v["size_min"].asInt();
		pkg.trim = trim;
		pkg.extrude_min = v["extrude_min"].asInt();
		pkg.extrude_max = v["extrude_max"].asInt();
		packages.push_back(pkg);
	}

	for (int i = 0, n = packages.size(); i < n; ++i) {
		Package& pkg0 = packages[i];
		if (pkg0.sources.size() == 1 && pkg0.sources[0] == "others")
		{
			for (int j = 0; j < n; ++j)
			{
				if (j == i) continue;
				const Package& pkg1 = packages[j];
				if (pkg1.sources.size() == 1 && pkg1.sources[0] == "others")  {
					continue;
				}
				for (int k = 0, m = pkg1.sources.size(); k < m; ++k) {
					const std::string& path = pkg1.sources[k];
					if (path != "others" && path != src_dir) {
						pkg0.ignores.push_back(path);
					}
				}
			}
			pkg0.sources[0] = src_dir;
		}
	}

	return trim;
}

void PackTexture::PackPackage(const Package& pkg, const std::string& src_dir,
							  const std::string& dst_file, int& start_id)
{
	std::vector<std::string> images;

	wxArrayString files;
	if (pkg.ignores.empty()) {
		for (int i = 0, n = pkg.sources.size(); i < n; ++i) {
			ee::FileHelper::FetchAllFiles(pkg.sources[i], files);
		}
	} else {
		for (int i = 0, n = pkg.sources.size(); i < n; ++i) {
			ee::FileHelper::FetchAllFiles(pkg.sources[i], pkg.ignores, files);
		}
	}
	for (int i = 0, n = files.size(); i < n; ++i) {
		if (ee::SymbolFile::Instance()->Type(files[i].ToStdString()) == s2::SYM_IMAGE) {
			std::string filepath = ee::FileHelper::FormatFilepathAbsolute(files[i].ToStdString());
			images.push_back(filepath);
		}
	}

	etexpacker::NormalPack tex_packer(images, pkg.trim, pkg.extrude_min, pkg.extrude_max, start_id);
	tex_packer.Pack(0, pkg.size_max, pkg.size_min);
	tex_packer.OutputInfo(src_dir, dst_file + ".json", pkg.format);
	tex_packer.OutputImage(dst_file + ".png");

	CompressPackedTex(tex_packer, start_id, dst_file, pkg.format, pkg.quality == "fastest");
}

}<|endoftext|>


<commit_before>#include <fstream>
#include <BGL.hh>
#include "testbed.h"

// Rectangle
BGL::Point pointSet1[] = {
    BGL::Point(-8.590003524884,  8.590000000000),
    BGL::Point(-8.590046474991, -8.590000000000),
    BGL::Point( 8.590000000000, -8.590000000000),
    BGL::Point( 8.590000000000,  8.590000000000),
    BGL::Point(-8.590003524884,  8.590000000000)
};

// Smaller Rectangle
BGL::Point pointSet2[] = {
    BGL::Point(-9.999997000000, 10.000000000000),
    BGL::Point(-9.849997000000, 10.000000000000),
    BGL::Point(-9.849997000000,  8.590000000000),
    BGL::Point(-9.999997000000,  8.590000000000),
    BGL::Point(-9.999997000000, 10.000000000000)
};

int main(int argc, char**argv)
{
    char fname[128];
    double infillInset=1.410000;

    BGL::Path path1(sizeof(pointSet1)/sizeof(BGL::Point), pointSet1);
    BGL::Path path2(sizeof(pointSet2)/sizeof(BGL::Point), pointSet2);

    fstream fout;
    BGL::SVG svg(250, 250);

    synthesize_testfile_name(fname, sizeof(fname), argv[0], "diff", "svg");
    fout.open(fname, fstream::out | fstream::trunc);
    if (fout.good()) {
	svg.header(fout);

	BGL::Paths outPaths;
	BGL::Path::differenceOf(path1, path2, outPaths);
	BGL::Paths::iterator it;

	fout << "<g stroke=\"#77f\">" << endl;
	path1 *= 3.0;
	path1.svgPathWithOffset(fout, 30, 30);
	fout << "</g>" << endl;

	fout << "<g stroke=\"#f77\">" << endl;
	path2 *= 3.0;
	path2.svgPathWithOffset(fout, 30, 30);
	fout << "</g>" << endl;

	for (it = outPaths.begin(); it != outPaths.end(); it++) {
	    *it *= 3.0;
	    it->svgPathWithOffset(fout, 30, 30);
	}

	svg.footer(fout);
	fout.sync();
	fout.close();
    }

    return 0;
}

<commit_msg>Removed unused variable.<commit_after>#include <fstream>
#include <BGL.hh>
#include "testbed.h"

// Rectangle
BGL::Point pointSet1[] = {
    BGL::Point(-8.590003524884,  8.590000000000),
    BGL::Point(-8.590046474991, -8.590000000000),
    BGL::Point( 8.590000000000, -8.590000000000),
    BGL::Point( 8.590000000000,  8.590000000000),
    BGL::Point(-8.590003524884,  8.590000000000)
};

// Smaller Rectangle
BGL::Point pointSet2[] = {
    BGL::Point(-9.999997000000, 10.000000000000),
    BGL::Point(-9.849997000000, 10.000000000000),
    BGL::Point(-9.849997000000,  8.590000000000),
    BGL::Point(-9.999997000000,  8.590000000000),
    BGL::Point(-9.999997000000, 10.000000000000)
};

int main(int argc, char**argv)
{
    char fname[128];

    BGL::Path path1(sizeof(pointSet1)/sizeof(BGL::Point), pointSet1);
    BGL::Path path2(sizeof(pointSet2)/sizeof(BGL::Point), pointSet2);

    fstream fout;
    BGL::SVG svg(250, 250);

    synthesize_testfile_name(fname, sizeof(fname), argv[0], "diff", "svg");
    fout.open(fname, fstream::out | fstream::trunc);
    if (fout.good()) {
	svg.header(fout);

	BGL::Paths outPaths;
	BGL::Path::differenceOf(path1, path2, outPaths);
	BGL::Paths::iterator it;

	fout << "<g stroke=\"#77f\">" << endl;
	path1 *= 3.0;
	path1.svgPathWithOffset(fout, 30, 30);
	fout << "</g>" << endl;

	fout << "<g stroke=\"#f77\">" << endl;
	path2 *= 3.0;
	path2.svgPathWithOffset(fout, 30, 30);
	fout << "</g>" << endl;

	for (it = outPaths.begin(); it != outPaths.end(); it++) {
	    *it *= 3.0;
	    it->svgPathWithOffset(fout, 30, 30);
	}

	svg.footer(fout);
	fout.sync();
	fout.close();
    }

    return 0;
}

<|endoftext|>


<commit_before><commit_msg>Increase simulation loop rate to 1 kHz<commit_after><|endoftext|>


<commit_before>#include "StatefulTimer.h"

#include "BackpropErrorsv2Cached.h"

using namespace std;

#undef STATIC
#define STATIC

#undef VIRTUAL
#define VIRTUAL

VIRTUAL BackpropErrorsv2Cached::~BackpropErrorsv2Cached() {
    delete kernel;
    delete applyActivationDeriv;
}
VIRTUAL void BackpropErrorsv2Cached::backpropErrors( int batchSize,
        CLWrapper *inputDataWrapper, CLWrapper *errorsWrapper, CLWrapper *weightsWrapper,
        CLWrapper *errorsForUpstreamWrapper ) {
    StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached start" );

//        const int batchSize,
//        global const float *errorsGlobal,
//        global const float *filtersGlobal,
//        global float *errorsForUpstream,
//        local float *_errorBoard,
//        local float *_filterBoard ) {

    kernel
       ->in( batchSize )
        ->in( errorsWrapper )
       ->in( weightsWrapper )
        ->out( errorsForUpstreamWrapper )
        ->localFloats( square( dim.outputBoardSize ) )
        ->localFloats( square( dim.filterSize ) );

    int numWorkgroups = batchSize * dim.inputPlanes;
    int workgroupSize = square( dim.inputBoardSize );
    workgroupSize = std::max( 32, workgroupSize ); // no point in wasting cores...
    int globalSize = numWorkgroups * workgroupSize;

//    int globalSize = batchSize * dim.inputCubeSize;
//    int workgroupsize = cl->getMaxWorkgroupSize();
//    globalSize = ( ( globalSize + workgroupsize - 1 ) / workgroupsize ) * workgroupsize;
//    kernel->run_1d(globalSize, workgroupsize);

    float const*errorsForUpstream = (float *)errorsForUpstreamWrapper->getHostArray();
    kernel->run_1d(globalSize, workgroupSize);
    cl->finish();
    errorsForUpstreamWrapper->copyToHost();
    StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after first kernel" );
    for( int i = 0; i < min( 40, batchSize * dim.inputCubeSize ); i++ ) {
        cout << "efu[" << i << "]=" << errorsForUpstream[i] << endl;
    }

//    applyActivationDeriv->in( batchSize * dim.inputCubeSize )->in( errorsForUpstreamWrapper )->in( inputDataWrapper );
//    applyActivationDeriv->run_1d(globalSize, workgroupSize);
    applyActivationDeriv->in( batchSize * dim.inputCubeSize )->in( errorsForUpstreamWrapper )->in( inputDataWrapper );
    applyActivationDeriv->run_1d(globalSize, workgroupSize);
    cl->finish();
    StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after applyActivationDeriv" );
    errorsForUpstreamWrapper->copyToHost();
    for( int i = 0; i < min( 40, batchSize * dim.inputCubeSize ); i++ ) {
        cout << "efu2[" << i << "]=" << errorsForUpstream[i] << endl;
    }

    StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached end" );
}
BackpropErrorsv2Cached::BackpropErrorsv2Cached( OpenCLHelper *cl, LayerDimensions dim, ActivationFunction const *upstreamFn ) :
        BackpropErrorsv2( cl, dim, upstreamFn )
            {
    std::string options = dim.buildOptionsString();
    options += " -D " + upstreamFn->getDefineName();
    // [[[cog
    // import stringify
    // stringify.write_kernel2( "kernel", "cl/backproperrorsv2cached.cl", "calcErrorsForUpstreamCached", 'options' )
    // # stringify.write_kernel2( "broadcastMultiply", "cl/backproperrorsv2.cl", "broadcast_multiply", 'options' )
    // stringify.write_kernel2( "applyActivationDeriv", "cl/applyActivationDeriv.cl", "applyActivationDeriv", 'options' )
    // # stringify.write_kernel( "kernelSource", "ClConvolve.cl")
    // ]]]
    // generated using cog:
    const char * kernelSource =
    "// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail\n"
    "//\n"
    "// This Source Code Form is subject to the terms of the Mozilla Public License,\n"
    "// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n"
    "// obtain one at http://mozilla.org/MPL/2.0/.\n"
    "\n"
    "// as calcErrorsForUpstream, but with local cache\n"
    "// convolve weights with errors to produce errorsForUpstream\n"
    "// workgroupid: [n][inputPlane]\n"
    "// localid: [upstreamrow][upstreamcol]\n"
    "// per-thread aggregation: [outPlane][filterRow][filterCol]\n"
    "// need to store locally:\n"
    "// - _errorBoard. size = outputBoardSizeSquared\n"
    "// - _filterBoard. size = filtersizesquared\n"
    "// note: currently doesnt use bias as input.  thats probably an error?\n"
    "// inputs: errors :convolve: filters => errorsForUpstream\n"
    "//\n"
    "// global:\n"
    "// errors: [n][outPlane][outRow][outCol] 128 * 32 * 19 * 19 * 4\n"
    "// weights: [filterId][upstreamplane][filterRow][filterCol] 32 * 32 * 5 * 5 * 4\n"
    "// per workgroup:\n"
    "// errors: [outPlane][outRow][outCol] 32 * 19 * 19 * 4 = 46KB\n"
    "// weights: [filterId][filterRow][filterCol] 32 * 5 * 5 * 4 = 3.2KB\n"
    "// errorsforupstream: [n][upstreamPlane][upstreamRow][upstreamCol]\n"
    "void kernel calcErrorsForUpstreamCached(\n"
    "        const int batchSize,\n"
    "        global const float *errorsGlobal,\n"
    "        global const float *filtersGlobal,\n"
    "        global float *errorsForUpstream,\n"
    "        local float *_errorBoard,\n"
    "        local float *_filterBoard ) {\n"
    "\n"
    "    const int globalId = get_global_id(0);\n"
    "    const int localId = get_local_id(0);\n"
    "    const int workgroupId = get_group_id(0);\n"
    "    const int workgroupSize = get_local_size(0);\n"
    "\n"
    "    const int n = workgroupId / gInputPlanes;\n"
    "    const int upstreamPlane = workgroupId % gInputPlanes;\n"
    "\n"
    "    const int upstreamRow = localId / gInputBoardSize;\n"
    "    const int upstreamCol = localId % gInputBoardSize;\n"
    "\n"
    "    const int minFilterRow = max( 0, upstreamRow + gMargin - (gOutputBoardSize - 1) );\n"
    "    const int maxFilterRow = min( gFilterSize - 1, upstreamRow + gMargin );\n"
    "    const int minFilterCol = max( 0, upstreamCol + gMargin - (gOutputBoardSize -1) );\n"
    "    const int maxFilterCol = min( gFilterSize - 1, upstreamCol + gMargin );\n"
    "\n"
    "    const int filterPixelCopiesPerThread = ( gFilterSizeSquared + workgroupSize - 1 ) / workgroupSize;\n"
    "    const int errorPixelCopiesPerThread = ( gOutputBoardSizeSquared + workgroupSize - 1 ) / workgroupSize;\n"
    "    const int pixelCopiesPerThread = max( filterPixelCopiesPerThread, errorPixelCopiesPerThread );\n"
    "\n"
    "    float sumWeightTimesOutError = 0;\n"
    "    for( int outPlane = 0; outPlane < gNumFilters; outPlane++ ) {\n"
    "        const int filterBoardGlobalOffset =( outPlane * gInputPlanes + upstreamPlane ) * gFilterSizeSquared;\n"
    "        const int errorBoardGlobalOffset = ( n * gNumFilters + outPlane ) * gOutputBoardSizeSquared;\n"
    "        barrier(CLK_LOCAL_MEM_FENCE);\n"
    "        for( int i = 0; i < pixelCopiesPerThread; i++ ) {\n"
    "            int thisOffset = workgroupSize * i + localId;\n"
    "            if( thisOffset < gFilterSizeSquared ) {\n"
    "                _filterBoard[ thisOffset ] = filtersGlobal[ filterBoardGlobalOffset + thisOffset ];\n"
    "            }\n"
    "            if( thisOffset < gOutputBoardSizeSquared ) {\n"
    "                _errorBoard[ thisOffset ] = errorsGlobal[ errorBoardGlobalOffset + thisOffset ];\n"
    "            }\n"
    "        }\n"
    "        barrier(CLK_LOCAL_MEM_FENCE);\n"
    "//        if( globalId == 0 ) {\n"
    "//            for( int i = 0; i < gFilterSizeSquared; i++ ) {\n"
    "//                errorsForUpstream[ (outPlane+1)*100 + i ] = _filterBoard[i];\n"
    "//            }\n"
    "//        }\n"
    "        for( int filterRow = minFilterRow; filterRow <= maxFilterRow; filterRow++ ) {\n"
    "            int outRow = upstreamRow + gMargin - filterRow;\n"
    "            for( int filterCol = minFilterCol; filterCol <= maxFilterCol; filterCol++ ) {\n"
    "                int outCol = upstreamCol + gMargin - filterCol;\n"
    "                int resultIndex = outRow * gOutputBoardSize + outCol;\n"
    "                float thisError = _errorBoard[resultIndex];\n"
    "                int thisWeightIndex = filterRow * gFilterSize + filterCol;\n"
    "                float thisWeight = _filterBoard[thisWeightIndex];\n"
    "                float thisWeightTimesError = thisWeight * thisError;\n"
    "                sumWeightTimesOutError += thisWeightTimesError;\n"
    "            }\n"
    "        }\n"
    "    }\n"
    "    const int upstreamBoardGlobalOffset = ( n * gInputPlanes + upstreamPlane ) * gInputBoardSizeSquared;\n"
    "    if( localId < gInputBoardSizeSquared ) {\n"
    "        errorsForUpstream[upstreamBoardGlobalOffset + localId] = sumWeightTimesOutError;\n"
    "    }\n"
    "}\n"
    "\n"
    "";
    kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstreamCached", options, "cl/backproperrorsv2cached.cl" );
    // generated using cog:
    const char * applyActivationDerivSource =
    "// Copyright Hugh Perkins 201, 2015 hughperkins at gmail\n"
    "//\n"
    "// This Source Code Form is subject to the terms of the Mozilla Public License,\n"
    "// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n"
    "// obtain one at http://mozilla.org/MPL/2.0/.\n"
    "\n"
    "// expected defines:\n"
    "// one of: [ TANH | RELU | LINEAR | SIGMOID | SCALEDTANH ]\n"
    "\n"
    "#ifdef TANH\n"
    "    #define ACTIVATION_DERIV(output) (1 - output * output)\n"
    "#elif defined SCALEDTANH\n"
    "    #define ACTIVATION_DERIV(output) ( 0.66667f * ( 1.7159f - 1 / 1.7159f * output * output ) )\n"
    "#elif defined SIGMOID\n"
    "    #define ACTIVATION_DERIV(output) (output * ( 1 - output ) )\n"
    "#elif defined RELU\n"
    "    #define ACTIVATION_DERIV(output) (output > 0 ? 1 : 0)\n"
    "#elif defined LINEAR\n"
    "    #define ACTIVATION_DERIV(output) (1.0f)\n"
    "#endif\n"
    "\n"
    "//#ifdef ACTIVATION_DERIV\n"
    "//void kernel applyActivationDeriv(\n"
    "//        const int N,\n"
    "//        global float *inout ) {\n"
    "//    int globalId = get_global_id(0);\n"
    "//    inout[globalId] = ACTIVATION_DERIV( inout[globalId] );\n"
    "//}\n"
    "//#endif\n"
    "\n"
    "#ifdef ACTIVATION_DERIV\n"
    "void kernel applyActivationDeriv(\n"
    "        const int N,\n"
    "        global float *target, global const float *source ) {\n"
    "    int globalId = get_global_id(0);\n"
    "    target[globalId] *= ACTIVATION_DERIV( source[globalId] );\n"
    "  //  target[globalId] *= source[globalId];\n"
    "}\n"
    "#endif\n"
    "\n"
    "";
    applyActivationDeriv = cl->buildKernelFromString( applyActivationDerivSource, "applyActivationDeriv", options, "cl/applyActivationDeriv.cl" );
    // [[[end]]]
//    kernel = cl->buildKernel( "backproperrorsv2.cl", "calcErrorsForUpstream", options );
//    kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstream", options );
}

<commit_msg>change in to inout<commit_after>#include "StatefulTimer.h"

#include "BackpropErrorsv2Cached.h"

using namespace std;

#undef STATIC
#define STATIC

#undef VIRTUAL
#define VIRTUAL

VIRTUAL BackpropErrorsv2Cached::~BackpropErrorsv2Cached() {
    delete kernel;
    delete applyActivationDeriv;
}
VIRTUAL void BackpropErrorsv2Cached::backpropErrors( int batchSize,
        CLWrapper *inputDataWrapper, CLWrapper *errorsWrapper, CLWrapper *weightsWrapper,
        CLWrapper *errorsForUpstreamWrapper ) {
    StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached start" );

//        const int batchSize,
//        global const float *errorsGlobal,
//        global const float *filtersGlobal,
//        global float *errorsForUpstream,
//        local float *_errorBoard,
//        local float *_filterBoard ) {

    kernel
       ->in( batchSize )
        ->in( errorsWrapper )
       ->in( weightsWrapper )
        ->out( errorsForUpstreamWrapper )
        ->localFloats( square( dim.outputBoardSize ) )
        ->localFloats( square( dim.filterSize ) );

    int numWorkgroups = batchSize * dim.inputPlanes;
    int workgroupSize = square( dim.inputBoardSize );
    workgroupSize = std::max( 32, workgroupSize ); // no point in wasting cores...
    int globalSize = numWorkgroups * workgroupSize;

//    int globalSize = batchSize * dim.inputCubeSize;
//    int workgroupsize = cl->getMaxWorkgroupSize();
//    globalSize = ( ( globalSize + workgroupsize - 1 ) / workgroupsize ) * workgroupsize;
//    kernel->run_1d(globalSize, workgroupsize);

    float const*errorsForUpstream = (float *)errorsForUpstreamWrapper->getHostArray();
    kernel->run_1d(globalSize, workgroupSize);
    cl->finish();
    errorsForUpstreamWrapper->copyToHost();
    StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after first kernel" );
    for( int i = 0; i < min( 40, batchSize * dim.inputCubeSize ); i++ ) {
        cout << "efu[" << i << "]=" << errorsForUpstream[i] << endl;
    }

//    applyActivationDeriv->in( batchSize * dim.inputCubeSize )->in( errorsForUpstreamWrapper )->in( inputDataWrapper );
//    applyActivationDeriv->run_1d(globalSize, workgroupSize);
    applyActivationDeriv->in( batchSize * dim.inputCubeSize )->inout( errorsForUpstreamWrapper )->in( inputDataWrapper );
    applyActivationDeriv->run_1d(globalSize, workgroupSize);
    cl->finish();
    StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after applyActivationDeriv" );
    errorsForUpstreamWrapper->copyToHost();
    for( int i = 0; i < min( 40, batchSize * dim.inputCubeSize ); i++ ) {
        cout << "efu2[" << i << "]=" << errorsForUpstream[i] << endl;
    }

    StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached end" );
}
BackpropErrorsv2Cached::BackpropErrorsv2Cached( OpenCLHelper *cl, LayerDimensions dim, ActivationFunction const *upstreamFn ) :
        BackpropErrorsv2( cl, dim, upstreamFn )
            {
    std::string options = dim.buildOptionsString();
    options += " -D " + upstreamFn->getDefineName();
    // [[[cog
    // import stringify
    // stringify.write_kernel2( "kernel", "cl/backproperrorsv2cached.cl", "calcErrorsForUpstreamCached", 'options' )
    // # stringify.write_kernel2( "broadcastMultiply", "cl/backproperrorsv2.cl", "broadcast_multiply", 'options' )
    // stringify.write_kernel2( "applyActivationDeriv", "cl/applyActivationDeriv.cl", "applyActivationDeriv", 'options' )
    // # stringify.write_kernel( "kernelSource", "ClConvolve.cl")
    // ]]]
    // generated using cog:
    const char * kernelSource =
    "// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail\n"
    "//\n"
    "// This Source Code Form is subject to the terms of the Mozilla Public License,\n"
    "// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n"
    "// obtain one at http://mozilla.org/MPL/2.0/.\n"
    "\n"
    "// as calcErrorsForUpstream, but with local cache\n"
    "// convolve weights with errors to produce errorsForUpstream\n"
    "// workgroupid: [n][inputPlane]\n"
    "// localid: [upstreamrow][upstreamcol]\n"
    "// per-thread aggregation: [outPlane][filterRow][filterCol]\n"
    "// need to store locally:\n"
    "// - _errorBoard. size = outputBoardSizeSquared\n"
    "// - _filterBoard. size = filtersizesquared\n"
    "// note: currently doesnt use bias as input.  thats probably an error?\n"
    "// inputs: errors :convolve: filters => errorsForUpstream\n"
    "//\n"
    "// global:\n"
    "// errors: [n][outPlane][outRow][outCol] 128 * 32 * 19 * 19 * 4\n"
    "// weights: [filterId][upstreamplane][filterRow][filterCol] 32 * 32 * 5 * 5 * 4\n"
    "// per workgroup:\n"
    "// errors: [outPlane][outRow][outCol] 32 * 19 * 19 * 4 = 46KB\n"
    "// weights: [filterId][filterRow][filterCol] 32 * 5 * 5 * 4 = 3.2KB\n"
    "// errorsforupstream: [n][upstreamPlane][upstreamRow][upstreamCol]\n"
    "void kernel calcErrorsForUpstreamCached(\n"
    "        const int batchSize,\n"
    "        global const float *errorsGlobal,\n"
    "        global const float *filtersGlobal,\n"
    "        global float *errorsForUpstream,\n"
    "        local float *_errorBoard,\n"
    "        local float *_filterBoard ) {\n"
    "\n"
    "    const int globalId = get_global_id(0);\n"
    "    const int localId = get_local_id(0);\n"
    "    const int workgroupId = get_group_id(0);\n"
    "    const int workgroupSize = get_local_size(0);\n"
    "\n"
    "    const int n = workgroupId / gInputPlanes;\n"
    "    const int upstreamPlane = workgroupId % gInputPlanes;\n"
    "\n"
    "    const int upstreamRow = localId / gInputBoardSize;\n"
    "    const int upstreamCol = localId % gInputBoardSize;\n"
    "\n"
    "    const int minFilterRow = max( 0, upstreamRow + gMargin - (gOutputBoardSize - 1) );\n"
    "    const int maxFilterRow = min( gFilterSize - 1, upstreamRow + gMargin );\n"
    "    const int minFilterCol = max( 0, upstreamCol + gMargin - (gOutputBoardSize -1) );\n"
    "    const int maxFilterCol = min( gFilterSize - 1, upstreamCol + gMargin );\n"
    "\n"
    "    const int filterPixelCopiesPerThread = ( gFilterSizeSquared + workgroupSize - 1 ) / workgroupSize;\n"
    "    const int errorPixelCopiesPerThread = ( gOutputBoardSizeSquared + workgroupSize - 1 ) / workgroupSize;\n"
    "    const int pixelCopiesPerThread = max( filterPixelCopiesPerThread, errorPixelCopiesPerThread );\n"
    "\n"
    "    float sumWeightTimesOutError = 0;\n"
    "    for( int outPlane = 0; outPlane < gNumFilters; outPlane++ ) {\n"
    "        const int filterBoardGlobalOffset =( outPlane * gInputPlanes + upstreamPlane ) * gFilterSizeSquared;\n"
    "        const int errorBoardGlobalOffset = ( n * gNumFilters + outPlane ) * gOutputBoardSizeSquared;\n"
    "        barrier(CLK_LOCAL_MEM_FENCE);\n"
    "        for( int i = 0; i < pixelCopiesPerThread; i++ ) {\n"
    "            int thisOffset = workgroupSize * i + localId;\n"
    "            if( thisOffset < gFilterSizeSquared ) {\n"
    "                _filterBoard[ thisOffset ] = filtersGlobal[ filterBoardGlobalOffset + thisOffset ];\n"
    "            }\n"
    "            if( thisOffset < gOutputBoardSizeSquared ) {\n"
    "                _errorBoard[ thisOffset ] = errorsGlobal[ errorBoardGlobalOffset + thisOffset ];\n"
    "            }\n"
    "        }\n"
    "        barrier(CLK_LOCAL_MEM_FENCE);\n"
    "//        if( globalId == 0 ) {\n"
    "//            for( int i = 0; i < gFilterSizeSquared; i++ ) {\n"
    "//                errorsForUpstream[ (outPlane+1)*100 + i ] = _filterBoard[i];\n"
    "//            }\n"
    "//        }\n"
    "        for( int filterRow = minFilterRow; filterRow <= maxFilterRow; filterRow++ ) {\n"
    "            int outRow = upstreamRow + gMargin - filterRow;\n"
    "            for( int filterCol = minFilterCol; filterCol <= maxFilterCol; filterCol++ ) {\n"
    "                int outCol = upstreamCol + gMargin - filterCol;\n"
    "                int resultIndex = outRow * gOutputBoardSize + outCol;\n"
    "                float thisError = _errorBoard[resultIndex];\n"
    "                int thisWeightIndex = filterRow * gFilterSize + filterCol;\n"
    "                float thisWeight = _filterBoard[thisWeightIndex];\n"
    "                float thisWeightTimesError = thisWeight * thisError;\n"
    "                sumWeightTimesOutError += thisWeightTimesError;\n"
    "            }\n"
    "        }\n"
    "    }\n"
    "    const int upstreamBoardGlobalOffset = ( n * gInputPlanes + upstreamPlane ) * gInputBoardSizeSquared;\n"
    "    if( localId < gInputBoardSizeSquared ) {\n"
    "        errorsForUpstream[upstreamBoardGlobalOffset + localId] = sumWeightTimesOutError;\n"
    "    }\n"
    "}\n"
    "\n"
    "";
    kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstreamCached", options, "cl/backproperrorsv2cached.cl" );
    // generated using cog:
    const char * applyActivationDerivSource =
    "// Copyright Hugh Perkins 201, 2015 hughperkins at gmail\n"
    "//\n"
    "// This Source Code Form is subject to the terms of the Mozilla Public License,\n"
    "// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n"
    "// obtain one at http://mozilla.org/MPL/2.0/.\n"
    "\n"
    "// expected defines:\n"
    "// one of: [ TANH | RELU | LINEAR | SIGMOID | SCALEDTANH ]\n"
    "\n"
    "#ifdef TANH\n"
    "    #define ACTIVATION_DERIV(output) (1 - output * output)\n"
    "#elif defined SCALEDTANH\n"
    "    #define ACTIVATION_DERIV(output) ( 0.66667f * ( 1.7159f - 1 / 1.7159f * output * output ) )\n"
    "#elif defined SIGMOID\n"
    "    #define ACTIVATION_DERIV(output) (output * ( 1 - output ) )\n"
    "#elif defined RELU\n"
    "    #define ACTIVATION_DERIV(output) (output > 0 ? 1 : 0)\n"
    "#elif defined LINEAR\n"
    "    #define ACTIVATION_DERIV(output) (1.0f)\n"
    "#endif\n"
    "\n"
    "//#ifdef ACTIVATION_DERIV\n"
    "//void kernel applyActivationDeriv(\n"
    "//        const int N,\n"
    "//        global float *inout ) {\n"
    "//    int globalId = get_global_id(0);\n"
    "//    inout[globalId] = ACTIVATION_DERIV( inout[globalId] );\n"
    "//}\n"
    "//#endif\n"
    "\n"
    "#ifdef ACTIVATION_DERIV\n"
    "void kernel applyActivationDeriv(\n"
    "        const int N,\n"
    "        global float *target, global const float *source ) {\n"
    "    int globalId = get_global_id(0);\n"
    "    target[globalId] *= ACTIVATION_DERIV( source[globalId] );\n"
    "  //  target[globalId] *= source[globalId];\n"
    "}\n"
    "#endif\n"
    "\n"
    "";
    applyActivationDeriv = cl->buildKernelFromString( applyActivationDerivSource, "applyActivationDeriv", options, "cl/applyActivationDeriv.cl" );
    // [[[end]]]
//    kernel = cl->buildKernel( "backproperrorsv2.cl", "calcErrorsForUpstream", options );
//    kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstream", options );
}

<|endoftext|>


<commit_before>#include <iostream>
#include <mutex>
#include <highgui.h>
#include <Camera/ClickIndexTaker.h>

namespace Camera{
  ClickIndexTaker::ClickIndexTaker(const Image& data)
    :
      _data(data)
  {
    updateCoords(0,0);
  }

  void ClickIndexTaker::updateCoords(int row, int column){
    cv::namedWindow("Choose two points..", cv::WINDOW_AUTOSIZE);
    cv::imshow("Choose two points..", _data.rgb);
    cv::Mat sblargaba=cv::imread("/home/simo/kinectData/rgb.png");
    cv::namedWindow("mySister", cv::WINDOW_AUTOSIZE);;
    cv::imshow("mySister", sblargaba);
    cv::waitKey(1);

    std::array<std::mutex, 2>  clicks;
    clicks[0].lock();
    clicks[1].lock();
    std::array<int, 2> xc, yc;

    int count=0;

    /*** WE NEED THIS TO CAST THE FUNCTION TO A POINTER (PASSING CONTEXT) **/
    struct parameterToCallback{
      std::array<std::mutex, 2>*  clicks;
      std::array<int, 2>* xc;
      std::array<int, 2>* yc;
      int *count;
    };
    parameterToCallback theParameter({&clicks, &xc, &yc, &count});

    cv::setMouseCallback("Choose two points..",
        [] (int event, int x, int y, int flags, void* stafava) -> void {
          parameterToCallback* par=static_cast<parameterToCallback*> (stafava);
          auto clicks=par->clicks;
          auto xc=par->xc;
          auto yc=par->yc;
          auto count=par->count;

          if(event==CV_EVENT_LBUTTONDOWN){
            std::cout << "Click.\nCount="<<*count <<"\n";
            if((*count)<2){
              std::cout << "Unlocking mutex #" << *count << "..\n";
              (*clicks)[*count].unlock();
              (*xc)[*count]=x;
              (*yc)[*count]=y;
              (*count)++;
            }
          }
        }
        , &theParameter);

    std::cout << "Click for first point..\n";
    while(!clicks[0].try_lock()){
      cv::waitKey(100);
    }
    std::cout << "Click for second point..\n";
    while(!clicks[1].try_lock()){
      cv::waitKey(100);
    }
    std::cout << "Thanks. Points: (" << xc[0] << "," << yc[0] << ") and (" << xc[1] << "," << yc[1] << ")\n";
    _x1=xc[0];
    _x2=xc[1];
    _y1=yc[0];
    _y2=yc[1];
    cv::destroyWindow("Choose two points..");
  }
}
<commit_msg>Remove debug stuff<commit_after>#include <iostream>
#include <mutex>
#include <highgui.h>
#include <Camera/ClickIndexTaker.h>

namespace Camera{
  ClickIndexTaker::ClickIndexTaker(const Image& data)
    :
      _data(data)
  {
    updateCoords(0,0);
  }

  void ClickIndexTaker::updateCoords(int row, int column){
    cv::namedWindow("Choose two points..", cv::WINDOW_AUTOSIZE);
    cv::imshow("Choose two points..", _data.rgb);
    cv::waitKey(1);

    std::array<std::mutex, 2>  clicks;
    clicks[0].lock();
    clicks[1].lock();
    std::array<int, 2> xc, yc;

    int count=0;

    /*** WE NEED THIS TO CAST THE FUNCTION TO A POINTER (PASSING CONTEXT) **/
    struct parameterToCallback{
      std::array<std::mutex, 2>*  clicks;
      std::array<int, 2>* xc;
      std::array<int, 2>* yc;
      int *count;
    };
    parameterToCallback theParameter({&clicks, &xc, &yc, &count});

    cv::setMouseCallback("Choose two points..",
        [] (int event, int x, int y, int flags, void* stafava) -> void {
          parameterToCallback* par=static_cast<parameterToCallback*> (stafava);
          auto clicks=par->clicks;
          auto xc=par->xc;
          auto yc=par->yc;
          auto count=par->count;

          if(event==CV_EVENT_LBUTTONDOWN){
            std::cout << "Click.\nCount="<<*count <<"\n";
            if((*count)<2){
              std::cout << "Unlocking mutex #" << *count << "..\n";
              (*clicks)[*count].unlock();
              (*xc)[*count]=x;
              (*yc)[*count]=y;
              (*count)++;
            }
          }
        }
        , &theParameter);

    std::cout << "Click for first point..\n";
    while(!clicks[0].try_lock()){
      cv::waitKey(100);
    }
    std::cout << "Click for second point..\n";
    while(!clicks[1].try_lock()){
      cv::waitKey(100);
    }
    std::cout << "Thanks. Points: (" << xc[0] << "," << yc[0] << ") and (" << xc[1] << "," << yc[1] << ")\n";
    _x1=xc[0];
    _x2=xc[1];
    _y1=yc[0];
    _y2=yc[1];
    cv::destroyWindow("Choose two points..");
  }
}
<|endoftext|>


<commit_before>namespace mant {
  namespace bbob {
    class EllipsoidalFunctionRotated : public BlackBoxOptimisationBenchmark {
      public:
        inline explicit EllipsoidalFunctionRotated(
            const unsigned int numberOfDimensions) noexcept;

        inline std::string toString() const noexcept override;

      protected:
        const arma::Col<double> parameterConditoning_;

        inline double getObjectiveValueImplementation(
            const arma::Col<double>& parameter) const noexcept override;

#if defined(MANTELLA_USE_PARALLEL)
        friend class cereal::access;

        template <typename Archive>
        void serialize(
            Archive& archive) noexcept {
          archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(this)));
          archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_));
        }

        template <typename Archive>
        static void load_and_construct(
            Archive& archive,
            cereal::construct<EllipsoidalFunctionRotated>& construct) noexcept {
          unsigned int numberOfDimensions;
          archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions));
          construct(numberOfDimensions);

          archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(construct.ptr())));
        }
#endif
    };

    //
    // Implementation
    //

    inline EllipsoidalFunctionRotated::EllipsoidalFunctionRotated(
        const unsigned int numberOfDimensions) noexcept
      : BlackBoxOptimisationBenchmark(numberOfDimensions),
        parameterConditoning_(getParameterConditioning(1000000.0)) {
      setParameterTranslation(getRandomParameterTranslation());
      setParameterRotation(getRandomRotationMatrix(numberOfDimensions_));
    }

    inline double EllipsoidalFunctionRotated::getObjectiveValueImplementation(
        const arma::Col<double>& parameter) const noexcept {
      return arma::dot(parameterConditoning_, arma::square(getOscillatedParameter(parameter)));
    }

    inline std::string EllipsoidalFunctionRotated::toString() const noexcept {
      return "bbob_ellipsoidal_function_rotated";
    }
  }
}

#if defined(MANTELLA_USE_PARALLEL)
CEREAL_REGISTER_TYPE(mant::bbob::EllipsoidalFunctionRotated);
#endif
<commit_msg>Fixed minor spelling error (internal field name)<commit_after>namespace mant {
  namespace bbob {
    class EllipsoidalFunctionRotated : public BlackBoxOptimisationBenchmark {
      public:
        inline explicit EllipsoidalFunctionRotated(
            const unsigned int numberOfDimensions) noexcept;

        inline std::string toString() const noexcept override;

      protected:
        const arma::Col<double> parameterConditioning_;

        inline double getObjectiveValueImplementation(
            const arma::Col<double>& parameter) const noexcept override;

#if defined(MANTELLA_USE_PARALLEL)
        friend class cereal::access;

        template <typename Archive>
        void serialize(
            Archive& archive) noexcept {
          archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(this)));
          archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_));
        }

        template <typename Archive>
        static void load_and_construct(
            Archive& archive,
            cereal::construct<EllipsoidalFunctionRotated>& construct) noexcept {
          unsigned int numberOfDimensions;
          archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions));
          construct(numberOfDimensions);

          archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(construct.ptr())));
        }
#endif
    };

    //
    // Implementation
    //

    inline EllipsoidalFunctionRotated::EllipsoidalFunctionRotated(
        const unsigned int numberOfDimensions) noexcept
      : BlackBoxOptimisationBenchmark(numberOfDimensions),
        parameterConditioning_(getParameterConditioning(1000000.0)) {
      setParameterTranslation(getRandomParameterTranslation());
      setParameterRotation(getRandomRotationMatrix(numberOfDimensions_));
    }

    inline double EllipsoidalFunctionRotated::getObjectiveValueImplementation(
        const arma::Col<double>& parameter) const noexcept {
      return arma::dot(parameterConditioning_, arma::square(getOscillatedParameter(parameter)));
    }

    inline std::string EllipsoidalFunctionRotated::toString() const noexcept {
      return "bbob_ellipsoidal_function_rotated";
    }
  }
}

#if defined(MANTELLA_USE_PARALLEL)
CEREAL_REGISTER_TYPE(mant::bbob::EllipsoidalFunctionRotated);
#endif
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <visionaray/math/math.h>

#include <gtest/gtest.h>

using namespace visionaray;

TEST(Vector, Ctor)
{
    // Test constructability from vectors with different
    // sizes to define a higher-dimensional vector

    vector<3, float> v3(1.0f, 2.0f, 3.0f);
    vector<2, float> v2(4.0f, 5.0f);
    vector<5, float> v5(v3, v2);
    EXPECT_FLOAT_EQ(v5[0], 1.0f);
    EXPECT_FLOAT_EQ(v5[1], 2.0f);
    EXPECT_FLOAT_EQ(v5[2], 3.0f);
    EXPECT_FLOAT_EQ(v5[3], 4.0f);
    EXPECT_FLOAT_EQ(v5[4], 5.0f);

    // Test vec4 specialization of this ctor

    vector<4, float> v4(v2, vector<2, float>(6.0f, 7.0f));
    EXPECT_FLOAT_EQ(v4[0], 4.0f);
    EXPECT_FLOAT_EQ(v4[1], 5.0f);
    EXPECT_FLOAT_EQ(v4[2], 6.0f);
    EXPECT_FLOAT_EQ(v4[3], 7.0f);
}

TEST(Vector, MinMaxElement)
{
    // FPU

    vector<3, float> vf(1.0f, 2.0f, 3.0f);
    auto minef = min_element(vf);
    auto maxef = max_element(vf);
    EXPECT_FLOAT_EQ(minef, 1.0f);
    EXPECT_FLOAT_EQ(maxef, 3.0f);

    // SSE

    vector<3, simd::float4> v4(1.0f, 2.0f, 3.0f);
    auto mine4 = min_element(v4);
    auto maxe4 = max_element(v4);
    EXPECT_TRUE( all(mine4 == simd::float4(1.0f)) );
    EXPECT_TRUE( all(maxe4 == simd::float4(3.0f)) );

#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX

    // AVX

    vector<3, simd::float8> v8(1.0f, 2.0f, 3.0f);
    auto mine8 = min_element(v8);
    auto maxe8 = max_element(v8);
    EXPECT_TRUE( all(mine8 == simd::float8(1.0f)) );
    EXPECT_TRUE( all(maxe8 == simd::float8(3.0f)) );

#endif // VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX
}
<commit_msg>More unit tests for math vectors<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <visionaray/math/math.h>

#include <gtest/gtest.h>

using namespace visionaray;

TEST(Vector, Ctor)
{
    // Test constructability from vectors with different
    // sizes to define a higher-dimensional vector

    vector<3, float> v3(1.0f, 2.0f, 3.0f);
    vector<2, float> v2(4.0f, 5.0f);
    vector<5, float> v5(v3, v2);
    EXPECT_FLOAT_EQ(v5[0], 1.0f);
    EXPECT_FLOAT_EQ(v5[1], 2.0f);
    EXPECT_FLOAT_EQ(v5[2], 3.0f);
    EXPECT_FLOAT_EQ(v5[3], 4.0f);
    EXPECT_FLOAT_EQ(v5[4], 5.0f);

    // Test vec4 specialization of this ctor

    vector<4, float> v4(v2, vector<2, float>(6.0f, 7.0f));
    EXPECT_FLOAT_EQ(v4[0], 4.0f);
    EXPECT_FLOAT_EQ(v4[1], 5.0f);
    EXPECT_FLOAT_EQ(v4[2], 6.0f);
    EXPECT_FLOAT_EQ(v4[3], 7.0f);
}

TEST(Vector, Dot)
{
    // Test dot product for different vector sizes
    // (implementation may in general depend on size)

    vector<2, float> v2_1(1.0f, 2.0f);
    vector<2, float> v2_2(2.0f, 1.0f);
    EXPECT_FLOAT_EQ(dot(v2_1, v2_2), 4.0f);

    vector<3, float> v3_1(1.0f, 2.0f, 3.0f);
    vector<3, float> v3_2(3.0f, 2.0f, 1.0f);
    EXPECT_FLOAT_EQ(dot(v3_1, v3_2), 10.0f);

    vector<4, float> v4_1(1.0f, 2.0f, 3.0f, 4.0f);
    vector<4, float> v4_2(4.0f, 3.0f, 2.0f, 1.0f);
    EXPECT_FLOAT_EQ(dot(v4_1, v4_2), 20.0f);

    float f5_1[5] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };
    float f5_2[5] = { 5.0f, 4.0f, 3.0f, 2.0f, 1.0f };
    vector<5, float> v5_1(f5_1);
    vector<5, float> v5_2(f5_2);
    EXPECT_FLOAT_EQ(dot(v5_1, v5_2), 35.0f);

    float f6_1[6] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f };
    float f6_2[6] = { 6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f };
    vector<6, float> v6_1(f6_1);
    vector<6, float> v6_2(f6_2);
    EXPECT_FLOAT_EQ(dot(v6_1, v6_2), 56.0f);
}

TEST(Vector, MinMaxElement)
{
    // FPU

    vector<3, float> vf(1.0f, 2.0f, 3.0f);
    auto minef = min_element(vf);
    auto maxef = max_element(vf);
    EXPECT_FLOAT_EQ(minef, 1.0f);
    EXPECT_FLOAT_EQ(maxef, 3.0f);

    // SSE

    vector<3, simd::float4> v4(1.0f, 2.0f, 3.0f);
    auto mine4 = min_element(v4);
    auto maxe4 = max_element(v4);
    EXPECT_TRUE( all(mine4 == simd::float4(1.0f)) );
    EXPECT_TRUE( all(maxe4 == simd::float4(3.0f)) );

#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX

    // AVX

    vector<3, simd::float8> v8(1.0f, 2.0f, 3.0f);
    auto mine8 = min_element(v8);
    auto maxe8 = max_element(v8);
    EXPECT_TRUE( all(mine8 == simd::float8(1.0f)) );
    EXPECT_TRUE( all(maxe8 == simd::float8(3.0f)) );

#endif // VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX
}
<|endoftext|>