<commit_before>//
// AliGenEpos.cxx
//
//  ALICE event generator based on EPOS model from Klaus Werner
//
//  Created on: Feb 28, 2009
//      Author: Piotr Ostrowski, postrow@if.pw.edu.pl
//

#include "AliGenEpos.h"
#include "TEpos.h"
#include "TParticle.h"
#include "TMath.h"
#include "AliLog.h"
#include "AliGenEventHeader.h"
#include "AliGenEposEventHeader.h"

ClassImp(AliGenEpos)

AliGenEpos::AliGenEpos() : AliGenMC(),
		fBmin(0),
		fBmax(10000),
		fPhiMin(0),
		fPhiMax(TMath::TwoPi()),
		fFilterModelOutput(kFALSE) {
	SetMC(new TEpos());
}

AliGenEpos::AliGenEpos(Int_t npart) : AliGenMC(npart),
		fBmin(0),
		fBmax(10000),
		fPhiMin(0),
		fPhiMax(TMath::TwoPi()),
		fFilterModelOutput(kFALSE) {
	SetMC(new TEpos());
}

void AliGenEpos::Init() {
  // Sets up TEpos
	AliGenMC::Init();
	TEpos *epos = GetTEpos();
	epos->SetLaproj(this->fZProjectile);
	epos->SetMaproj(this->fAProjectile);
	epos->SetLatarg(this->fZTarget);
	epos->SetMatarg(this->fATarget);
	epos->SetPhimin(this->fPhiMin);
	epos->SetPhimax(this->fPhiMax);
	epos->SetBminim(this->fBmin);
	epos->SetBmaxim(this->fBmax);
	epos->SetEcms(this->fEnergyCMS);
	epos->SetSplitting(kTRUE);
	GetTEpos()->Initialize();
}

void AliGenEpos::Generate() {
  // Does actual generation and output conversion
	  Float_t polar[3]   =   {0,0,0};
	  Float_t origin0[3]  =   {0,0,0};
	  Float_t origin[3]   =   {0,0,0};
	  fNprimaries = 0;
	  Int_t nt  = 0; //output parameter for PushTrack

	  Vertex();
	  for (int j=0; j < 3; j++) origin0[j] = fVertex[j];

	  // Generate one event

	  GetTEpos()->GenerateEvent();
	  AliWarning("Generated");
	  GetTEpos()->ImportParticles(&fParticles);

	  Int_t np = fParticles.GetEntriesFast();
	  AliWarning(Form("Imported %d particles", np));

	  Int_t *idsOnStack = NULL;
	  idsOnStack = new Int_t[np];
	  TParticle *iparticle;

	  for (int i = 0; i < np; i++) {
		  iparticle = (TParticle *) fParticles.At(i);
		  //Bool_t isNullEntry = iparticle->GetStatusCode() == 0;
		  //Bool_t isCommentOrUnknown = iparticle->GetStatusCode() > 2;
		  Bool_t hasDecayed = iparticle->GetStatusCode() >= 2;
		  Bool_t isFinalState = iparticle->GetStatusCode() == 1;
		  Int_t imo = iparticle->GetFirstMother();
		  Bool_t  hasMother = (imo >=0);

		  if (isFinalState) {
			  origin[0] = iparticle->Vx();
			  origin[1] = iparticle->Vy();
			  origin[2] = iparticle->Vz();
			  //doubled track with freeze out coordinates for femtoscopy
			  PushTrack(0,
					  imo>=0?idsOnStack[imo]:-1,
					  iparticle->GetPdgCode(),
				iparticle->Px(),iparticle->Py(),iparticle->Pz(),iparticle->Energy(),
				origin[0], origin[1], origin[2],
				iparticle->T(),
				polar[0],polar[1],polar[2],
				hasMother ? kPDecay:kPNoProcess,nt);

		      idsOnStack[i] = nt;
		      fNprimaries++;
		      KeepTrack(nt);

		      //real track with smeared vertex
		      origin[0] += origin0[0];
		      origin[1] += origin0[1];
		      origin[2] += origin0[2];
			  PushTrack(1,
					  nt,   //doubled track as mother
					  iparticle->GetPdgCode(),
				iparticle->Px(),iparticle->Py(),iparticle->Pz(),iparticle->Energy(),
				origin[0], origin[1], origin[2],
				iparticle->T(),
				polar[0],polar[1],polar[2],
				kPDecay,nt);
		      fNprimaries++;
		      KeepTrack(nt);
		  } else if(hasDecayed || !fFilterModelOutput) {
			  // don't track it and don't smear vertex
			  origin[0] = iparticle->Vx();
			  origin[1] = iparticle->Vy();
			  origin[2] = iparticle->Vz();
			  PushTrack(0,
					  imo>=0?idsOnStack[imo]:-1,
					  iparticle->GetPdgCode(),
				iparticle->Px(),iparticle->Py(),iparticle->Pz(),iparticle->Energy(),
				origin[0], origin[1], origin[2],
				iparticle->T(),
				polar[0],polar[1],polar[2],
				hasMother ? kPDecay:kPNoProcess,nt);
		      idsOnStack[i] = nt;
		      fNprimaries++;
		      KeepTrack(nt);
		  } else if(fFilterModelOutput) {
			  //filtered internal model objects
			  idsOnStack[i] = -1; // to erase mother field in its dauthers
		  }
	  }
	  SetHighWaterMark(fNprimaries);
	  TArrayF eventVertex;
	  eventVertex.Set(3);
	  eventVertex[0] = origin0[0];
	  eventVertex[1] = origin0[1];
	  eventVertex[2] = origin0[2];
	// Builds the event header, to be called after each event
	  AliGenEposEventHeader* header = new AliGenEposEventHeader("EPOS");

	  header->SetNProduced(fNprimaries);
	  header->SetPrimaryVertex(eventVertex);

	  header->SetImpactParameter(GetTEpos()->GetBimevt());
	  header->SetReactionPlaneAngle(GetTEpos()->GetPhievt());

	  header->SetHardScatters(0);
	  header->SetParticipants(GetTEpos()->GetNpjevt(), GetTEpos()->GetNtgevt());
	  header->SetCollisions(GetTEpos()->GetKolevt(), 0, 0, GetTEpos()->GetNpjevt());
	  header->SetSpectators(GetTEpos()->GetJpnevt(), GetTEpos()->GetJppevt(), GetTEpos()->GetJtnevt(), GetTEpos()->GetJtpevt());

	// Event Vertex
	  header->SetPrimaryVertex(fVertex);

	  header->SetBimevt(GetTEpos()->GetBimevt());
	  header->SetPhievt(GetTEpos()->GetPhievt());
	  header->SetKolevt(GetTEpos()->GetKolevt());
	  header->SetKoievt(GetTEpos()->GetKoievt());
	  header->SetPmxevt(GetTEpos()->GetPmxevt());
	  header->SetEgyevt(GetTEpos()->GetEgyevt());
	  header->SetNpjevt(GetTEpos()->GetNpjevt());
	  header->SetNtgevt(GetTEpos()->GetNtgevt());
	  header->SetNpnevt(GetTEpos()->GetNpnevt());
	  header->SetNppevt(GetTEpos()->GetNppevt());
	  header->SetNtnevt(GetTEpos()->GetNtnevt());
	  header->SetNtpevt(GetTEpos()->GetNtpevt());
	  header->SetJpnevt(GetTEpos()->GetJpnevt());
	  header->SetJppevt(GetTEpos()->GetJppevt());
	  header->SetJtnevt(GetTEpos()->GetJtnevt());
	  header->SetJtpevt(GetTEpos()->GetJtpevt());
	  header->SetXbjevt(GetTEpos()->GetXbjevt());
	  header->SetQsqevt(GetTEpos()->GetQsqevt());
	  header->SetNglevt(GetTEpos()->GetNglevt());
	  header->SetZppevt(GetTEpos()->GetZppevt());
	  header->SetZptevt(GetTEpos()->GetZptevt());
    AddHeader(header);
    fCollisionGeometry = (AliGenEposEventHeader*)  header;

    delete[] idsOnStack;
}

AliGenEpos::~AliGenEpos() {
}

<commit_msg>Coverity corrections.<commit_after>//
// AliGenEpos.cxx
//
//  ALICE event generator based on EPOS model from Klaus Werner
//
//  Created on: Feb 28, 2009
//      Author: Piotr Ostrowski, postrow@if.pw.edu.pl
//

#include "AliGenEpos.h"
#include "TEpos.h"
#include "TParticle.h"
#include "TMath.h"
#include "AliLog.h"
#include "AliGenEventHeader.h"
#include "AliGenEposEventHeader.h"

ClassImp(AliGenEpos)

AliGenEpos::AliGenEpos() : AliGenMC(),
		fBmin(0),
		fBmax(10000),
		fPhiMin(0),
		fPhiMax(TMath::TwoPi()),
		fFilterModelOutput(kFALSE) {
	SetMC(new TEpos());
}

AliGenEpos::AliGenEpos(Int_t npart) : AliGenMC(npart),
		fBmin(0),
		fBmax(10000),
		fPhiMin(0),
		fPhiMax(TMath::TwoPi()),
		fFilterModelOutput(kFALSE) {
	SetMC(new TEpos());
}

void AliGenEpos::Init() {
  // Sets up TEpos
	AliGenMC::Init();
	TEpos *epos = GetTEpos();
	epos->SetLaproj(this->fZProjectile);
	epos->SetMaproj(this->fAProjectile);
	epos->SetLatarg(this->fZTarget);
	epos->SetMatarg(this->fATarget);
	epos->SetPhimin(this->fPhiMin);
	epos->SetPhimax(this->fPhiMax);
	epos->SetBminim(this->fBmin);
	epos->SetBmaxim(this->fBmax);
	epos->SetEcms(this->fEnergyCMS);
	epos->SetSplitting(kTRUE);
	GetTEpos()->Initialize();
}

void AliGenEpos::Generate() {
  // Does actual generation and output conversion
	  Float_t polar[3]    =   {0,0,0};
	  Float_t origin0[3]  =   {0,0,0};
	  Float_t origin[3]   =   {0,0,0};
	  fNprimaries = 0;
	  Int_t nt  = 0; //output parameter for PushTrack

	  Vertex();
	  for (int j=0; j < 3; j++) origin0[j] = fVertex[j];

	  // Generate one event

	  GetTEpos()->GenerateEvent();
	  AliWarning("Generated");
	  GetTEpos()->ImportParticles(&fParticles);

	  Int_t np = fParticles.GetEntriesFast();
	  AliWarning(Form("Imported %d particles", np));

	  Int_t *idsOnStack = NULL;
	  idsOnStack = new Int_t[np];
	  for (int i = 0; i < np; i++) idsOnStack[i] = 0;
	  TParticle *iparticle;

	  for (int i = 0; i < np; i++) {
		  iparticle = (TParticle *) fParticles.At(i);
		  //Bool_t isNullEntry = iparticle->GetStatusCode() == 0;
		  //Bool_t isCommentOrUnknown = iparticle->GetStatusCode() > 2;
		  Bool_t hasDecayed = iparticle->GetStatusCode() >= 2;
		  Bool_t isFinalState = iparticle->GetStatusCode() == 1;
		  Int_t imo = iparticle->GetFirstMother();
		  Bool_t  hasMother = (imo >=0);

		  if (isFinalState) {
			  origin[0] = iparticle->Vx();
			  origin[1] = iparticle->Vy();
			  origin[2] = iparticle->Vz();
			  //doubled track with freeze out coordinates for femtoscopy
			  PushTrack(0,
					  imo>=0?idsOnStack[imo]:-1,
					  iparticle->GetPdgCode(),
				iparticle->Px(),iparticle->Py(),iparticle->Pz(),iparticle->Energy(),
				origin[0], origin[1], origin[2],
				iparticle->T(),
				polar[0],polar[1],polar[2],
				hasMother ? kPDecay:kPNoProcess,nt);

		      idsOnStack[i] = nt;
		      fNprimaries++;
		      KeepTrack(nt);

		      //real track with smeared vertex
		      origin[0] += origin0[0];
		      origin[1] += origin0[1];
		      origin[2] += origin0[2];
			  PushTrack(1,
					  nt,   //doubled track as mother
					  iparticle->GetPdgCode(),
				iparticle->Px(),iparticle->Py(),iparticle->Pz(),iparticle->Energy(),
				origin[0], origin[1], origin[2],
				iparticle->T(),
				polar[0],polar[1],polar[2],
				kPDecay,nt);
		      fNprimaries++;
		      KeepTrack(nt);
		  } else if(hasDecayed || !fFilterModelOutput) {
			  // don't track it and don't smear vertex
			  origin[0] = iparticle->Vx();
			  origin[1] = iparticle->Vy();
			  origin[2] = iparticle->Vz();
			  PushTrack(0,
					  imo>=0?idsOnStack[imo]:-1,
					  iparticle->GetPdgCode(),
				iparticle->Px(),iparticle->Py(),iparticle->Pz(),iparticle->Energy(),
				origin[0], origin[1], origin[2],
				iparticle->T(),
				polar[0],polar[1],polar[2],
				hasMother ? kPDecay:kPNoProcess,nt);
		      idsOnStack[i] = nt;
		      fNprimaries++;
		      KeepTrack(nt);
		  } else if(fFilterModelOutput) {
			  //filtered internal model objects
			  idsOnStack[i] = -1; // to erase mother field in its dauthers
		  }
	  }
	  SetHighWaterMark(fNprimaries);
	  TArrayF eventVertex;
	  eventVertex.Set(3);
	  eventVertex[0] = origin0[0];
	  eventVertex[1] = origin0[1];
	  eventVertex[2] = origin0[2];
	// Builds the event header, to be called after each event
	  AliGenEposEventHeader* header = new AliGenEposEventHeader("EPOS");

	  header->SetNProduced(fNprimaries);
	  header->SetPrimaryVertex(eventVertex);

	  header->SetImpactParameter(GetTEpos()->GetBimevt());
	  header->SetReactionPlaneAngle(GetTEpos()->GetPhievt());

	  header->SetHardScatters(0);
	  header->SetParticipants(GetTEpos()->GetNpjevt(), GetTEpos()->GetNtgevt());
	  header->SetCollisions(GetTEpos()->GetKolevt(), 0, 0, GetTEpos()->GetNpjevt());
	  header->SetSpectators(GetTEpos()->GetJpnevt(), GetTEpos()->GetJppevt(), GetTEpos()->GetJtnevt(), GetTEpos()->GetJtpevt());

	// Event Vertex
	  header->SetPrimaryVertex(fVertex);

	  header->SetBimevt(GetTEpos()->GetBimevt());
	  header->SetPhievt(GetTEpos()->GetPhievt());
	  header->SetKolevt(GetTEpos()->GetKolevt());
	  header->SetKoievt(GetTEpos()->GetKoievt());
	  header->SetPmxevt(GetTEpos()->GetPmxevt());
	  header->SetEgyevt(GetTEpos()->GetEgyevt());
	  header->SetNpjevt(GetTEpos()->GetNpjevt());
	  header->SetNtgevt(GetTEpos()->GetNtgevt());
	  header->SetNpnevt(GetTEpos()->GetNpnevt());
	  header->SetNppevt(GetTEpos()->GetNppevt());
	  header->SetNtnevt(GetTEpos()->GetNtnevt());
	  header->SetNtpevt(GetTEpos()->GetNtpevt());
	  header->SetJpnevt(GetTEpos()->GetJpnevt());
	  header->SetJppevt(GetTEpos()->GetJppevt());
	  header->SetJtnevt(GetTEpos()->GetJtnevt());
	  header->SetJtpevt(GetTEpos()->GetJtpevt());
	  header->SetXbjevt(GetTEpos()->GetXbjevt());
	  header->SetQsqevt(GetTEpos()->GetQsqevt());
	  header->SetNglevt(GetTEpos()->GetNglevt());
	  header->SetZppevt(GetTEpos()->GetZppevt());
	  header->SetZptevt(GetTEpos()->GetZptevt());
    AddHeader(header);
    fCollisionGeometry = (AliGenEposEventHeader*)  header;

    delete[] idsOnStack;
}

AliGenEpos::~AliGenEpos() {
}

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_FEATURE_HPP
#define MAPNIK_FEATURE_HPP

// mapnik
#include <mapnik/value.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/raster.hpp>

// boost
#include <boost/version.hpp>
#if BOOST_VERSION >= 104000
#include <boost/property_map/property_map.hpp>
#else
#include <boost/property_map.hpp>
#endif
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>

// stl
#include <map>

namespace mapnik {

typedef boost::shared_ptr<raster> raster_ptr;
typedef std::map<std::string,int> map_type;
typedef boost::associative_property_map<map_type> base_type;

class feature_impl;

class context : private boost::noncopyable,
                public base_type

{
    friend class feature_impl;
public:

    context()
        : base_type(mapping_) {}

    void push(std::string const& name)
    {
        mapping_.insert(std::make_pair(name,mapping_.size()));
    }

private:
    map_type mapping_;
};

typedef boost::shared_ptr<context> context_ptr;

class feature_impl : private boost::noncopyable
{
public:
    typedef mapnik::value value_type;
    typedef std::vector<value_type> cont_type;

    feature_impl(context_ptr const& ctx, int id)
        : id_(id),
          ctx_(ctx),
          data_(ctx_->mapping_.size())
    {}

    inline int id() const { return id_;}

    inline void set_id(int id) { id_ = id;}

    template <typename T>
    void put(std::string const& key, T const& val)
    {
        map_type::const_iterator itr = ctx_->mapping_.find(key);
        if (itr != ctx_->mapping_.end())
        {
            data_[itr->second] = value(val);
        }
    }

    value_type const& get(std::string const& key) const
    {
        map_type::const_iterator itr = ctx_->mapping_.find(key);
        if (itr != ctx_->mapping_.end())
        {
            return data_[itr->second];
        }
        static const value_type default_value;
        return default_value;
    }

    boost::ptr_vector<geometry_type> & paths()
    {
        return geom_cont_;
    }

    void add_geometry(geometry_type * geom)
    {
       geom_cont_.push_back(geom);
    }

    unsigned num_geometries() const
    {
        return geom_cont_.size();
    }

    geometry_type const& get_geometry(unsigned index) const
    {
        return geom_cont_[index];
    }

    geometry_type& get_geometry(unsigned index)
    {
        return geom_cont_[index];
    }

    const raster_ptr& get_raster() const
    {
        return raster_;
    }

    void set_raster(raster_ptr const& raster)
    {
        raster_ = raster;
    }

    std::string to_string() const
    {
        std::stringstream ss;
        ss << "Feature (" << std::endl;
        map_type::const_iterator itr = ctx_->mapping_.begin();
        map_type::const_iterator end = ctx_->mapping_.end();
        for ( ;itr!=end; ++itr)
        {
            ss << "  " << itr->first  << ":" <<  data_[itr->second] << std::endl;
        }
        ss << ")" << std::endl;
        return ss.str();
    }

private:
    context_ptr ctx_;
    int id_;
    boost::ptr_vector<geometry_type> geom_cont_;
    raster_ptr raster_;

    cont_type data_;
};

inline std::ostream& operator<< (std::ostream & out,feature_impl const& f)
{
    out << f.to_string();
    return out;
}

typedef feature_impl Feature;

}

#endif // MAPNIK_FEATURE_HPP
<commit_msg>fix init order<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_FEATURE_HPP
#define MAPNIK_FEATURE_HPP

// mapnik
#include <mapnik/value.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/raster.hpp>

// boost
#include <boost/version.hpp>
#if BOOST_VERSION >= 104000
#include <boost/property_map/property_map.hpp>
#else
#include <boost/property_map.hpp>
#endif
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>

// stl
#include <map>

namespace mapnik {

typedef boost::shared_ptr<raster> raster_ptr;
typedef std::map<std::string,int> map_type;
typedef boost::associative_property_map<map_type> base_type;

class feature_impl;

class context : private boost::noncopyable,
                public base_type

{
    friend class feature_impl;
public:

    context()
        : base_type(mapping_) {}

    void push(std::string const& name)
    {
        mapping_.insert(std::make_pair(name,mapping_.size()));
    }

private:
    map_type mapping_;
};

typedef boost::shared_ptr<context> context_ptr;

class feature_impl : private boost::noncopyable
{
public:
    typedef mapnik::value value_type;
    typedef std::vector<value_type> cont_type;

    feature_impl(context_ptr const& ctx, int id)
        : id_(id),
          ctx_(ctx),
          data_(ctx_->mapping_.size())
    {}

    inline int id() const { return id_;}

    inline void set_id(int id) { id_ = id;}

    template <typename T>
    void put(std::string const& key, T const& val)
    {
        map_type::const_iterator itr = ctx_->mapping_.find(key);
        if (itr != ctx_->mapping_.end())
        {
            data_[itr->second] = value(val);
        }
    }

    value_type const& get(std::string const& key) const
    {
        map_type::const_iterator itr = ctx_->mapping_.find(key);
        if (itr != ctx_->mapping_.end())
        {
            return data_[itr->second];
        }
        static const value_type default_value;
        return default_value;
    }

    boost::ptr_vector<geometry_type> & paths()
    {
        return geom_cont_;
    }

    void add_geometry(geometry_type * geom)
    {
       geom_cont_.push_back(geom);
    }

    unsigned num_geometries() const
    {
        return geom_cont_.size();
    }

    geometry_type const& get_geometry(unsigned index) const
    {
        return geom_cont_[index];
    }

    geometry_type& get_geometry(unsigned index)
    {
        return geom_cont_[index];
    }

    const raster_ptr& get_raster() const
    {
        return raster_;
    }

    void set_raster(raster_ptr const& raster)
    {
        raster_ = raster;
    }

    std::string to_string() const
    {
        std::stringstream ss;
        ss << "Feature (" << std::endl;
        map_type::const_iterator itr = ctx_->mapping_.begin();
        map_type::const_iterator end = ctx_->mapping_.end();
        for ( ;itr!=end; ++itr)
        {
            ss << "  " << itr->first  << ":" <<  data_[itr->second] << std::endl;
        }
        ss << ")" << std::endl;
        return ss.str();
    }

private:
    int id_;
    context_ptr ctx_;
    boost::ptr_vector<geometry_type> geom_cont_;
    raster_ptr raster_;

    cont_type data_;
};

inline std::ostream& operator<< (std::ostream & out,feature_impl const& f)
{
    out << f.to_string();
    return out;
}

typedef feature_impl Feature;

}

#endif // MAPNIK_FEATURE_HPP
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_FEATURE_HPP
#define MAPNIK_FEATURE_HPP

// mapnik
#include <mapnik/value.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/raster.hpp>

// boost
#include <boost/version.hpp>
#if BOOST_VERSION >= 104000
#include <boost/property_map/property_map.hpp>
#else
#include <boost/property_map.hpp>
#endif
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>

// stl
#include <vector>
#include <map>
#include <stdexcept>

namespace mapnik {

typedef boost::shared_ptr<raster> raster_ptr;
typedef std::string key_type;
typedef std::map<key_type,std::size_t> map_type;
typedef boost::associative_property_map<map_type> base_type;

class feature_impl;

class context : private boost::noncopyable,
                public base_type

{
    friend class feature_impl;
public:
    typedef map_type::value_type value_type;
    typedef map_type::key_type key_type;
    typedef map_type::size_type size_type;
    typedef map_type::difference_type difference_type;
    typedef map_type::iterator iterator;
    typedef map_type::const_iterator const_iterator;

    context()
        : base_type(mapping_) {}

    void push(key_type const& name)
    {
        mapping_.insert(std::make_pair(name,mapping_.size()));
    }
    std::size_t size() const { return mapping_.size(); }
    const_iterator begin() const { return mapping_.begin();}
    const_iterator end() const { return mapping_.end();}

private:
    map_type mapping_;
};

typedef boost::shared_ptr<context> context_ptr;

class feature_impl : private boost::noncopyable
{
    friend class feature_kv_iterator;
public:

    typedef mapnik::value value_type;
    typedef std::vector<value_type> cont_type;

    feature_impl(context_ptr const& ctx, int id)
        : id_(id),
          ctx_(ctx),
          data_(ctx_->mapping_.size())
    {}

    inline int id() const { return id_;}

    inline void set_id(int id) { id_ = id;}

    template <typename T>
    void put(key_type const& key, T const& val)
    {
        map_type::const_iterator itr = ctx_->mapping_.find(key);
        if (itr != ctx_->mapping_.end())
        {
            data_[itr->second] = value(val);
        }
        else
            throw std::out_of_range("Key doesn't exist");
    }

    void put(key_type const& key, value const& val)
    {
        map_type::const_iterator itr = ctx_->mapping_.find(key);
        if (itr != ctx_->mapping_.end())
        {
            data_[itr->second] = val;
        }
        else
            throw std::out_of_range("Key doesn't exist");
    }

    bool has_key(key_type const& key) const
    {
        return (ctx_->mapping_.find(key) != ctx_->mapping_.end());
    }

    value_type const& get(key_type const& key) const
    {
        map_type::const_iterator itr = ctx_->mapping_.find(key);
        if (itr != ctx_->mapping_.end())
        {
            return data_[itr->second];
        }
        throw std::out_of_range("Key doesn't exist");
    }

    boost::ptr_vector<geometry_type> & paths()
    {
        return geom_cont_;
    }

    void add_geometry(geometry_type * geom)
    {
        geom_cont_.push_back(geom);
    }

    unsigned num_geometries() const
    {
        return geom_cont_.size();
    }

    geometry_type const& get_geometry(unsigned index) const
    {
        return geom_cont_[index];
    }

    geometry_type& get_geometry(unsigned index)
    {
        return geom_cont_[index];
    }

    box2d<double> envelope() const
    {
        box2d<double> result;
        for (unsigned i=0;i<num_geometries();++i)
        {
            geometry_type const& geom = get_geometry(i);
            if (i==0)
            {
                box2d<double> box = geom.envelope();
                result.init(box.minx(),box.miny(),box.maxx(),box.maxy());
            }
            else
            {
                result.expand_to_include(geom.envelope());
            }
        }
        return result;
    }

    const raster_ptr& get_raster() const
    {
        return raster_;
    }

    void set_raster(raster_ptr const& raster)
    {
        raster_ = raster;
    }

    std::string to_string() const
    {
        std::stringstream ss;
        ss << "Feature (" << std::endl;
        map_type::const_iterator itr = ctx_->mapping_.begin();
        map_type::const_iterator end = ctx_->mapping_.end();
        for ( ;itr!=end; ++itr)
        {
            ss << "  " << itr->first  << ":" <<  data_[itr->second] << std::endl;
        }
        ss << ")" << std::endl;
        return ss.str();
    }

private:
    int id_;
    context_ptr ctx_;
    boost::ptr_vector<geometry_type> geom_cont_;
    raster_ptr raster_;
    cont_type data_;
};

inline std::ostream& operator<< (std::ostream & out,feature_impl const& f)
{
    out << f.to_string();
    return out;
}

typedef feature_impl Feature;

}

#endif // MAPNIK_FEATURE_HPP
<commit_msg>+ check index in valid range+ + add size() and context() methods<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_FEATURE_HPP
#define MAPNIK_FEATURE_HPP

// mapnik
#include <mapnik/value.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/raster.hpp>

// boost
#include <boost/version.hpp>
#if BOOST_VERSION >= 104000
#include <boost/property_map/property_map.hpp>
#else
#include <boost/property_map.hpp>
#endif
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>

// stl
#include <vector>
#include <map>
#include <stdexcept>

namespace mapnik {

typedef boost::shared_ptr<raster> raster_ptr;
typedef std::string key_type;
typedef std::map<key_type,std::size_t> map_type;
typedef boost::associative_property_map<map_type> base_type;

class feature_impl;

class context : private boost::noncopyable,
                public base_type

{
    friend class feature_impl;
public:
    typedef map_type::value_type value_type;
    typedef map_type::key_type key_type;
    typedef map_type::size_type size_type;
    typedef map_type::difference_type difference_type;
    typedef map_type::iterator iterator;
    typedef map_type::const_iterator const_iterator;

    context()
        : base_type(mapping_) {}

    void push(key_type const& name)
    {
        mapping_.insert(std::make_pair(name,mapping_.size()));
    }
    std::size_t size() const { return mapping_.size(); }
    const_iterator begin() const { return mapping_.begin();}
    const_iterator end() const { return mapping_.end();}

private:
    map_type mapping_;
};

typedef boost::shared_ptr<context> context_ptr;

class feature_impl : private boost::noncopyable
{
    friend class feature_kv_iterator;
public:

    typedef mapnik::value value_type;
    typedef std::vector<value_type> cont_type;

    feature_impl(context_ptr const& ctx, int id)
        : id_(id),
          ctx_(ctx),
          data_(ctx_->mapping_.size())
    {}

    inline int id() const { return id_;}

    inline void set_id(int id) { id_ = id;}

    template <typename T>
    void put(key_type const& key, T const& val)
    {
        map_type::const_iterator itr = ctx_->mapping_.find(key);
        if (itr != ctx_->mapping_.end()
            && itr->second < data_.size())
        {
            data_[itr->second] = value(val);
        }
        else
            throw std::out_of_range("Key doesn't exist");
    }

    void put(key_type const& key, value const& val)
    {
        map_type::const_iterator itr = ctx_->mapping_.find(key);
        if (itr != ctx_->mapping_.end()
            && itr->second < data_.size())
        {
            data_[itr->second] = val;
        }
        else
            throw std::out_of_range("Key doesn't exist");
    }

    bool has_key(key_type const& key) const
    {
        return (ctx_->mapping_.find(key) != ctx_->mapping_.end());
    }

    value_type const& get(key_type const& key) const
    {
        map_type::const_iterator itr = ctx_->mapping_.find(key);
        if (itr != ctx_->mapping_.end()
            && itr->second < data_.size())
        {
            return data_[itr->second];
        }
        throw std::out_of_range("Key doesn't exist");
    }

    std::size_t size() const
    {
        return data_.size();
    }

    context_ptr context()
    {
        return ctx_;
    }

    boost::ptr_vector<geometry_type> & paths()
    {
        return geom_cont_;
    }

    void add_geometry(geometry_type * geom)
    {
        geom_cont_.push_back(geom);
    }

    unsigned num_geometries() const
    {
        return geom_cont_.size();
    }

    geometry_type const& get_geometry(unsigned index) const
    {
        return geom_cont_[index];
    }

    geometry_type& get_geometry(unsigned index)
    {
        return geom_cont_[index];
    }

    box2d<double> envelope() const
    {
        box2d<double> result;
        for (unsigned i=0;i<num_geometries();++i)
        {
            geometry_type const& geom = get_geometry(i);
            if (i==0)
            {
                box2d<double> box = geom.envelope();
                result.init(box.minx(),box.miny(),box.maxx(),box.maxy());
            }
            else
            {
                result.expand_to_include(geom.envelope());
            }
        }
        return result;
    }

    const raster_ptr& get_raster() const
    {
        return raster_;
    }

    void set_raster(raster_ptr const& raster)
    {
        raster_ = raster;
    }

    std::string to_string() const
    {
        std::stringstream ss;
        ss << "Feature (" << std::endl;
        map_type::const_iterator itr = ctx_->mapping_.begin();
        map_type::const_iterator end = ctx_->mapping_.end();
        for ( ;itr!=end; ++itr)
        {
            ss << "  " << itr->first  << ":" <<  data_[itr->second] << std::endl;
        }
        ss << ")" << std::endl;
        return ss.str();
    }

private:
    int id_;
    context_ptr ctx_;
    boost::ptr_vector<geometry_type> geom_cont_;
    raster_ptr raster_;
    cont_type data_;
};

inline std::ostream& operator<< (std::ostream & out,feature_impl const& f)
{
    out << f.to_string();
    return out;
}

typedef feature_impl Feature;

}

#endif // MAPNIK_FEATURE_HPP
<|endoftext|>


<commit_before>#pragma once

#include <cstddef>
#include <memory>
#include <functional>
#include <ratio>
#include <iterator>
#include <initializer_list>

#include <circular_iterator.hpp>

namespace helene
{
template <class T,
          std::size_t Size,
          template <class, class, std::size_t> class StoragePolicy>
class sliding_window
    : public StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
{
    typedef StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
        storage_policy;

public:
    static const std::size_t size = Size;

    typedef T value_type;
    typedef T& reference;
    typedef const T& const_reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef circular_iterator<T*> iterator;
    typedef circular_iterator<const T*> const_iterator;

public:
    sliding_window()
        : storage_policy(),
          head_(storage_policy::begin(),
                storage_policy::end(),
                storage_policy::begin())
    {
    }

    template <class Iterator>
    sliding_window(Iterator first, Iterator last) : sliding_window()
    {
        for(; first != last; ++first, ++head_)
        {
            *head_ = *first;
        }
    }

    sliding_window(std::initializer_list<T> il)
        : sliding_window(il.begin(), il.end())
    {
    }

    void
    push_back(const T& value)
    {
        *head_ = value;
        ++head_;
    }

    void
    push_back(const T& value, size_type n)
    {
        std::fill_n(head_, n, value);
        head_ += n;
    }

    void
    push_front(const T& value)
    {
        --head_;
        *head_ = value;
    }

    void
    push_front(const T& value, size_type n)
    {
        std::fill_n(std::make_reverse_iterator(head_), n, value);
        head_ -= n;
    }

    reference
    front()
    {
        return *head_;
    }

    const_reference
    front() const
    {
        return *head_;
    }

    reference
    back()
    {
        return *(head_ + Size - 1);
    }

    const_reference
    back() const
    {
        return *(head_ + Size - 1);
    }

    reference operator[](size_type n)
    {
        return head_[n];
    }

    const_reference operator[](size_type n) const
    {
        return head_[n];
    }

    iterator
    begin()
    {
        return head_;
    }

    iterator
    end()
    {
        return head_ + Size;
    }

private:
    iterator head_;
};

template <class Derived, class T, std::size_t Size>
class stack_storage
{
public:
    stack_storage() : buffer_{}
    {
    }

    stack_storage(const stack_storage& other)
    {
        std::copy(std::begin(other.buffer_),
                  std::end(other.buffer_),
                  std::begin(buffer_));
    }

public:
    T*
    begin()
    {
        return buffer_;
    }

    T*
    end()
    {
        return buffer_ + Size;
    }

protected:
    T buffer_[Size];
};

template <class Derived, class T, std::size_t Size>
class static_heap_storage
{
public:
    static_heap_storage() : buffer_(new T[Size]{})
    {
    }

    static_heap_storage(const static_heap_storage& other)
        : static_heap_storage()
    {
        std::copy(
            other.buffer_.get(), other.buffer_.get() + Size, buffer_.get());
    }

    static_heap_storage(static_heap_storage&& other) = default;

    static_heap_storage&
    operator=(const static_heap_storage& other)
    {
        auto temp = other;
        swap(*this, temp);
        return *this;
    }

    void
    swap(static_heap_storage& other)
    {
        std::swap(buffer_, other.buffer_);
    }

public:
    T*
    begin()
    {
        return buffer_.get();
    }

    T*
    end()
    {
        return buffer_.get() + Size;
    }

protected:
    std::unique_ptr<T[]> buffer_;
};

template <class T, std::size_t Size>
using stack_sliding_window = sliding_window<T, Size, stack_storage>;

template <class T, std::size_t Size>
using static_heap_sliding_window = sliding_window<T, Size, static_heap_storage>;

namespace detail
{
struct runtime_ratio
{
    runtime_ratio() : num(1), den(1)
    {
    }

    template <std::intmax_t Num, std::intmax_t Denom>
    constexpr runtime_ratio(std::ratio<Num, Denom>) : num(Num), den(Denom)
    {
    }

    std::intmax_t num;
    std::intmax_t den;
};

template <class Numeric>
Numeric operator*(const runtime_ratio& lhs, Numeric rhs)
{
    return rhs * static_cast<Numeric>(lhs.num) / static_cast<Numeric>(lhs.den);
}

template <class Numeric>
Numeric operator*(Numeric lhs, const runtime_ratio& rhs)
{
    return rhs * lhs;
}

template <class Numeric>
Numeric
operator/(Numeric lhs, const runtime_ratio& rhs)
{
    return lhs * static_cast<Numeric>(rhs.den) / static_cast<Numeric>(rhs.num);
}
} // namespace detail

template <class KeyType,
          class ValueType,
          std::size_t Size,
          class Compare = std::less<KeyType>>
class sliding_window_map
{
public:
    sliding_window_map() = default;
    template <std::intmax_t Num, std::intmax_t Denom>
    sliding_window_map(std::ratio<Num, Denom>)
        : sliding_buffer_(), origin_(), precision_(std::ratio<Num, Denom>())
    {
    }

    std::pair<KeyType, KeyType>
    extent() const
    {
        return std::make_pair(origin_, origin_ + Size * precision_);
    }

    ////////////////////////////////////////////////////////////////////////////
    // map like interface
    ValueType&
    at(KeyType k)
    {
        const auto index = index_of_key(k);
        const Compare c;
        if(c(index, 0) || (!c(index, Size)))
        {
            throw std::out_of_range("Key outside of current window");
        }

        return sliding_buffer_[index];
    }

private:
    std::size_t
    index_of_key(KeyType k)
    {
        return (k - origin_) / precision_;
    }

private:
    static_heap_sliding_window<ValueType, Size> sliding_buffer_;
    KeyType origin_;
    detail::runtime_ratio precision_;
};
} // namespace helene
<commit_msg>Add copy assignment operator to stack_storage policy class. 	modified:   include/sliding_window.hpp<commit_after>#pragma once

#include <cstddef>
#include <memory>
#include <functional>
#include <ratio>
#include <iterator>
#include <initializer_list>

#include <circular_iterator.hpp>

namespace helene
{
template <class T,
          std::size_t Size,
          template <class, class, std::size_t> class StoragePolicy>
class sliding_window
    : public StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
{
    typedef StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
        storage_policy;

public:
    static const std::size_t size = Size;

    typedef T value_type;
    typedef T& reference;
    typedef const T& const_reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef circular_iterator<T*> iterator;
    typedef circular_iterator<const T*> const_iterator;

public:
    sliding_window()
        : storage_policy(),
          head_(storage_policy::begin(),
                storage_policy::end(),
                storage_policy::begin())
    {
    }

    template <class Iterator>
    sliding_window(Iterator first, Iterator last) : sliding_window()
    {
        for(; first != last; ++first, ++head_)
        {
            *head_ = *first;
        }
    }

    sliding_window(std::initializer_list<T> il)
        : sliding_window(il.begin(), il.end())
    {
    }

    void
    push_back(const T& value)
    {
        *head_ = value;
        ++head_;
    }

    void
    push_back(const T& value, size_type n)
    {
        std::fill_n(head_, n, value);
        head_ += n;
    }

    void
    push_front(const T& value)
    {
        --head_;
        *head_ = value;
    }

    void
    push_front(const T& value, size_type n)
    {
        std::fill_n(std::make_reverse_iterator(head_), n, value);
        head_ -= n;
    }

    reference
    front()
    {
        return *head_;
    }

    const_reference
    front() const
    {
        return *head_;
    }

    reference
    back()
    {
        return *(head_ + Size - 1);
    }

    const_reference
    back() const
    {
        return *(head_ + Size - 1);
    }

    reference operator[](size_type n)
    {
        return head_[n];
    }

    const_reference operator[](size_type n) const
    {
        return head_[n];
    }

    iterator
    begin()
    {
        return head_;
    }

    iterator
    end()
    {
        return head_ + Size;
    }

private:
    iterator head_;
};

template <class Derived, class T, std::size_t Size>
class stack_storage
{
public:
    stack_storage() : buffer_{}
    {
    }

    stack_storage(const stack_storage& other)
    {
        std::copy(std::begin(other.buffer_),
                  std::end(other.buffer_),
                  std::begin(buffer_));
    }

    stack_storage&
    operator=(const stack_storage& other)
    {
        std::copy(std::begin(other.buffer_),
                  std::end(other.buffer_),
                  std::begin(buffer_));
    }

public:
    T*
    begin()
    {
        return buffer_;
    }

    T*
    end()
    {
        return buffer_ + Size;
    }

protected:
    T buffer_[Size];
};

template <class Derived, class T, std::size_t Size>
class static_heap_storage
{
public:
    static_heap_storage() : buffer_(new T[Size]{})
    {
    }

    static_heap_storage(const static_heap_storage& other)
        : static_heap_storage()
    {
        std::copy(
            other.buffer_.get(), other.buffer_.get() + Size, buffer_.get());
    }

    static_heap_storage(static_heap_storage&& other) = default;

    static_heap_storage&
    operator=(const static_heap_storage& other)
    {
        auto temp = other;
        swap(*this, temp);
        return *this;
    }

    void
    swap(static_heap_storage& other)
    {
        std::swap(buffer_, other.buffer_);
    }

public:
    T*
    begin()
    {
        return buffer_.get();
    }

    T*
    end()
    {
        return buffer_.get() + Size;
    }

protected:
    std::unique_ptr<T[]> buffer_;
};

template <class T, std::size_t Size>
using stack_sliding_window = sliding_window<T, Size, stack_storage>;

template <class T, std::size_t Size>
using static_heap_sliding_window = sliding_window<T, Size, static_heap_storage>;

namespace detail
{
struct runtime_ratio
{
    runtime_ratio() : num(1), den(1)
    {
    }

    template <std::intmax_t Num, std::intmax_t Denom>
    constexpr runtime_ratio(std::ratio<Num, Denom>) : num(Num), den(Denom)
    {
    }

    std::intmax_t num;
    std::intmax_t den;
};

template <class Numeric>
Numeric operator*(const runtime_ratio& lhs, Numeric rhs)
{
    return rhs * static_cast<Numeric>(lhs.num) / static_cast<Numeric>(lhs.den);
}

template <class Numeric>
Numeric operator*(Numeric lhs, const runtime_ratio& rhs)
{
    return rhs * lhs;
}

template <class Numeric>
Numeric
operator/(Numeric lhs, const runtime_ratio& rhs)
{
    return lhs * static_cast<Numeric>(rhs.den) / static_cast<Numeric>(rhs.num);
}
} // namespace detail

template <class KeyType,
          class ValueType,
          std::size_t Size,
          class Compare = std::less<KeyType>>
class sliding_window_map
{
public:
    sliding_window_map() = default;
    template <std::intmax_t Num, std::intmax_t Denom>
    sliding_window_map(std::ratio<Num, Denom>)
        : sliding_buffer_(), origin_(), precision_(std::ratio<Num, Denom>())
    {
    }

    std::pair<KeyType, KeyType>
    extent() const
    {
        return std::make_pair(origin_, origin_ + Size * precision_);
    }

    ////////////////////////////////////////////////////////////////////////////
    // map like interface
    ValueType&
    at(KeyType k)
    {
        const auto index = index_of_key(k);
        const Compare c;
        if(c(index, 0) || (!c(index, Size)))
        {
            throw std::out_of_range("Key outside of current window");
        }

        return sliding_buffer_[index];
    }

private:
    std::size_t
    index_of_key(KeyType k)
    {
        return (k - origin_) / precision_;
    }

private:
    static_heap_sliding_window<ValueType, Size> sliding_buffer_;
    KeyType origin_;
    detail::runtime_ratio precision_;
};
} // namespace helene
<|endoftext|>


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

#if defined(_WIN32)
  #include <direct.h>
  #include <io.h>
  #define access _access
  #define R_OK 4
  #define W_OK 2
  #define X_OK R_OK
  #define F_OK 0
#else
  #include <sys/stat.h>
  #include <unistd.h>
#endif
#include <cerrno>
#include <stdexcept>
#include <string>
#include <ostream>

namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace filesystem {

class path {
  public:
    path(std::string&& x): data_(std::move(x)) {}

    template <class T>
    path(const T& x): data_(x) {}

    path parent_path() const {
        if (data_ == "/") return *this;
        auto pos = data_.find_last_of('/');
        return path(data_.substr(0u, pos));
    }
    path filename() const {
        if (data_ == "/") return *this;
        auto pos = data_.find_last_of('/');
        return path(data_.substr(++pos));
    }
    path stem() const {
        auto name = filename().string();
        auto pos = name.find_last_of('.');
        if (pos == std::string::npos) return path("");
        if (pos == name.size() - 1u) return path(name);
        return path(name.substr(0u, pos));
    }
    path extension() const {
        auto name = filename().string();
        auto pos = name.find_last_of('.');
        if (pos == std::string::npos) return path("");
        if (pos == name.size() - 1u) return path("");
        return path(name.substr(pos));
    }
    path& append(const path& p) {
        if (p.is_absolute()) {
            data_ = p.data_;
        } else {
            if (data_.back() != '/') {
                data_ += '/';
            }
            data_ += p.string();
        }
        return *this;
    }
    path& operator/=(const path& p) {
        return append(p);
    }
    path& concat(const path& p) {
        data_ += p.string();
        return *this;
    }
    path& operator+=(const path& p) {
        return concat(p);
    }
    friend path operator/(const path& lhs, const path& rhs) {
        return path(lhs.string()) /= rhs;
    }
    friend bool operator==(const path& lhs, const path& rhs) noexcept {
        return lhs.data_ == rhs.data_;
    }
    friend bool operator!=(const path& lhs, const path& rhs) noexcept {
        return lhs.data_ != rhs.data_;
    }
    friend std::ostream& operator<<(std::ostream& ost, const path& p) {
        return ost << '"' << p.string() << '"';
    }
    bool is_absolute() const {return data_[0u] == '/';}
    bool is_relative() const {return !is_absolute();}
    const char* c_str() const noexcept {return data_.c_str();}
    std::string string() const noexcept {return data_;}
  private:
    std::string data_;
};

inline bool create_directory(const path& p) {
#if defined(_WIN32)
    const int status = ::_mkdir(p.c_str());
#else
    const int status = ::mkdir(p.c_str(), 0755);
#endif
    if (status && errno != EEXIST) {
        throw std::runtime_error(p.string());
    }
    return status == 0;
}

inline void current_path(const path& p) {
#if defined(_WIN32)
    if (::_chdir(p.c_str())) {
#else
    if (::chdir(p.c_str())) {
#endif
        throw std::runtime_error(p.string());
    }
}

inline path current_path() {
    char buffer[1024];
#if defined(_WIN32)
    if (!::_getcwd(buffer, sizeof(buffer))) {
#else
    if (!::getcwd(buffer, sizeof(buffer))) {
#endif
        throw std::runtime_error(buffer);
    }
    return path(std::string(buffer));
}

inline bool exists(const path& p) {
    return !::access(p.c_str(), F_OK);
}

} // namespace filesystem
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

// RAII
class ChDir {
  public:
    ChDir(const std::string& dst, bool mkdir=false) {
        if (dst.empty() || dst == ".") return;
        if (mkdir) {
            filesystem::create_directory(dst);
        }
        filesystem::current_path(dst);
    }
    ~ChDir() {
        filesystem::current_path(origin_);
    }
  private:
    const filesystem::path origin_ = filesystem::current_path();
};

} // namespace wtl

#endif /* WTL_FILESYSTEM_HPP_ */
<commit_msg>:art: Clean switch for _WIN32<commit_after>#pragma once
#ifndef WTL_FILESYSTEM_HPP_
#define WTL_FILESYSTEM_HPP_

#if defined(_WIN32)
  #include <direct.h>
  #include <io.h>
  #define mkdir(name, mode) _mkdir(name)
  #define chdir _chdir
  #define getcwd _getcwd
  #define access _access
  #define F_OK 0
#else
  #include <sys/stat.h>
  #include <unistd.h>
#endif
#include <cerrno>
#include <stdexcept>
#include <string>
#include <ostream>

namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace filesystem {

class path {
  public:
    path(std::string&& x): data_(std::move(x)) {}

    template <class T>
    path(const T& x): data_(x) {}

    path parent_path() const {
        if (data_ == "/") return *this;
        auto pos = data_.find_last_of('/');
        return path(data_.substr(0u, pos));
    }
    path filename() const {
        if (data_ == "/") return *this;
        auto pos = data_.find_last_of('/');
        return path(data_.substr(++pos));
    }
    path stem() const {
        auto name = filename().string();
        auto pos = name.find_last_of('.');
        if (pos == std::string::npos) return path("");
        if (pos == name.size() - 1u) return path(name);
        return path(name.substr(0u, pos));
    }
    path extension() const {
        auto name = filename().string();
        auto pos = name.find_last_of('.');
        if (pos == std::string::npos) return path("");
        if (pos == name.size() - 1u) return path("");
        return path(name.substr(pos));
    }
    path& append(const path& p) {
        if (p.is_absolute()) {
            data_ = p.data_;
        } else {
            if (data_.back() != '/') {
                data_ += '/';
            }
            data_ += p.string();
        }
        return *this;
    }
    path& operator/=(const path& p) {
        return append(p);
    }
    path& concat(const path& p) {
        data_ += p.string();
        return *this;
    }
    path& operator+=(const path& p) {
        return concat(p);
    }
    friend path operator/(const path& lhs, const path& rhs) {
        return path(lhs.string()) /= rhs;
    }
    friend bool operator==(const path& lhs, const path& rhs) noexcept {
        return lhs.data_ == rhs.data_;
    }
    friend bool operator!=(const path& lhs, const path& rhs) noexcept {
        return lhs.data_ != rhs.data_;
    }
    friend std::ostream& operator<<(std::ostream& ost, const path& p) {
        return ost << '"' << p.string() << '"';
    }
    bool is_absolute() const {return data_[0u] == '/';}
    bool is_relative() const {return !is_absolute();}
    const char* c_str() const noexcept {return data_.c_str();}
    std::string string() const noexcept {return data_;}
  private:
    std::string data_;
};

inline bool create_directory(const path& p) {
    const int status = ::mkdir(p.c_str(), 0755);
    if (status && errno != EEXIST) {
        throw std::runtime_error(p.string());
    }
    return status == 0;
}

inline void current_path(const path& p) {
    if (::chdir(p.c_str())) {
        throw std::runtime_error(p.string());
    }
}

inline path current_path() {
    char buffer[1024];
    if (!::getcwd(buffer, sizeof(buffer))) {
        throw std::runtime_error(buffer);
    }
    return path(std::string(buffer));
}

inline bool exists(const path& p) {
    return !::access(p.c_str(), F_OK);
}

} // namespace filesystem
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

// RAII
class ChDir {
  public:
    ChDir(const std::string& dst, bool mkdir=false) {
        if (dst.empty() || dst == ".") return;
        if (mkdir) {
            filesystem::create_directory(dst);
        }
        filesystem::current_path(dst);
    }
    ~ChDir() {
        filesystem::current_path(origin_);
    }
  private:
    const filesystem::path origin_ = filesystem::current_path();
};

} // namespace wtl

#endif /* WTL_FILESYSTEM_HPP_ */
<|endoftext|>


<commit_before>#include <stdio.h>  // for snprintf
#include <string>
#include <vector>

#include "boost/algorithm/string.hpp"
#include "google/protobuf/text_format.h"

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/net.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/db.hpp"
#include "caffe/util/io.hpp"
#include "caffe/vision_layers.hpp"

using caffe::Blob;
using caffe::Caffe;
using caffe::Datum;
using caffe::Net;
using boost::shared_ptr;
using std::string;
namespace db = caffe::db;

template<typename Dtype>
int feature_extraction_pipeline(int argc, char** argv);

int main(int argc, char** argv) {
  return feature_extraction_pipeline<float>(argc, argv);
//  return feature_extraction_pipeline<double>(argc, argv);
}

template<typename Dtype>
int feature_extraction_pipeline(int argc, char** argv) {
  ::google::InitGoogleLogging(argv[0]);
  const int num_required_args = 7;
  if (argc < num_required_args) {
    LOG(ERROR)<<
    "This program takes in a trained network and an input data layer, and then"
    " extract features of the input data produced by the net.\n"
    "Usage: extract_features  pretrained_net_param"
    "  feature_extraction_proto_file  extract_feature_blob_name1[,name2,...]"
    "  save_feature_dataset_name1[,name2,...]  num_mini_batches  db_type"
    "  [CPU/GPU] [DEVICE_ID=0]\n"
    "Note: you can extract multiple features in one pass by specifying"
    " multiple feature blob names and dataset names seperated by ','."
    " The names cannot contain white space characters and the number of blobs"
    " and datasets must be equal.";
    return 1;
  }
  int arg_pos = num_required_args;

  arg_pos = num_required_args;
  if (argc > arg_pos && strcmp(argv[arg_pos], "GPU") == 0) {
    LOG(ERROR)<< "Using GPU";
    uint device_id = 0;
    if (argc > arg_pos + 1) {
      device_id = atoi(argv[arg_pos + 1]);
      CHECK_GE(device_id, 0);
    }
    LOG(ERROR) << "Using Device_id=" << device_id;
    Caffe::SetDevice(device_id);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(ERROR) << "Using CPU";
    Caffe::set_mode(Caffe::CPU);
  }

  arg_pos = 0;  // the name of the executable
  std::string pretrained_binary_proto(argv[++arg_pos]);

  // Expected prototxt contains at least one data layer such as
  //  the layer data_layer_name and one feature blob such as the
  //  fc7 top blob to extract features.
  /*
   layers {
     name: "data_layer_name"
     type: DATA
     data_param {
       source: "/path/to/your/images/to/extract/feature/images_leveldb"
       mean_file: "/path/to/your/image_mean.binaryproto"
       batch_size: 128
       crop_size: 227
       mirror: false
     }
     top: "data_blob_name"
     top: "label_blob_name"
   }
   layers {
     name: "drop7"
     type: DROPOUT
     dropout_param {
       dropout_ratio: 0.5
     }
     bottom: "fc7"
     top: "fc7"
   }
   */
  std::string feature_extraction_proto(argv[++arg_pos]);
  shared_ptr<Net<Dtype> > feature_extraction_net(
      new Net<Dtype>(feature_extraction_proto, caffe::TEST));
  feature_extraction_net->CopyTrainedLayersFrom(pretrained_binary_proto);

  std::string extract_feature_blob_names(argv[++arg_pos]);
  std::vector<std::string> blob_names;
  boost::split(blob_names, extract_feature_blob_names, boost::is_any_of(","));

  std::string save_feature_dataset_names(argv[++arg_pos]);
  std::vector<std::string> dataset_names;
  boost::split(dataset_names, save_feature_dataset_names,
               boost::is_any_of(","));
  CHECK_EQ(blob_names.size(), dataset_names.size()) <<
      " the number of blob names and dataset names must be equal";
  size_t num_features = blob_names.size();

  for (size_t i = 0; i < num_features; i++) {
    CHECK(feature_extraction_net->has_blob(blob_names[i]))
        << "Unknown feature blob name " << blob_names[i]
        << " in the network " << feature_extraction_proto;
  }

  int num_mini_batches = atoi(argv[++arg_pos]);

  std::vector<shared_ptr<db::DB> > feature_dbs;
  std::vector<shared_ptr<db::Transaction> > txns;
  for (size_t i = 0; i < num_features; ++i) {
    LOG(INFO)<< "Opening dataset " << dataset_names[i];
    shared_ptr<db::DB> db(db::GetDB(argv[++arg_pos]));
    db->Open(dataset_names.at(i), db::NEW);
    feature_dbs.push_back(db);
    shared_ptr<db::Transaction> txn(db->NewTransaction());
    txns.push_back(txn);
  }

  LOG(ERROR)<< "Extacting Features";

  Datum datum;
  const int kMaxKeyStrLength = 100;
  char key_str[kMaxKeyStrLength];
  std::vector<Blob<float>*> input_vec;
  std::vector<int> image_indices(num_features, 0);
  for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) {
    feature_extraction_net->Forward(input_vec);
    for (int i = 0; i < num_features; ++i) {
      const shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net
          ->blob_by_name(blob_names[i]);
      int batch_size = feature_blob->num();
      int dim_features = feature_blob->count() / batch_size;
      const Dtype* feature_blob_data;
      for (int n = 0; n < batch_size; ++n) {
        datum.set_height(feature_blob->height());
        datum.set_width(feature_blob->width());
        datum.set_channels(feature_blob->channels());
        datum.clear_data();
        datum.clear_float_data();
        feature_blob_data = feature_blob->cpu_data() +
            feature_blob->offset(n);
        for (int d = 0; d < dim_features; ++d) {
          datum.add_float_data(feature_blob_data[d]);
        }
        int length = snprintf(key_str, kMaxKeyStrLength, "%010d",
            image_indices[i]);
        string out;
        CHECK(datum.SerializeToString(&out));
        txns.at(i)->Put(std::string(key_str, length), out);
        ++image_indices[i];
        if (image_indices[i] % 1000 == 0) {
          txns.at(i)->Commit();
          txns.at(i).reset(feature_dbs.at(i)->NewTransaction());
          LOG(ERROR)<< "Extracted features of " << image_indices[i] <<
              " query images for feature blob " << blob_names[i];
        }
      }  // for (int n = 0; n < batch_size; ++n)
    }  // for (int i = 0; i < num_features; ++i)
  }  // for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index)
  // write the last batch
  for (int i = 0; i < num_features; ++i) {
    if (image_indices[i] % 1000 != 0) {
      txns.at(i)->Commit();
    }
    LOG(ERROR)<< "Extracted features of " << image_indices[i] <<
        " query images for feature blob " << blob_names[i];
    feature_dbs.at(i)->Close();
  }

  LOG(ERROR)<< "Successfully extracted the features!";
  return 0;
}

<commit_msg>fix the bug with db_type when the number of features to be extracted is larger than 1<commit_after>#include <stdio.h>  // for snprintf
#include <string>
#include <vector>

#include "boost/algorithm/string.hpp"
#include "google/protobuf/text_format.h"

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/net.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/db.hpp"
#include "caffe/util/io.hpp"
#include "caffe/vision_layers.hpp"

using caffe::Blob;
using caffe::Caffe;
using caffe::Datum;
using caffe::Net;
using boost::shared_ptr;
using std::string;
namespace db = caffe::db;

template<typename Dtype>
int feature_extraction_pipeline(int argc, char** argv);

int main(int argc, char** argv) {
  return feature_extraction_pipeline<float>(argc, argv);
//  return feature_extraction_pipeline<double>(argc, argv);
}

template<typename Dtype>
int feature_extraction_pipeline(int argc, char** argv) {
  ::google::InitGoogleLogging(argv[0]);
  const int num_required_args = 7;
  if (argc < num_required_args) {
    LOG(ERROR)<<
    "This program takes in a trained network and an input data layer, and then"
    " extract features of the input data produced by the net.\n"
    "Usage: extract_features  pretrained_net_param"
    "  feature_extraction_proto_file  extract_feature_blob_name1[,name2,...]"
    "  save_feature_dataset_name1[,name2,...]  num_mini_batches  db_type"
    "  [CPU/GPU] [DEVICE_ID=0]\n"
    "Note: you can extract multiple features in one pass by specifying"
    " multiple feature blob names and dataset names seperated by ','."
    " The names cannot contain white space characters and the number of blobs"
    " and datasets must be equal.";
    return 1;
  }
  int arg_pos = num_required_args;

  arg_pos = num_required_args;
  if (argc > arg_pos && strcmp(argv[arg_pos], "GPU") == 0) {
    LOG(ERROR)<< "Using GPU";
    uint device_id = 0;
    if (argc > arg_pos + 1) {
      device_id = atoi(argv[arg_pos + 1]);
      CHECK_GE(device_id, 0);
    }
    LOG(ERROR) << "Using Device_id=" << device_id;
    Caffe::SetDevice(device_id);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(ERROR) << "Using CPU";
    Caffe::set_mode(Caffe::CPU);
  }

  arg_pos = 0;  // the name of the executable
  std::string pretrained_binary_proto(argv[++arg_pos]);

  // Expected prototxt contains at least one data layer such as
  //  the layer data_layer_name and one feature blob such as the
  //  fc7 top blob to extract features.
  /*
   layers {
     name: "data_layer_name"
     type: DATA
     data_param {
       source: "/path/to/your/images/to/extract/feature/images_leveldb"
       mean_file: "/path/to/your/image_mean.binaryproto"
       batch_size: 128
       crop_size: 227
       mirror: false
     }
     top: "data_blob_name"
     top: "label_blob_name"
   }
   layers {
     name: "drop7"
     type: DROPOUT
     dropout_param {
       dropout_ratio: 0.5
     }
     bottom: "fc7"
     top: "fc7"
   }
   */
  std::string feature_extraction_proto(argv[++arg_pos]);
  shared_ptr<Net<Dtype> > feature_extraction_net(
      new Net<Dtype>(feature_extraction_proto, caffe::TEST));
  feature_extraction_net->CopyTrainedLayersFrom(pretrained_binary_proto);

  std::string extract_feature_blob_names(argv[++arg_pos]);
  std::vector<std::string> blob_names;
  boost::split(blob_names, extract_feature_blob_names, boost::is_any_of(","));

  std::string save_feature_dataset_names(argv[++arg_pos]);
  std::vector<std::string> dataset_names;
  boost::split(dataset_names, save_feature_dataset_names,
               boost::is_any_of(","));
  CHECK_EQ(blob_names.size(), dataset_names.size()) <<
      " the number of blob names and dataset names must be equal";
  size_t num_features = blob_names.size();

  for (size_t i = 0; i < num_features; i++) {
    CHECK(feature_extraction_net->has_blob(blob_names[i]))
        << "Unknown feature blob name " << blob_names[i]
        << " in the network " << feature_extraction_proto;
  }

  int num_mini_batches = atoi(argv[++arg_pos]);

  std::vector<shared_ptr<db::DB> > feature_dbs;
  std::vector<shared_ptr<db::Transaction> > txns;
  const char* db_type = argv[++arg_pos];
  for (size_t i = 0; i < num_features; ++i) {
    LOG(INFO)<< "Opening dataset " << dataset_names[i];
    shared_ptr<db::DB> db(db::GetDB(db_type));
    db->Open(dataset_names.at(i), db::NEW);
    feature_dbs.push_back(db);
    shared_ptr<db::Transaction> txn(db->NewTransaction());
    txns.push_back(txn);
  }

  LOG(ERROR)<< "Extacting Features";

  Datum datum;
  const int kMaxKeyStrLength = 100;
  char key_str[kMaxKeyStrLength];
  std::vector<Blob<float>*> input_vec;
  std::vector<int> image_indices(num_features, 0);
  for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) {
    feature_extraction_net->Forward(input_vec);
    for (int i = 0; i < num_features; ++i) {
      const shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net
          ->blob_by_name(blob_names[i]);
      int batch_size = feature_blob->num();
      int dim_features = feature_blob->count() / batch_size;
      const Dtype* feature_blob_data;
      for (int n = 0; n < batch_size; ++n) {
        datum.set_height(feature_blob->height());
        datum.set_width(feature_blob->width());
        datum.set_channels(feature_blob->channels());
        datum.clear_data();
        datum.clear_float_data();
        feature_blob_data = feature_blob->cpu_data() +
            feature_blob->offset(n);
        for (int d = 0; d < dim_features; ++d) {
          datum.add_float_data(feature_blob_data[d]);
        }
        int length = snprintf(key_str, kMaxKeyStrLength, "%010d",
            image_indices[i]);
        string out;
        CHECK(datum.SerializeToString(&out));
        txns.at(i)->Put(std::string(key_str, length), out);
        ++image_indices[i];
        if (image_indices[i] % 1000 == 0) {
          txns.at(i)->Commit();
          txns.at(i).reset(feature_dbs.at(i)->NewTransaction());
          LOG(ERROR)<< "Extracted features of " << image_indices[i] <<
              " query images for feature blob " << blob_names[i];
        }
      }  // for (int n = 0; n < batch_size; ++n)
    }  // for (int i = 0; i < num_features; ++i)
  }  // for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index)
  // write the last batch
  for (int i = 0; i < num_features; ++i) {
    if (image_indices[i] % 1000 != 0) {
      txns.at(i)->Commit();
    }
    LOG(ERROR)<< "Extracted features of " << image_indices[i] <<
        " query images for feature blob " << blob_names[i];
    feature_dbs.at(i)->Close();
  }

  LOG(ERROR)<< "Successfully extracted the features!";
  return 0;
}

<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2021 Lalit Sharma <lsharma@quicklogic.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */
#include "kernel/celltypes.h"
#include "kernel/log.h"
#include "kernel/register.h"
#include "kernel/rtlil.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SynthQuickLogicPass : public ScriptPass {

    SynthQuickLogicPass() : ScriptPass("synth_quicklogic", "Synthesis for QuickLogic FPGAs") {}

    void help() override
    {
        log("\n");
        log("   synth_quicklogic [options]\n");
        log("This command runs synthesis for QuickLogic FPGAs\n");
        log("\n");
        log("    -top <module>\n");
        log("         use the specified module as top module\n");
        log("\n");
        log("    -family <family>\n");
        log("        run synthesis for the specified QuickLogic architecture\n");
        log("        generate the synthesis netlist for the specified family.\n");
        log("        supported values:\n");
        log("        - qlf_k4n8 : qlf_k4n8 \n");
        log("        - qlf_k6n10: qlf_k6n10 \n");
        log("\n");
        log("    -no_abc_opt\n");
        log("        By default most of ABC logic optimization features is\n");
        log("        enabled. Specifying this switch turns them off.\n");
        log("\n");
        log("    -edif <file>\n");
        log("        write the design to the specified edif file. writing of an output file\n");
        log("        is omitted if this parameter is not specified.\n");
        log("\n");
        log("    -blif <file>\n");
        log("        write the design to the specified BLIF file. writing of an output file\n");
        log("        is omitted if this parameter is not specified.\n");
        log("\n");
        log("    -verilog <file>\n");
        log("        write the design to the specified verilog file. writing of an output file\n");
        log("        is omitted if this parameter is not specified.\n");
        log("\n");
        log("    -no_adder\n");
        log("        By default use adder cells in output netlist.\n");
        log("        Specifying this switch turns it off.\n");
        log("\n");
        log("    -no_bram\n");
        log("        By default use Block RAM in output netlist.\n");
        log("        Specifying this switch turns it off.\n");
        log("\n");
        log("    -no_ff_map\n");
        log("        By default ff techmap is turned on. Specifying this switch turns it off.\n");
        log("\n");
        log("\n");
        log("The following commands are executed by this synthesis command:\n");
        help_script();
        log("\n");
    }

    string top_opt, edif_file, blif_file, family, currmodule, verilog_file;
    bool inferAdder;
    bool inferBram;
    bool abcOpt;
    bool noffmap;

    void clear_flags() override
    {
        top_opt = "-auto-top";
        edif_file = "";
        blif_file = "";
        verilog_file = "";
        currmodule = "";
        family = "qlf_k4n8";
        inferAdder = true;
        inferBram = true;
        abcOpt = true;
        noffmap = false;
    }

    void execute(std::vector<std::string> args, RTLIL::Design *design) override
    {
        string run_from, run_to;
        clear_flags();

        size_t argidx;
        for (argidx = 1; argidx < args.size(); argidx++) {
            if (args[argidx] == "-top" && argidx + 1 < args.size()) {
                top_opt = "-top " + args[++argidx];
                continue;
            }
            if (args[argidx] == "-edif" && argidx + 1 < args.size()) {
                edif_file = args[++argidx];
                continue;
            }

            if (args[argidx] == "-family" && argidx + 1 < args.size()) {
                family = args[++argidx];
                continue;
            }
            if (args[argidx] == "-blif" && argidx + 1 < args.size()) {
                blif_file = args[++argidx];
                continue;
            }
            if (args[argidx] == "-verilog" && argidx + 1 < args.size()) {
                verilog_file = args[++argidx];
                continue;
            }
            if (args[argidx] == "-no_adder") {
                inferAdder = false;
                continue;
            }
            if (args[argidx] == "-no_bram") {
                inferBram = false;
                continue;
            }
            if (args[argidx] == "-no_abc_opt") {
                abcOpt = false;
                continue;
            }
            if (args[argidx] == "-no_ff_map") {
                noffmap = true;
                continue;
            }

            break;
        }
        extra_args(args, argidx, design);

        if (!design->full_selection())
            log_cmd_error("This command only operates on fully selected designs!\n");

        log_header(design, "Executing SYNTH_QUICKLOGIC pass.\n");
        log_push();

        run_script(design, run_from, run_to);

        log_pop();
    }

    void script() override
    {
        if (check_label("begin")) {
            std::string readVelArgs;
            readVelArgs = " +/quicklogic/" + family + "_cells_sim.v";

            run("read_verilog -lib -specify +/quicklogic/cells_sim.v" + readVelArgs);
            run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str()));
        }

        if (check_label("prepare")) {
            run("proc");
            run("flatten");
            run("opt_expr");
            run("opt_clean");
            run("deminout");
            run("opt");
        }

        if (check_label("coarse")) {
            run("opt_expr");
            run("opt_clean");
            run("check");
            run("opt");
            run("wreduce -keepdc");
            run("peepopt");
            run("pmuxtree");
            run("opt_clean");

            run("alumacc");
            run("opt");
            run("fsm");
            run("opt -fast");
            run("memory -nomap");
            run("opt_clean");
        }

        if (check_label("map_bram", "(skip if -no_bram)") && family == "qlf_k6n10" && inferBram) {
            run("memory_bram -rules +/quicklogic/" + family + "_brams.txt");
            run("techmap -map +/quicklogic/" + family + "_brams_map.v");
        }

        if (check_label("map_ffram")) {
            run("opt -fast -mux_undef -undriven -fine");
            run("memory_map -iattr -attr !ram_block -attr !rom_block -attr logic_block "
                "-attr syn_ramstyle=auto -attr syn_ramstyle=registers "
                "-attr syn_romstyle=auto -attr syn_romstyle=logic");
            run("opt -undriven -fine");
        }

        if (check_label("map_gates")) {
            if (inferAdder) {
                run("techmap -map +/techmap.v -map +/quicklogic/" + family + "_arith_map.v");
            } else {
                run("techmap");
            }
            run("opt -fast");
            run("opt_expr");
            run("opt_merge");
            run("opt_clean");
            run("opt");
        }

        if (check_label("map_ffs")) {
            if (family == "qlf_k4n8") {
                run("shregmap -minlen 8 -maxlen 8");
            }
            if (family == "qlf_k6n10") {
                run("dfflegalize -cell $_DFF_P_ 0 -cell $_DFF_PP?_ 0 -cell $_DFFE_PP?P_ 0 -cell $_DFFSR_PPP_ 0 -cell $_DFFSRE_PPPP_ 0 -cell "
                    "$_DLATCHSR_PPP_ 0");
                //    In case we add clock inversion in the future.
                //    run("dfflegalize -cell $_DFF_?_ 0 -cell $_DFF_?P?_ 0 -cell $_DFFE_?P?P_ 0 -cell $_DFFSR_?PP_ 0 -cell $_DFFSRE_?PPP_ 0 -cell
                //    $_DLATCH_PPP_ 0");
            } else {
                run("dfflegalize -cell $_DFF_P_ 0 -cell $_DFF_P??_ 0 -cell $_DFF_N_ 0 -cell $_DFF_N??_ 0 -cell $_DFFSR_???_ 0");
            }
            std::string techMapArgs = " -map +/techmap.v -map +/quicklogic/" + family + "_ffs_map.v";
            if (!noffmap) {
                run("techmap " + techMapArgs);
            }
            run("opt_merge");
            run("opt_clean");
            run("opt");
        }

        if (check_label("map_luts")) {
            if(abcOpt) {
                if (family == "qlf_k6n10") {
                    run("abc -lut 6 ");
                } else {
                    run("abc -lut 4 ");
                }
            }
            run("clean");
            run("opt_lut");
        }

        if (check_label("map_cells") && family == "qlf_k6n10") {
            std::string techMapArgs;
            techMapArgs = "-map +/quicklogic/" + family + "_lut_map.v";
            run("techmap " + techMapArgs);
            run("clean");
        }

        if (check_label("check")) {
            run("autoname");
            run("hierarchy -check");
            run("stat");
            run("check -noinit");
        }

        if (check_label("finalize")) {
            run("check");
            run("opt_clean -purge");
        }

        if (check_label("edif")) {
            if (!edif_file.empty())
                run(stringf("write_edif -nogndvcc -attrprop -pvector par %s %s", this->currmodule.c_str(), edif_file.c_str()));
        }

        if (check_label("blif")) {
            if (!blif_file.empty()) {
                if (inferAdder) {
                    run(stringf("write_blif -param %s", help_mode ? "<file-name>" : blif_file.c_str()));
                } else {
                    run(stringf("write_blif %s", help_mode ? "<file-name>" : blif_file.c_str()));
                }
            }
        }

        if (check_label("verilog")) {
            if (!verilog_file.empty()) {
                run("write_verilog -noattr -nohex " + verilog_file);
            }
        }
    }

} SynthQuicklogicPass;

PRIVATE_NAMESPACE_END
<commit_msg>Updating formatting for newly added statement<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2021 Lalit Sharma <lsharma@quicklogic.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */
#include "kernel/celltypes.h"
#include "kernel/log.h"
#include "kernel/register.h"
#include "kernel/rtlil.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SynthQuickLogicPass : public ScriptPass {

    SynthQuickLogicPass() : ScriptPass("synth_quicklogic", "Synthesis for QuickLogic FPGAs") {}

    void help() override
    {
        log("\n");
        log("   synth_quicklogic [options]\n");
        log("This command runs synthesis for QuickLogic FPGAs\n");
        log("\n");
        log("    -top <module>\n");
        log("         use the specified module as top module\n");
        log("\n");
        log("    -family <family>\n");
        log("        run synthesis for the specified QuickLogic architecture\n");
        log("        generate the synthesis netlist for the specified family.\n");
        log("        supported values:\n");
        log("        - qlf_k4n8 : qlf_k4n8 \n");
        log("        - qlf_k6n10: qlf_k6n10 \n");
        log("\n");
        log("    -no_abc_opt\n");
        log("        By default most of ABC logic optimization features is\n");
        log("        enabled. Specifying this switch turns them off.\n");
        log("\n");
        log("    -edif <file>\n");
        log("        write the design to the specified edif file. writing of an output file\n");
        log("        is omitted if this parameter is not specified.\n");
        log("\n");
        log("    -blif <file>\n");
        log("        write the design to the specified BLIF file. writing of an output file\n");
        log("        is omitted if this parameter is not specified.\n");
        log("\n");
        log("    -verilog <file>\n");
        log("        write the design to the specified verilog file. writing of an output file\n");
        log("        is omitted if this parameter is not specified.\n");
        log("\n");
        log("    -no_adder\n");
        log("        By default use adder cells in output netlist.\n");
        log("        Specifying this switch turns it off.\n");
        log("\n");
        log("    -no_bram\n");
        log("        By default use Block RAM in output netlist.\n");
        log("        Specifying this switch turns it off.\n");
        log("\n");
        log("    -no_ff_map\n");
        log("        By default ff techmap is turned on. Specifying this switch turns it off.\n");
        log("\n");
        log("\n");
        log("The following commands are executed by this synthesis command:\n");
        help_script();
        log("\n");
    }

    string top_opt, edif_file, blif_file, family, currmodule, verilog_file;
    bool inferAdder;
    bool inferBram;
    bool abcOpt;
    bool noffmap;

    void clear_flags() override
    {
        top_opt = "-auto-top";
        edif_file = "";
        blif_file = "";
        verilog_file = "";
        currmodule = "";
        family = "qlf_k4n8";
        inferAdder = true;
        inferBram = true;
        abcOpt = true;
        noffmap = false;
    }

    void execute(std::vector<std::string> args, RTLIL::Design *design) override
    {
        string run_from, run_to;
        clear_flags();

        size_t argidx;
        for (argidx = 1; argidx < args.size(); argidx++) {
            if (args[argidx] == "-top" && argidx + 1 < args.size()) {
                top_opt = "-top " + args[++argidx];
                continue;
            }
            if (args[argidx] == "-edif" && argidx + 1 < args.size()) {
                edif_file = args[++argidx];
                continue;
            }

            if (args[argidx] == "-family" && argidx + 1 < args.size()) {
                family = args[++argidx];
                continue;
            }
            if (args[argidx] == "-blif" && argidx + 1 < args.size()) {
                blif_file = args[++argidx];
                continue;
            }
            if (args[argidx] == "-verilog" && argidx + 1 < args.size()) {
                verilog_file = args[++argidx];
                continue;
            }
            if (args[argidx] == "-no_adder") {
                inferAdder = false;
                continue;
            }
            if (args[argidx] == "-no_bram") {
                inferBram = false;
                continue;
            }
            if (args[argidx] == "-no_abc_opt") {
                abcOpt = false;
                continue;
            }
            if (args[argidx] == "-no_ff_map") {
                noffmap = true;
                continue;
            }

            break;
        }
        extra_args(args, argidx, design);

        if (!design->full_selection())
            log_cmd_error("This command only operates on fully selected designs!\n");

        log_header(design, "Executing SYNTH_QUICKLOGIC pass.\n");
        log_push();

        run_script(design, run_from, run_to);

        log_pop();
    }

    void script() override
    {
        if (check_label("begin")) {
            std::string readVelArgs;
            readVelArgs = " +/quicklogic/" + family + "_cells_sim.v";

            run("read_verilog -lib -specify +/quicklogic/cells_sim.v" + readVelArgs);
            run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str()));
        }

        if (check_label("prepare")) {
            run("proc");
            run("flatten");
            run("opt_expr");
            run("opt_clean");
            run("deminout");
            run("opt");
        }

        if (check_label("coarse")) {
            run("opt_expr");
            run("opt_clean");
            run("check");
            run("opt");
            run("wreduce -keepdc");
            run("peepopt");
            run("pmuxtree");
            run("opt_clean");

            run("alumacc");
            run("opt");
            run("fsm");
            run("opt -fast");
            run("memory -nomap");
            run("opt_clean");
        }

        if (check_label("map_bram", "(skip if -no_bram)") && family == "qlf_k6n10" && inferBram) {
            run("memory_bram -rules +/quicklogic/" + family + "_brams.txt");
            run("techmap -map +/quicklogic/" + family + "_brams_map.v");
        }

        if (check_label("map_ffram")) {
            run("opt -fast -mux_undef -undriven -fine");
            run("memory_map -iattr -attr !ram_block -attr !rom_block -attr logic_block "
                "-attr syn_ramstyle=auto -attr syn_ramstyle=registers "
                "-attr syn_romstyle=auto -attr syn_romstyle=logic");
            run("opt -undriven -fine");
        }

        if (check_label("map_gates")) {
            if (inferAdder) {
                run("techmap -map +/techmap.v -map +/quicklogic/" + family + "_arith_map.v");
            } else {
                run("techmap");
            }
            run("opt -fast");
            run("opt_expr");
            run("opt_merge");
            run("opt_clean");
            run("opt");
        }

        if (check_label("map_ffs")) {
            if (family == "qlf_k4n8") {
                run("shregmap -minlen 8 -maxlen 8");
            }
            if (family == "qlf_k6n10") {
                run("dfflegalize -cell $_DFF_P_ 0 -cell $_DFF_PP?_ 0 -cell $_DFFE_PP?P_ 0 -cell $_DFFSR_PPP_ 0 -cell $_DFFSRE_PPPP_ 0 -cell "
                    "$_DLATCHSR_PPP_ 0");
                //    In case we add clock inversion in the future.
                //    run("dfflegalize -cell $_DFF_?_ 0 -cell $_DFF_?P?_ 0 -cell $_DFFE_?P?P_ 0 -cell $_DFFSR_?PP_ 0 -cell $_DFFSRE_?PPP_ 0 -cell
                //    $_DLATCH_PPP_ 0");
            } else {
                run("dfflegalize -cell $_DFF_P_ 0 -cell $_DFF_P??_ 0 -cell $_DFF_N_ 0 -cell $_DFF_N??_ 0 -cell $_DFFSR_???_ 0");
            }
            std::string techMapArgs = " -map +/techmap.v -map +/quicklogic/" + family + "_ffs_map.v";
            if (!noffmap) {
                run("techmap " + techMapArgs);
            }
            run("opt_merge");
            run("opt_clean");
            run("opt");
        }

        if (check_label("map_luts")) {
            if (abcOpt) {
                if (family == "qlf_k6n10") {
                    run("abc -lut 6 ");
                } else {
                    run("abc -lut 4 ");
                }
            }
            run("clean");
            run("opt_lut");
        }

        if (check_label("map_cells") && family == "qlf_k6n10") {
            std::string techMapArgs;
            techMapArgs = "-map +/quicklogic/" + family + "_lut_map.v";
            run("techmap " + techMapArgs);
            run("clean");
        }

        if (check_label("check")) {
            run("autoname");
            run("hierarchy -check");
            run("stat");
            run("check -noinit");
        }

        if (check_label("finalize")) {
            run("check");
            run("opt_clean -purge");
        }

        if (check_label("edif")) {
            if (!edif_file.empty())
                run(stringf("write_edif -nogndvcc -attrprop -pvector par %s %s", this->currmodule.c_str(), edif_file.c_str()));
        }

        if (check_label("blif")) {
            if (!blif_file.empty()) {
                if (inferAdder) {
                    run(stringf("write_blif -param %s", help_mode ? "<file-name>" : blif_file.c_str()));
                } else {
                    run(stringf("write_blif %s", help_mode ? "<file-name>" : blif_file.c_str()));
                }
            }
        }

        if (check_label("verilog")) {
            if (!verilog_file.empty()) {
                run("write_verilog -noattr -nohex " + verilog_file);
            }
        }
    }

} SynthQuicklogicPass;

PRIVATE_NAMESPACE_END
<|endoftext|>


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

#include <GLES2/gl2.h>

#include "gpu/demos/framework/demo.h"
#include "gpu/demos/framework/demo_factory.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/size.h"
#include "ppapi/cpp/dev/context_3d_dev.h"
#include "ppapi/cpp/dev/graphics_3d_dev.h"
#include "ppapi/cpp/dev/surface_3d_dev.h"
#include "ppapi/lib/gl/gles2/gl2ext_ppapi.h"

namespace gpu {
namespace demos {

class PluginInstance : public pp::Instance {
 public:
  PluginInstance(PP_Instance instance, pp::Module* module)
      : pp::Instance(instance),
        module_(module),
        demo_(CreateDemo()),
        swap_pending_(false),
        paint_needed_(false) {
    // Set the callback object outside of the initializer list to avoid a
    // compiler warning about using "this" in an initializer list.
    callback_factory_.Initialize(this);
  }

  ~PluginInstance() {
    if (!context_.is_null()) {
      glSetCurrentContextPPAPI(context_.pp_resource());
      delete demo_;
      glSetCurrentContextPPAPI(0);
    }
  }

  virtual void DidChangeView(const pp::Rect& position,
                             const pp::Rect& /*clip*/) {
    if (size_ == position.size())
      return;

    size_ = position.size();
    demo_->InitWindowSize(size_.width(), size_.height());

    if (context_.is_null()) {
      context_ = pp::Context3D_Dev(*this, 0, pp::Context3D_Dev(), NULL);
      if (context_.is_null())
        return;

      glSetCurrentContextPPAPI(context_.pp_resource());
      demo_->InitGL();
      glSetCurrentContextPPAPI(0);
    } else {
      // Need to recreate surface. Unbind existing surface.
      pp::Instance::BindGraphics(pp::Surface3D_Dev());
      context_.BindSurfaces(pp::Surface3D_Dev(), pp::Surface3D_Dev());
    }
    surface_ = pp::Surface3D_Dev(*this, 0, NULL);
    context_.BindSurfaces(surface_, surface_);
    pp::Instance::BindGraphics(surface_);

    Paint();
  }

  void Paint() {
    if (swap_pending_) {
      // A swap is pending. Delay paint until swap finishes.
      paint_needed_ = true;
      return;
    }
    glSetCurrentContextPPAPI(context_.pp_resource());
    demo_->Draw();
    swap_pending_ = true;
    surface_.SwapBuffers(
        callback_factory_.NewCallback(&PluginInstance::OnSwap));
    glSetCurrentContextPPAPI(0);
  }

 private:
  void OnSwap(int32_t) {
    swap_pending_ = false;
    if (paint_needed_ || demo_->IsAnimated()) {
      paint_needed_ = false;
      Paint();
    }
  }

  pp::Module* module_;
  Demo* demo_;
  pp::Context3D_Dev context_;
  pp::Surface3D_Dev surface_;
  pp::Size size_;
  bool swap_pending_;
  bool paint_needed_;
  pp::CompletionCallbackFactory<PluginInstance> callback_factory_;
};

class PluginModule : public pp::Module {
 public:
  PluginModule() {}
  ~PluginModule() {
    glTerminatePPAPI();
  }

  virtual bool Init() {
    return glInitializePPAPI(get_browser_interface()) == GL_TRUE ? true : false;
  }

  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new PluginInstance(instance, this);
  }
};

}  // namespace demos
}  // namespace gpu

namespace pp {

Module* CreateModule() {
  return new gpu::demos::PluginModule();
}

}  // namespace pp

<commit_msg>Reland r93090, which was reverted in r93104.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <GLES2/gl2.h>

#include "gpu/demos/framework/demo.h"
#include "gpu/demos/framework/demo_factory.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/size.h"
#include "ppapi/cpp/dev/graphics_3d_dev.h"
#include "ppapi/lib/gl/gles2/gl2ext_ppapi.h"

namespace gpu {
namespace demos {

class PluginInstance : public pp::Instance {
 public:
  PluginInstance(PP_Instance instance, pp::Module* module)
      : pp::Instance(instance),
        module_(module),
        demo_(CreateDemo()),
        swap_pending_(false),
        paint_needed_(false) {
    // Set the callback object outside of the initializer list to avoid a
    // compiler warning about using "this" in an initializer list.
    callback_factory_.Initialize(this);
  }

  ~PluginInstance() {
    if (!context_.is_null()) {
      glSetCurrentContextPPAPI(context_.pp_resource());
      delete demo_;
      glSetCurrentContextPPAPI(0);
    }
  }

  virtual void DidChangeView(const pp::Rect& position,
                             const pp::Rect& /*clip*/) {
    if (size_ == position.size())
      return;

    size_ = position.size();
    demo_->InitWindowSize(size_.width(), size_.height());

    if (context_.is_null()) {
      context_ = pp::Graphics3D_Dev(*this, 0, pp::Graphics3D_Dev(), NULL);
      if (context_.is_null())
        return;

      pp::Instance::BindGraphics(context_);
      glSetCurrentContextPPAPI(context_.pp_resource());
      demo_->InitGL();
      glSetCurrentContextPPAPI(0);
    }

    Paint();
  }

  void Paint() {
    if (swap_pending_) {
      // A swap is pending. Delay paint until swap finishes.
      paint_needed_ = true;
      return;
    }
    glSetCurrentContextPPAPI(context_.pp_resource());
    demo_->Draw();
    swap_pending_ = true;
    context_.SwapBuffers(
        callback_factory_.NewCallback(&PluginInstance::OnSwap));
    glSetCurrentContextPPAPI(0);
  }

 private:
  void OnSwap(int32_t) {
    swap_pending_ = false;
    if (paint_needed_ || demo_->IsAnimated()) {
      paint_needed_ = false;
      Paint();
    }
  }

  pp::Module* module_;
  Demo* demo_;
  pp::Graphics3D_Dev context_;
  pp::Size size_;
  bool swap_pending_;
  bool paint_needed_;
  pp::CompletionCallbackFactory<PluginInstance> callback_factory_;
};

class PluginModule : public pp::Module {
 public:
  PluginModule() {}
  ~PluginModule() {
    glTerminatePPAPI();
  }

  virtual bool Init() {
    return glInitializePPAPI(get_browser_interface()) == GL_TRUE ? true : false;
  }

  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new PluginInstance(instance, this);
  }
};

}  // namespace demos
}  // namespace gpu

namespace pp {

Module* CreateModule() {
  return new gpu::demos::PluginModule();
}

}  // namespace pp

<|endoftext|>