<commit_before>#include "betweenness_centrality.hpp"
#include <cassert>
#include <queue>
#include <algorithm>
using namespace std;

namespace betweenness_centrality {
  void BetweennessCentralityBase::BuildGraph(const vector<pair<int, int> > &es){
    vertex2id.clear();
    G[0].clear();
    G[1].clear();

    V = 0;
    E = es.size();
    for (const auto &e : es){
      if (vertex2id.count(e.fst) == 0) vertex2id[e.fst] = V++;
      if (vertex2id.count(e.snd) == 0) vertex2id[e.snd] = V++;
    }
    G[0].resize(V);
    G[1].resize(V);
    for (const auto &e : es){
      G[0][vertex2id[e.fst]].push_back(vertex2id[e.snd]);
      G[1][vertex2id[e.snd]].push_back(vertex2id[e.fst]);
    }
  }

  void BetweennessCentralityNaive::PreCompute(const vector<pair<int, int> > &es) {
    BuildGraph(es);
    centrality_map = vector<double>(V, 0);
    const auto &forward_adj = G[0];

    for (int s = 0; (size_t)s < V; s++){
      // Brandes' algorithm (2001)
      // Step1. Compute distance and the number of shortest paths from s. O(m) time.
      vector<int>    distance(V, -1);
      vector<double> num_paths(V, 0);
      vector<double> delta(V, 0);
      vector<int>    order;
      queue<int>     que;

      distance[s] = 0;
      num_paths[s] = 1;
      que.push(s);

      while (!que.empty()){
        int v = que.front(); que.pop(); order.push_back(v);
        for (int w : forward_adj[v]){
          if (distance[w] == -1){
            distance[w] = distance[v] + 1;;
            que.push(w);
          }

          if (distance[w] == distance[v] + 1){
            num_paths[w] += num_paths[v];
          }
        }
      }

      // Step2. Aggregate betweenness centrality values. O(m) time.
      reverse(order.begin(), order.end());
      for (int v : order){
        for (int w : forward_adj[v]){
          if (distance[w] == distance[v] + 1 && num_paths[w] > 0){
            delta[v] += num_paths[v] / num_paths[w];
            delta[v] += num_paths[v] / num_paths[w] * delta[w];
          }
        }
      }
      for (int t = 0; (size_t)t < V; t++){
        if (s != t) centrality_map[t] += delta[t];
      }
    }
  }

  // void BetweennessCentrality::Index::
  // calcPaths(int s, const vector<IVec> &dag, DVec &num_ps){
  //   assert(num_ps.size() == dag.size() && 0 <= s && s < int(dag.size()));
  //   fill(num_ps.begin(), num_ps.end(), 0);
  //   queue<int> que;
  //   num_ps[s] = 1;
  //   que.push(s);

  //   while (!que.empty()){
  //     int v = que.front(); que.pop();
  //     for (int w : dag[v]){  // dag[v]は最短路DAGの辺なので距離のチェックは不要
  //       if (num_ps[w] < EPS) que.push(w);
  //       num_ps[w] += num_ps[v];
  //     }
  //   }
  // }

  // inline double StaticSketch::Index::getWeight(int id) const {
  //   if (0 <= id && id < int(id_to_vertex.size()) && id != sources[0] && id != sources[1]){
  //     return num_ps[0][id] / num_total_paths * num_ps[1][id];
  //   } else {
  //     return 0;
  //   }
  // }

  // StaticSketch::Index::Index(int s, int t,
  //                            const vector<IVec> &dag_fadj,
  //                            const vector<IVec> &dag_badj,
  //                            const IVec &id_to_vertex)
  //   : sources({s, t}), adj({dag_fadj, dag_badj}), id_to_vertex(id_to_vertex)
  // {
  //   int n = id_to_vertex.size();
  //   // assert(s < int(adj[0].size()));

  //   REP(i, 2){
  //     num_ps[i].resize(n, 0);
  //     calcPaths(sources[i], adj[i], num_ps[i]);
  //   }

  //   double abs_error = abs(num_ps[0][t] - num_ps[1][s]);
  //   double max_abs   = max(num_ps[0][t], num_ps[1][s]);
  //   assert(max_abs < EPS || abs_error / max_abs < EPS);
  //   num_total_paths = num_ps[0][t];
  //   assert(num_total_paths < 1e100);
  //   assert(num_total_paths > 0);
  // }

  // StaticSketch::Index *StaticSketch::buildIndex(int s, int t){
  //   vector<int> &id_to_vertex = tmp_vars.id_to_vertex;
  //   vector<int> &vertex_to_id = tmp_vars.vertex_to_id;

  //   assert(id_to_vertex.empty());
  //   bidirectionalSearch(s, t);

  //   if (!id_to_vertex.empty()){
  //     vector<IVec > dag_fadj(id_to_vertex.size());
  //     vector<IVec > dag_badj(id_to_vertex.size());
  //     assert(vertex_to_id[s] != -1 && vertex_to_id[t] != -1);

  //     for (auto v : id_to_vertex){
  //       for (auto w : tmp_vars.adj[v]){
  //         dag_fadj[vertex_to_id[v]].push_back(vertex_to_id[w]);
  //         dag_badj[vertex_to_id[w]].push_back(vertex_to_id[v]);
  //       }
  //     }

  //     int s_id = vertex_to_id[s];
  //     int t_id = vertex_to_id[t];
  //     for (int v : id_to_vertex){
  //       tmp_vars.adj[v].clear();
  //       vertex_to_id[v] = -1;
  //     }
  //     for (auto v : vertex_to_id) assert(v == -1);

  //     Index *index = new Index(s_id, t_id, dag_fadj, dag_badj, id_to_vertex);
  //     id_to_vertex.clear();
  //     return index;
  //   } else {
  //     return nullptr;
  //   }
  // }

  // inline void StaticSketch::addNodeToDag(int v){
  //   if (tmp_vars.vertex_to_id[v] == -1){
  //     int id = tmp_vars.id_to_vertex.size();
  //     tmp_vars.id_to_vertex.push_back(v);
  //     tmp_vars.vertex_to_id[v] = id;
  //   }
  // }

  // inline void StaticSketch::
  // updateDag(const IVec &dist, queue<int> &que, int v, int w, bool rev){
  //   if (dist[w] != -1 && dist[w] == dist[v] - 1){
  //     if (!tmp_vars.dag_nodes[w]){
  //       tmp_vars.dag_nodes[w] = true;
  //       que.push(w);
  //       addNodeToDag(w);
  //     }

  //     if (!rev){
  //       tmp_vars.adj[w].push_back(v);
  //     } else {
  //       tmp_vars.adj[v].push_back(w);
  //     }
  //   }
  // }

  // void StaticSketch::bidirectionalSearch(int s, int t){
  //   assert(s != t);
  //   int  curr  = 0;
  //   int  next  = 2;
  //   queue<int>  que[4];
  //   vector<int> update[2];
  //   vector<int> center;

  //   que[0].push(s); tmp_vars.dist[0][s] = 0; update[0].push_back(s);
  //   que[1].push(t); tmp_vars.dist[1][t] = 0; update[1].push_back(t);

  //   while (!que[curr].empty() || !que[curr + 1].empty()){
  //     REP(i, 2){
  //       while (!que[curr + i].empty()){
  //         int v = que[curr + i].front(); que[curr + i].pop();
  //         for (int w : adj[i][v]){
  //           int &src_d = tmp_vars.dist[i    ][w];
  //           int &dst_d = tmp_vars.dist[1 - i][w];
  //           if (src_d != -1) continue;
  //           if (dst_d != -1) center.push_back(w);
  //           que[next + i].push(w);
  //           update[i].push_back(w);
  //           tmp_vars.dist[i][w] = tmp_vars.dist[i][v] + 1;
  //         }
  //       }
  //       if (!center.empty()) goto LOOP_END;
  //     }
  //     swap(curr, next);
  //   }
  // LOOP_END:
  //   tmp_vars.id_to_vertex.clear();

  //   for (int v : center) addNodeToDag(v);
  //   {
  //     queue<int> que;
  //     REP(i, 2){
  //       for (int v : center) que.push(v);
  //       while (!que.empty()){
  //         int v = que.front(); que.pop();
  //         for (int w : adj[1 - i][v]){
  //           updateDag(tmp_vars.dist[i], que, v, w, i);
  //         }
  //       }
  //     }
  //   }

  //   for (int v :tmp_vars.id_to_vertex) tmp_vars.dag_nodes[v] = false;

  //   REP(i, 2) {
  //     for (auto v : update[i]) tmp_vars.dist[i][v] = -1;
  //   }
  // }

  // void StaticSketch::init(){
  //   // adjacecy list以外のメンバ変数を初期化
  //   centrality = std::vector<double>(num_nodes, 0.0);
  //   tmp_vars.init(num_nodes);
  //   indices.clear();
  // }

  // void StaticSketch::constructSketch(){

  //   if (num_indices == -1){
  //     // test用のコード、厳密解をすべての頂点に対してサンプリングを行って求める
  //     num_indices = num_nodes * num_nodes;

  //     REP(s, num_nodes) REP(t, num_nodes){
  //       Index *e = nullptr;
  //       if (s != t && (e = buildIndex(s, t)) != nullptr){
  //         REP(j, e->getDagSize()){
  //           centrality[e->getNode(j)] += e->getWeight(j);
  //         }
  //       }
  //       indices.push_back(e);
  //     }
  //   } else {
  //     // 通常のインデックス作成
  //     REP(i, num_indices){
  //       int s = rand() % num_nodes;
  //       int t = rand() % num_nodes;
  //       Index *e = nullptr;

  //       if (s != t && (e = buildIndex(s, t)) != nullptr){
  //         REP(j, e->getDagSize()){
  //           centrality[e->getNode(j)] += e->getWeight(j);
  //         }
  //       }
  //       indices.push_back(e);
  //     }
  //   }
  // }

  // void StaticSketch::Compute(const vector<pair<int, int> > &es, int num_samples){
  //   // Only consider undirected graphs.
  //   int V = 0;
  //   for (const auto &e : es){
  //     V = max({V, e.fst + 1, e.snd + 1});
  //   }

  //   vector<vector<int> > G(V);
  //   for (const auto &e : es){
  //     G[e.fst].push_back(e.snd);
  //     G[e.snd].push_back(e.fst);
  //   }

  //   vector<vector<int> > dist(2, vector<int>(V));

  //   clear();
  //   num_nodes = computeNumNodes(es);
  //   num_indices = M;

  //   // setup adjacency lists.
  //   REP(i, 2){
  //     adj[i].resize(num_nodes);
  //   }
  //   for (auto &e : es){
  //     adj[0][e.first].push_back(e.second);
  //     adj[1][e.second].push_back(e.first);
  //   }

  //   REP(i, 2) REP(v, num_nodes){
  //     sort(ALL(adj[i][v]));
  //     make_unique<int>(adj[i][v]);
  //   }

  //   init();
  //   constructSketch();
  // }
}

<commit_msg>Remove unnecessary comments<commit_after>#include "betweenness_centrality.hpp"
#include <cassert>
#include <queue>
#include <algorithm>
using namespace std;

namespace betweenness_centrality {
  void BetweennessCentralityBase::BuildGraph(const vector<pair<int, int> > &es){
    vertex2id.clear();
    G[0].clear();
    G[1].clear();

    V = 0;
    E = es.size();
    for (const auto &e : es){
      if (vertex2id.count(e.fst) == 0) vertex2id[e.fst] = V++;
      if (vertex2id.count(e.snd) == 0) vertex2id[e.snd] = V++;
    }
    G[0].resize(V);
    G[1].resize(V);
    for (const auto &e : es){
      G[0][vertex2id[e.fst]].push_back(vertex2id[e.snd]);
      G[1][vertex2id[e.snd]].push_back(vertex2id[e.fst]);
    }
  }

  void BetweennessCentralityNaive::PreCompute(const vector<pair<int, int> > &es) {
    BuildGraph(es);
    centrality_map = vector<double>(V, 0);
    const auto &forward_adj = G[0];

    for (int s = 0; (size_t)s < V; s++){
      // Brandes' algorithm (2001)
      // Step1. Compute distance and the number of shortest paths from s. O(m) time.
      vector<int>    distance(V, -1);
      vector<double> num_paths(V, 0);
      vector<double> delta(V, 0);
      vector<int>    order;
      queue<int>     que;

      distance[s] = 0;
      num_paths[s] = 1;
      que.push(s);

      while (!que.empty()){
        int v = que.front(); que.pop(); order.push_back(v);
        for (int w : forward_adj[v]){
          if (distance[w] == -1){
            distance[w] = distance[v] + 1;;
            que.push(w);
          }

          if (distance[w] == distance[v] + 1){
            num_paths[w] += num_paths[v];
          }
        }
      }

      // Step2. Aggregate betweenness centrality values. O(m) time.
      reverse(order.begin(), order.end());
      for (int v : order){
        for (int w : forward_adj[v]){
          if (distance[w] == distance[v] + 1 && num_paths[w] > 0){
            delta[v] += num_paths[v] / num_paths[w];
            delta[v] += num_paths[v] / num_paths[w] * delta[w];
          }
        }
      }
      for (int t = 0; (size_t)t < V; t++){
        if (s != t) centrality_map[t] += delta[t];
      }
    }
  }
}

<|endoftext|>


<commit_before>#include "background.hpp"
#include "defs.hpp"
#include "client/texturefile.hpp"
#include "sys/rand.hpp"
#include <memory>
#include <stdio.h>
namespace LD22 {
namespace Bkgr {

struct CloudDef {
    unsigned char x, y, w, h;

    // Call inside a GL_QUADS with the cloud texture
    void render(float px, float py) const
    {
        float x0 = px, x1 = px + 128 * w;
        float y0 = py, y1 = py + 128 * h;
        float u0 = x * 0.125f, u1 = (x + w) * 0.125f;
        float v0 = (y + h) * 0.25f, v1 = y * 0.25f;
        glTexCoord2f(u0, v0); glVertex2f(x0, y0);
        glTexCoord2f(u0, v1); glVertex2f(x0, y1);
        glTexCoord2f(u1, v1); glVertex2f(x1, y1);
        glTexCoord2f(u1, v0); glVertex2f(x1, y0);
    }
};

static const CloudDef CLOUDS[10] = {
    // big clouds
    { 0, 0, 2, 2 },
    { 2, 0, 3, 2 },
    { 5, 0, 3, 2 },
    { 3, 2, 3, 2 },

    // medium clouds
    { 0, 2, 3, 1 },
    { 0, 3, 3, 1 },

    // small clouds
    { 6, 2, 1, 1 },
    { 6, 3, 1, 1 },
    { 7, 2, 1, 1 },
    { 7, 3, 1, 1 }
};

struct CloudInstance {
    short cloud;
    short dx;
    short dy;
};

static const CloudInstance LAYER1[10] = {
    { 6,   43, 300 },
    { 7,  110, 250 },
    { 8,  177, 275 },
    { 9,  233, 290 },
    { 7,  523, 250 },
    { 6,  570, 300 },
    { 9,  817, 250 },
    { 8,  885, 300 },
    { 6,  893, 300 },
    { 7, 1004, 290 }
};

static const CloudInstance LAYER2[10] = {
    { 6,    0, 200 },
    { 6,  224, 200 },
    { 6,  283, 200 },
    { 6,  385, 200 },
    { 6,  495, 200 },
    { 6,  533, 200 },
    { 6,  640, 200 },
    { 6,  796, 200 },
    { 6,  903, 200 },
    { 6,  915, 200 }
};

static const CloudInstance LAYER3[10] = {
    { 0,   94, 50 },
    { 1,  235, 50 },
    { 2,  350, 50 },
    { 3,  508, 50 },
    { 0,  427, 50 },
    { 2,  477, 50 },
    { 3,  481, 50 },
    { 1,  535, 50 },
    { 2,  733, 50 },
    { 3,  863, 50 }
};

struct CloudLayer {
    const CloudInstance *data;
    unsigned count;
    unsigned offset;
    unsigned speed;
};

class Clouds {
    static const int LAYERS = 3;
    CloudLayer m_layer[LAYERS];
    Texture::Ref m_tex;

public:
    Clouds()
    { }

    void init()
    {
        m_tex = TextureFile::open("back/clouds.jpg");
        m_layer[0].data = LAYER1;
        m_layer[1].data = LAYER2;
        m_layer[2].data = LAYER3;
        m_layer[0].count = 10;
        m_layer[1].count = 10;
        m_layer[2].count = 10;
        for (int i = 0; i < LAYERS; ++i)
            m_layer[i].offset = Rand::girand();
        m_layer[0].speed = 3;
        m_layer[1].speed = 6;
        m_layer[2].speed = 8;
    }

    void advance()
    {
        for (int i = 0; i < LAYERS; ++i)
            m_layer[i].offset += m_layer[i].speed;
    }

    void draw(int delta)
    {
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_BLEND);
        m_tex->bind();
        // glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);
        glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);
        int z = 160;
        glColor3ub(z, z, z);
        glBegin(GL_QUADS);
        for (int i = 0; i < LAYERS; ++i) {
            unsigned lpos = m_layer[i].offset +
                m_layer[i].speed * delta / FRAME_TIME;
            for (unsigned j = 0; j < m_layer[i].count; ++j) {
                const CloudInstance &ci = m_layer[i].data[j];
                int x = (-SCREEN_WIDTH / 2) + ((ci.dx * 2 + lpos) & 2047);
                int y = ci.dy;
                CLOUDS[ci.cloud].render(x, y);
            }
        }
        glEnd();
        // glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
        glDisable(GL_BLEND);
        glDisable(GL_TEXTURE_2D);
        glColor3ub(255, 255, 255);
    }
};

class Empty : public Background {
public:
    Empty()
        : Background(EMPTY)
    { }

    virtual ~Empty()
    { }

    virtual void init()
    { }

    virtual void advance()
    { }

    virtual void draw(int delta)
    {
        float x0 = 0.0f, x1 = SCREEN_WIDTH;
        float y0 = 0.0f, y1 = SCREEN_HEIGHT;
        glColor3ub(64, 64, 64);
        glBegin(GL_QUADS);
        glVertex2f(x0, y0);
        glVertex2f(x0, y1);
        glVertex2f(x1, y1);
        glVertex2f(x1, y0);
        glEnd();
        glColor3ub(255, 255, 255);
        (void) delta;
    }
};

class Mountains : public Background {
    Texture::Ref m_tex;
    Clouds m_clouds;

public:
    Mountains()
        : Background(MOUNTAINS)
    { }

    virtual ~Mountains()
    { }

    virtual void init()
    {
        m_tex = TextureFile::open("back/mountains.jpg");
        m_clouds.init();
    }

    virtual void advance()
    {
        m_clouds.advance();
    }

    virtual void draw(int delta)
    {
        float x0 = 0.0f, x1 = SCREEN_WIDTH;
        float y0 = 0.0f, y1 = SCREEN_HEIGHT;
        float u0 = 0.0f, u1 = 1.0f;
        float v0 = 1.0f, v1 = 0.0f;
        glEnable(GL_TEXTURE_2D);
        m_tex->bind();
        glBegin(GL_QUADS);
        glTexCoord2f(u0, v0); glVertex2f(x0, y0);
        glTexCoord2f(u0, v1); glVertex2f(x0, y1);
        glTexCoord2f(u1, v1); glVertex2f(x1, y1);
        glTexCoord2f(u1, v0); glVertex2f(x1, y0);
        glEnd();
        glDisable(GL_TEXTURE_2D);
        m_clouds.draw(delta);
    }
};

class City : public Background {
    Texture::Ref m_tex;

public:
    City()
        : Background(CITY)
    { }

    virtual ~City()
    { }

    virtual void init()
    {
        m_tex = TextureFile::open("back/city.jpg");
    }

    virtual void advance()
    { }

    virtual void draw(int delta)
    {
        float x0 = 0.0f, x1 = SCREEN_WIDTH;
        float y0 = 0.0f, y1 = SCREEN_HEIGHT;
        float u0 = 0.0f, u1 = 1.0f;
        float v0 = 1.0f, v1 = 0.0f;
        glEnable(GL_TEXTURE_2D);
        m_tex->bind();
        glBegin(GL_QUADS);
        glTexCoord2f(u0, v0); glVertex2f(x0, y0);
        glTexCoord2f(u0, v1); glVertex2f(x0, y1);
        glTexCoord2f(u1, v1); glVertex2f(x1, y1);
        glTexCoord2f(u1, v0); glVertex2f(x1, y0);
        glEnd();
        glDisable(GL_TEXTURE_2D);
    }
};

}

Background::~Background()
{ }

Background *Background::getBackground(int which)
{
    std::auto_ptr<Background> b;
    switch (which) {
    case EMPTY:
    default:
        b.reset(new Bkgr::Empty);
        break;

    case MOUNTAINS:
        b.reset(new Bkgr::Mountains);
        break;

    case CITY:
        b.reset(new Bkgr::City);
        break;
    }
    b->init();
    return b.release();
}

}
<commit_msg>Coalesce redundant background code<commit_after>#include "background.hpp"
#include "defs.hpp"
#include "client/texturefile.hpp"
#include "sys/rand.hpp"
#include <memory>
#include <stdio.h>
namespace LD22 {
namespace Bkgr {

struct CloudDef {
    unsigned char x, y, w, h;

    // Call inside a GL_QUADS with the cloud texture
    void render(float px, float py) const
    {
        float x0 = px, x1 = px + 128 * w;
        float y0 = py, y1 = py + 128 * h;
        float u0 = x * 0.125f, u1 = (x + w) * 0.125f;
        float v0 = (y + h) * 0.25f, v1 = y * 0.25f;
        glTexCoord2f(u0, v0); glVertex2f(x0, y0);
        glTexCoord2f(u0, v1); glVertex2f(x0, y1);
        glTexCoord2f(u1, v1); glVertex2f(x1, y1);
        glTexCoord2f(u1, v0); glVertex2f(x1, y0);
    }
};

static const CloudDef CLOUDS[10] = {
    // big clouds
    { 0, 0, 2, 2 },
    { 2, 0, 3, 2 },
    { 5, 0, 3, 2 },
    { 3, 2, 3, 2 },

    // medium clouds
    { 0, 2, 3, 1 },
    { 0, 3, 3, 1 },

    // small clouds
    { 6, 2, 1, 1 },
    { 6, 3, 1, 1 },
    { 7, 2, 1, 1 },
    { 7, 3, 1, 1 }
};

struct CloudInstance {
    short cloud;
    short dx;
    short dy;
};

static const CloudInstance LAYER1[10] = {
    { 6,   43, 300 },
    { 7,  110, 250 },
    { 8,  177, 275 },
    { 9,  233, 290 },
    { 7,  523, 250 },
    { 6,  570, 300 },
    { 9,  817, 250 },
    { 8,  885, 300 },
    { 6,  893, 300 },
    { 7, 1004, 290 }
};

static const CloudInstance LAYER2[10] = {
    { 6,    0, 200 },
    { 6,  224, 200 },
    { 6,  283, 200 },
    { 6,  385, 200 },
    { 6,  495, 200 },
    { 6,  533, 200 },
    { 6,  640, 200 },
    { 6,  796, 200 },
    { 6,  903, 200 },
    { 6,  915, 200 }
};

static const CloudInstance LAYER3[10] = {
    { 0,   94, 50 },
    { 1,  235, 50 },
    { 2,  350, 50 },
    { 3,  508, 50 },
    { 0,  427, 50 },
    { 2,  477, 50 },
    { 3,  481, 50 },
    { 1,  535, 50 },
    { 2,  733, 50 },
    { 3,  863, 50 }
};

struct CloudLayer {
    const CloudInstance *data;
    unsigned count;
    unsigned offset;
    unsigned speed;
};

class Clouds {
    static const int LAYERS = 3;
    CloudLayer m_layer[LAYERS];
    Texture::Ref m_tex;

public:
    Clouds()
    { }

    void init()
    {
        m_tex = TextureFile::open("back/clouds.jpg");
        m_layer[0].data = LAYER1;
        m_layer[1].data = LAYER2;
        m_layer[2].data = LAYER3;
        m_layer[0].count = 10;
        m_layer[1].count = 10;
        m_layer[2].count = 10;
        for (int i = 0; i < LAYERS; ++i)
            m_layer[i].offset = Rand::girand();
        m_layer[0].speed = 3;
        m_layer[1].speed = 6;
        m_layer[2].speed = 8;
    }

    void advance()
    {
        for (int i = 0; i < LAYERS; ++i)
            m_layer[i].offset += m_layer[i].speed;
    }

    void draw(int delta)
    {
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_BLEND);
        m_tex->bind();
        // glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);
        glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);
        int z = 160;
        glColor3ub(z, z, z);
        glBegin(GL_QUADS);
        for (int i = 0; i < LAYERS; ++i) {
            unsigned lpos = m_layer[i].offset +
                m_layer[i].speed * delta / FRAME_TIME;
            for (unsigned j = 0; j < m_layer[i].count; ++j) {
                const CloudInstance &ci = m_layer[i].data[j];
                int x = (-SCREEN_WIDTH / 2) + ((ci.dx * 2 + lpos) & 2047);
                int y = ci.dy;
                CLOUDS[ci.cloud].render(x, y);
            }
        }
        glEnd();
        // glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
        glDisable(GL_BLEND);
        glDisable(GL_TEXTURE_2D);
        glColor3ub(255, 255, 255);
    }
};

class Empty : public Background {
public:
    Empty()
        : Background(EMPTY)
    { }

    virtual ~Empty()
    { }

    virtual void init()
    { }

    virtual void advance()
    { }

    virtual void draw(int delta)
    {
        float x0 = 0.0f, x1 = SCREEN_WIDTH;
        float y0 = 0.0f, y1 = SCREEN_HEIGHT;
        glColor3ub(64, 64, 64);
        glBegin(GL_QUADS);
        glVertex2f(x0, y0);
        glVertex2f(x0, y1);
        glVertex2f(x1, y1);
        glVertex2f(x1, y0);
        glEnd();
        glColor3ub(255, 255, 255);
        (void) delta;
    }
};

class Picture {
    std::string m_path;
    Texture::Ref m_tex;
public:
    Picture(const std::string &path)
        : m_path(path)
    { }

    void init()
    {
        m_tex = TextureFile::open(m_path);
    }

    void draw()
    {
        float x0 = 0.0f, x1 = SCREEN_WIDTH;
        float y0 = 0.0f, y1 = SCREEN_HEIGHT;
        float u0 = 0.1f, u1 = 0.9f;
        float v0 = 1.0f, v1 = 0.0f;
        glEnable(GL_TEXTURE_2D);
        m_tex->bind();
        glBegin(GL_QUADS);
        glTexCoord2f(u0, v0); glVertex2f(x0, y0);
        glTexCoord2f(u0, v1); glVertex2f(x0, y1);
        glTexCoord2f(u1, v1); glVertex2f(x1, y1);
        glTexCoord2f(u1, v0); glVertex2f(x1, y0);
        glEnd();
        glDisable(GL_TEXTURE_2D);
    }
};

class Mountains : public Background {
    Picture m_pic;
    Clouds m_clouds;

public:
    Mountains()
        : Background(MOUNTAINS), m_pic("back/mountains.jpg")
    { }

    virtual ~Mountains()
    { }

    virtual void init()
    {
        m_pic.init();
        m_clouds.init();
    }

    virtual void advance()
    {
        m_clouds.advance();
    }

    virtual void draw(int delta)
    {
        m_pic.draw();
        m_clouds.draw(delta);
    }
};

class City : public Background {
    Picture m_pic;

public:
    City()
        : Background(CITY), m_pic("back/city.jpg")
    { }

    virtual ~City()
    { }

    virtual void init()
    {
        m_pic.init();
    }

    virtual void advance()
    { }

    virtual void draw(int delta)
    {
        m_pic.draw();
    }
};

}

Background::~Background()
{ }

Background *Background::getBackground(int which)
{
    std::auto_ptr<Background> b;
    switch (which) {
    case EMPTY:
    default:
        b.reset(new Bkgr::Empty);
        break;

    case MOUNTAINS:
        b.reset(new Bkgr::Mountains);
        break;

    case CITY:
        b.reset(new Bkgr::City);
        break;
    }
    b->init();
    return b.release();
}

}
<|endoftext|>


<commit_before>/*
 * Copyright © 2010 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include "ast.h"
#include "glsl_types.h"
#include "ir.h"

void
ast_array_specifier::print(void) const
{
   if (this->is_unsized_array) {
      printf("[ ] ");
   }

   foreach_list_typed (ast_node, array_dimension, link, &this->array_dimensions) {
      printf("[ ");
      array_dimension->print();
      printf("] ");
   }
}

/**
 * If \c ir is a reference to an array for which we are tracking the max array
 * element accessed, track that the given element has been accessed.
 * Otherwise do nothing.
 *
 * This function also checks whether the array is a built-in array whose
 * maximum size is too small to accommodate the given index, and if so uses
 * loc and state to report the error.
 */
static void
update_max_array_access(ir_rvalue *ir, unsigned idx, YYLTYPE *loc,
                        struct _mesa_glsl_parse_state *state)
{
   if (ir_dereference_variable *deref_var = ir->as_dereference_variable()) {
      ir_variable *var = deref_var->var;
      if (idx > var->data.max_array_access) {
         var->data.max_array_access = idx;

         /* Check whether this access will, as a side effect, implicitly cause
          * the size of a built-in array to be too large.
          */
         check_builtin_array_max_size(var->name, idx+1, *loc, state);
      }
   } else if (ir_dereference_record *deref_record =
              ir->as_dereference_record()) {
      /* There are two possibilities we need to consider:
       *
       * - Accessing an element of an array that is a member of a named
       *   interface block (e.g. ifc.foo[i])
       *
       * - Accessing an element of an array that is a member of a named
       *   interface block array (e.g. ifc[j].foo[i]).
       */
      ir_dereference_variable *deref_var =
         deref_record->record->as_dereference_variable();
      if (deref_var == NULL) {
         if (ir_dereference_array *deref_array =
             deref_record->record->as_dereference_array()) {
            deref_var = deref_array->array->as_dereference_variable();
         }
      }

      if (deref_var != NULL) {
         if (deref_var->var->is_interface_instance()) {
            const glsl_type *interface_type =
               deref_var->var->get_interface_type();
            unsigned field_index =
               deref_record->record->type->field_index(deref_record->field);
            assert(field_index < interface_type->length);
            if (idx > deref_var->var->max_ifc_array_access[field_index]) {
               deref_var->var->max_ifc_array_access[field_index] = idx;

               /* Check whether this access will, as a side effect, implicitly
                * cause the size of a built-in array to be too large.
                */
               check_builtin_array_max_size(deref_record->field, idx+1, *loc,
                                            state);
            }
         }
      }
   }
}

ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
			     struct _mesa_glsl_parse_state *state,
			     ir_rvalue *array, ir_rvalue *idx,
			     YYLTYPE &loc, YYLTYPE &idx_loc)
{
   if (!array->type->is_error()
       && !array->type->is_array()
       && !array->type->is_matrix()
       && !array->type->is_vector()) {
      _mesa_glsl_error(& idx_loc, state,
		       "cannot dereference non-array / non-matrix / "
		       "non-vector");
   }

   if (!idx->type->is_error()) {
      if (!idx->type->is_integer()) {
	 _mesa_glsl_error(& idx_loc, state, "array index must be integer type");
      } else if (!idx->type->is_scalar()) {
	 _mesa_glsl_error(& idx_loc, state, "array index must be scalar");
      }
   }

   /* If the array index is a constant expression and the array has a
    * declared size, ensure that the access is in-bounds.  If the array
    * index is not a constant expression, ensure that the array has a
    * declared size.
    */
   ir_constant *const const_index = idx->constant_expression_value();
   if (const_index != NULL && idx->type->is_integer()) {
      const int idx = const_index->value.i[0];
      const char *type_name = "error";
      unsigned bound = 0;

      /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
       *
       *    "It is illegal to declare an array with a size, and then
       *    later (in the same shader) index the same array with an
       *    integral constant expression greater than or equal to the
       *    declared size. It is also illegal to index an array with a
       *    negative constant expression."
       */
      if (array->type->is_matrix()) {
	 if (array->type->row_type()->vector_elements <= idx) {
	    type_name = "matrix";
	    bound = array->type->row_type()->vector_elements;
	 }
      } else if (array->type->is_vector()) {
	 if (array->type->vector_elements <= idx) {
	    type_name = "vector";
	    bound = array->type->vector_elements;
	 }
      } else {
	 /* glsl_type::array_size() returns -1 for non-array types.  This means
	  * that we don't need to verify that the type is an array before
	  * doing the bounds checking.
	  */
	 if ((array->type->array_size() > 0)
	     && (array->type->array_size() <= idx)) {
	    type_name = "array";
	    bound = array->type->array_size();
	 }
      }

      if (bound > 0) {
	 _mesa_glsl_error(& loc, state, "%s index must be < %u",
			  type_name, bound);
      } else if (idx < 0) {
	 _mesa_glsl_error(& loc, state, "%s index must be >= 0",
			  type_name);
      }

      if (array->type->is_array())
         update_max_array_access(array, idx, &loc, state);
   } else if (const_index == NULL && array->type->is_array()) {
      if (array->type->is_unsized_array()) {
	 _mesa_glsl_error(&loc, state, "unsized array index must be constant");
      } else if (array->type->fields.array->is_interface()
                 && array->variable_referenced()->data.mode == ir_var_uniform
                 && !state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
	 /* Page 46 in section 4.3.7 of the OpenGL ES 3.00 spec says:
	  *
	  *     "All indexes used to index a uniform block array must be
	  *     constant integral expressions."
	  */
	 _mesa_glsl_error(&loc, state,
			  "uniform block array index must be constant");
      } else {
	 /* whole_variable_referenced can return NULL if the array is a
	  * member of a structure.  In this case it is safe to not update
	  * the max_array_access field because it is never used for fields
	  * of structures.
	  */
	 ir_variable *v = array->whole_variable_referenced();
	 if (v != NULL)
	    v->data.max_array_access = array->type->array_size() - 1;
      }

      /* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
       *
       *    "Samplers aggregated into arrays within a shader (using square
       *    brackets [ ]) can only be indexed with integral constant
       *    expressions [...]."
       *
       * This restriction was added in GLSL 1.30.  Shaders using earlier
       * version of the language should not be rejected by the compiler
       * front-end for using this construct.  This allows useful things such
       * as using a loop counter as the index to an array of samplers.  If the
       * loop in unrolled, the code should compile correctly.  Instead, emit a
       * warning.
       */
      if (array->type->element_type()->is_sampler()) {
	 if (!state->is_version(130, 100)) {
	    if (state->es_shader) {
	       _mesa_glsl_warning(&loc, state,
				  "sampler arrays indexed with non-constant "
				  "expressions is optional in %s",
				  state->get_version_string());
	    } else {
	       _mesa_glsl_warning(&loc, state,
				  "sampler arrays indexed with non-constant "
				  "expressions will be forbidden in GLSL 1.30 "
				  "and later");
	    }
	 } else {
	    _mesa_glsl_error(&loc, state,
			     "sampler arrays indexed with non-constant "
			     "expressions is forbidden in GLSL 1.30 and "
			     "later");
	 }
      }
   }

   /* After performing all of the error checking, generate the IR for the
    * expression.
    */
   if (array->type->is_array()
       || array->type->is_matrix()) {
      return new(mem_ctx) ir_dereference_array(array, idx);
   } else if (array->type->is_vector()) {
      return new(mem_ctx) ir_expression(ir_binop_vector_extract, array, idx);
   } else if (array->type->is_error()) {
      return array;
   } else {
      ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
      result->type = glsl_type::error_type;

      return result;
   }
}
<commit_msg>glsl: Allow dynamically uniform sampler array indexing with 4.0/gs5<commit_after>/*
 * Copyright © 2010 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include "ast.h"
#include "glsl_types.h"
#include "ir.h"

void
ast_array_specifier::print(void) const
{
   if (this->is_unsized_array) {
      printf("[ ] ");
   }

   foreach_list_typed (ast_node, array_dimension, link, &this->array_dimensions) {
      printf("[ ");
      array_dimension->print();
      printf("] ");
   }
}

/**
 * If \c ir is a reference to an array for which we are tracking the max array
 * element accessed, track that the given element has been accessed.
 * Otherwise do nothing.
 *
 * This function also checks whether the array is a built-in array whose
 * maximum size is too small to accommodate the given index, and if so uses
 * loc and state to report the error.
 */
static void
update_max_array_access(ir_rvalue *ir, unsigned idx, YYLTYPE *loc,
                        struct _mesa_glsl_parse_state *state)
{
   if (ir_dereference_variable *deref_var = ir->as_dereference_variable()) {
      ir_variable *var = deref_var->var;
      if (idx > var->data.max_array_access) {
         var->data.max_array_access = idx;

         /* Check whether this access will, as a side effect, implicitly cause
          * the size of a built-in array to be too large.
          */
         check_builtin_array_max_size(var->name, idx+1, *loc, state);
      }
   } else if (ir_dereference_record *deref_record =
              ir->as_dereference_record()) {
      /* There are two possibilities we need to consider:
       *
       * - Accessing an element of an array that is a member of a named
       *   interface block (e.g. ifc.foo[i])
       *
       * - Accessing an element of an array that is a member of a named
       *   interface block array (e.g. ifc[j].foo[i]).
       */
      ir_dereference_variable *deref_var =
         deref_record->record->as_dereference_variable();
      if (deref_var == NULL) {
         if (ir_dereference_array *deref_array =
             deref_record->record->as_dereference_array()) {
            deref_var = deref_array->array->as_dereference_variable();
         }
      }

      if (deref_var != NULL) {
         if (deref_var->var->is_interface_instance()) {
            const glsl_type *interface_type =
               deref_var->var->get_interface_type();
            unsigned field_index =
               deref_record->record->type->field_index(deref_record->field);
            assert(field_index < interface_type->length);
            if (idx > deref_var->var->max_ifc_array_access[field_index]) {
               deref_var->var->max_ifc_array_access[field_index] = idx;

               /* Check whether this access will, as a side effect, implicitly
                * cause the size of a built-in array to be too large.
                */
               check_builtin_array_max_size(deref_record->field, idx+1, *loc,
                                            state);
            }
         }
      }
   }
}

ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
			     struct _mesa_glsl_parse_state *state,
			     ir_rvalue *array, ir_rvalue *idx,
			     YYLTYPE &loc, YYLTYPE &idx_loc)
{
   if (!array->type->is_error()
       && !array->type->is_array()
       && !array->type->is_matrix()
       && !array->type->is_vector()) {
      _mesa_glsl_error(& idx_loc, state,
		       "cannot dereference non-array / non-matrix / "
		       "non-vector");
   }

   if (!idx->type->is_error()) {
      if (!idx->type->is_integer()) {
	 _mesa_glsl_error(& idx_loc, state, "array index must be integer type");
      } else if (!idx->type->is_scalar()) {
	 _mesa_glsl_error(& idx_loc, state, "array index must be scalar");
      }
   }

   /* If the array index is a constant expression and the array has a
    * declared size, ensure that the access is in-bounds.  If the array
    * index is not a constant expression, ensure that the array has a
    * declared size.
    */
   ir_constant *const const_index = idx->constant_expression_value();
   if (const_index != NULL && idx->type->is_integer()) {
      const int idx = const_index->value.i[0];
      const char *type_name = "error";
      unsigned bound = 0;

      /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
       *
       *    "It is illegal to declare an array with a size, and then
       *    later (in the same shader) index the same array with an
       *    integral constant expression greater than or equal to the
       *    declared size. It is also illegal to index an array with a
       *    negative constant expression."
       */
      if (array->type->is_matrix()) {
	 if (array->type->row_type()->vector_elements <= idx) {
	    type_name = "matrix";
	    bound = array->type->row_type()->vector_elements;
	 }
      } else if (array->type->is_vector()) {
	 if (array->type->vector_elements <= idx) {
	    type_name = "vector";
	    bound = array->type->vector_elements;
	 }
      } else {
	 /* glsl_type::array_size() returns -1 for non-array types.  This means
	  * that we don't need to verify that the type is an array before
	  * doing the bounds checking.
	  */
	 if ((array->type->array_size() > 0)
	     && (array->type->array_size() <= idx)) {
	    type_name = "array";
	    bound = array->type->array_size();
	 }
      }

      if (bound > 0) {
	 _mesa_glsl_error(& loc, state, "%s index must be < %u",
			  type_name, bound);
      } else if (idx < 0) {
	 _mesa_glsl_error(& loc, state, "%s index must be >= 0",
			  type_name);
      }

      if (array->type->is_array())
         update_max_array_access(array, idx, &loc, state);
   } else if (const_index == NULL && array->type->is_array()) {
      if (array->type->is_unsized_array()) {
	 _mesa_glsl_error(&loc, state, "unsized array index must be constant");
      } else if (array->type->fields.array->is_interface()
                 && array->variable_referenced()->data.mode == ir_var_uniform
                 && !state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
	 /* Page 46 in section 4.3.7 of the OpenGL ES 3.00 spec says:
	  *
	  *     "All indexes used to index a uniform block array must be
	  *     constant integral expressions."
	  */
	 _mesa_glsl_error(&loc, state,
			  "uniform block array index must be constant");
      } else {
	 /* whole_variable_referenced can return NULL if the array is a
	  * member of a structure.  In this case it is safe to not update
	  * the max_array_access field because it is never used for fields
	  * of structures.
	  */
	 ir_variable *v = array->whole_variable_referenced();
	 if (v != NULL)
	    v->data.max_array_access = array->type->array_size() - 1;
      }

      /* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
       *
       *    "Samplers aggregated into arrays within a shader (using square
       *    brackets [ ]) can only be indexed with integral constant
       *    expressions [...]."
       *
       * This restriction was added in GLSL 1.30.  Shaders using earlier
       * version of the language should not be rejected by the compiler
       * front-end for using this construct.  This allows useful things such
       * as using a loop counter as the index to an array of samplers.  If the
       * loop in unrolled, the code should compile correctly.  Instead, emit a
       * warning.
       *
       * In GLSL 4.00 / ARB_gpu_shader5, this requirement is relaxed again to allow
       * indexing with dynamically uniform expressions. Note that these are not
       * required to be uniforms or expressions based on them, but merely that the
       * values must not diverge between shader invocations run together. If the
       * values *do* diverge, then the behavior of the operation requiring a
       * dynamically uniform expression is undefined.
       */
      if (array->type->element_type()->is_sampler()) {
	 if (!state->is_version(130, 100)) {
	    if (state->es_shader) {
	       _mesa_glsl_warning(&loc, state,
				  "sampler arrays indexed with non-constant "
				  "expressions is optional in %s",
				  state->get_version_string());
	    } else {
	       _mesa_glsl_warning(&loc, state,
				  "sampler arrays indexed with non-constant "
				  "expressions will be forbidden in GLSL 1.30 "
				  "and later");
	    }
	 } else if (!state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
	    _mesa_glsl_error(&loc, state,
			     "sampler arrays indexed with non-constant "
			     "expressions is forbidden in GLSL 1.30 and "
			     "later");
	 }
      }
   }

   /* After performing all of the error checking, generate the IR for the
    * expression.
    */
   if (array->type->is_array()
       || array->type->is_matrix()) {
      return new(mem_ctx) ir_dereference_array(array, idx);
   } else if (array->type->is_vector()) {
      return new(mem_ctx) ir_expression(ir_binop_vector_extract, array, idx);
   } else if (array->type->is_error()) {
      return array;
   } else {
      ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
      result->type = glsl_type::error_type;

      return result;
   }
}
<|endoftext|>


<commit_before>#include <opencv2/opencv.hpp>
// #include "opencv2/highgui/highgui.hpp"
// #include "opencv2/imgproc/imgproc.hpp"
//#include "opencv2/gpu/gpu.hpp"
#include "opencv2/core/cuda.hpp"
#include "opencv2/cudaobjdetect.hpp"

using namespace cv;
using namespace std;

int main (int argc, const char * argv[]){

    Mat img;
    //init the descriptors
    cv::Ptr<cv::cuda::HOG> gpu_hog = cv::cuda::HOG::create();
    HOGDescriptor cpu_hog;

    //set the svm to default people detector
    gpu_hog->setSVMDetector(gpu_hog->getDefaultPeopleDetector());
    cpu_hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());

    while (true){

        img = imread("../walkingPeople.jpeg");

        if (!img.data){
            cerr<<"Couldn't open image"<<endl;
            return -1;
        }

        // //resizing the video since it's so massive
        // resize(img, img, Size(640, 360), 0, 0, INTER_CUBIC);

        vector<Rect> found_cpu, found_filtered_cpu;
        vector<Rect> found_gpu, found_filtered_gpu;

        //comput for the gpu
        cuda::GpuMat gpu_img;
        gpu_img.upload(img);
        gpu_hog->detectMultiScale(gpu_img, found_gpu);

        //comput for the cpu
        cpu_hog.detectMultiScale(img, found_cpu, 0, Size(8,8), Size(32,32), 1.05, 2);
        size_t i, j;

        for (i=0; i<found.size(); i++)
        {
            Rect r = found[i];
            for (j=0; j<found.size(); j++)
                if (j!=i && (r & found[j]) == r)
                    break;
            if (j== found.size())
                found_filtered.push_back(r);
        }

        for (i=0; i<found_filtered.size(); i++)
        {
            Rect r = found_filtered[i];
            r.x += cvRound(r.width*0.1);
        r.width = cvRound(r.width*0.8);
        r.y += cvRound(r.height*0.07);
        r.height = cvRound(r.height*0.8);
        rectangle(img, r.tl(), r.br(), Scalar(0,255,0), 3);
        }
        if(found_filtered.size() > 0){
            cout<<"Rec: " << found_filtered[0].x << endl;
        }
        imwrite("tracking.jpeg",img);

    }
    return 0;
}

int findObject(vector<Rec> found, Mat img,string filename){
    size_t j = 0, i = 0;
    vector<Rec> found_filtered;

    for (i=0; i<found.size(); i++){
        Rect r = found[i];
        for (j=0; j<found.size(); j++){
            if (j!=i && (r & found[j]) == r){
                break;
            }
        }
        if (j== found.size()){
            found_filtered.push_back(r);
        }
    }

        for (i=0; i<found_filtered.size(); i++){
            Rect r = found_filtered[i];
            r.x += cvRound(r.width*0.1);
            r.width = cvRound(r.width*0.8);
            r.y += cvRound(r.height*0.07);
            r.height = cvRound(r.height*0.8);
            rectangle(img, r.tl(), r.br(), Scalar(0,255,0), 3);
        }

        imwrite(filename,img);
}
<commit_msg>fixed the rect opencv datatype<commit_after>#include <opencv2/opencv.hpp>
// #include "opencv2/highgui/highgui.hpp"
// #include "opencv2/imgproc/imgproc.hpp"
//#include "opencv2/gpu/gpu.hpp"
#include "opencv2/core/cuda.hpp"
#include "opencv2/cudaobjdetect.hpp"

using namespace cv;
using namespace std;

int findObject(vector<Rect> found, Mat img,string filename);

int main (int argc, const char * argv[]){

    Mat img;
    //init the descriptors
    cv::Ptr<cv::cuda::HOG> gpu_hog = cv::cuda::HOG::create();
    HOGDescriptor cpu_hog;

    //set the svm to default people detector
    gpu_hog->setSVMDetector(gpu_hog->getDefaultPeopleDetector());
    cpu_hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());

    while (true){

        img = imread("../walkingPeople.jpeg");

        if (!img.data){
            cerr<<"Couldn't open image"<<endl;
            return -1;
        }

        // //resizing the video since it's so massive
        // resize(img, img, Size(640, 360), 0, 0, INTER_CUBIC);

        vector<Rect> found_cpu, found_filtered_cpu;
        vector<Rect> found_gpu, found_filtered_gpu;

        //comput for the gpu
        cuda::GpuMat gpu_img;
        gpu_img.upload(img);
        gpu_hog->detectMultiScale(gpu_img, found_gpu);

        //comput for the cpu
        cpu_hog.detectMultiScale(img, found_cpu, 0, Size(8,8), Size(32,32), 1.05, 2);
        findObject(found_cpu,img,"tracking_cpu.jpeg");
        findObject(found_gpu,img,"tracking_gpu.jpeg");

    }
    return 0;
}

int findObject(vector<Rect> found, Mat img,string filename){
    size_t j = 0, i = 0;
    vector<Rect> found_filtered;

    for (i=0; i<found.size(); i++){
        Rect r = found[i];
        for (j=0; j<found.size(); j++){
            if (j!=i && (r & found[j]) == r){
                break;
            }
        }
        if (j== found.size()){
            found_filtered.push_back(r);
        }
    }

        for (i=0; i<found_filtered.size(); i++){
            Rect r = found_filtered[i];
            r.x += cvRound(r.width*0.1);
            r.width = cvRound(r.width*0.8);
            r.y += cvRound(r.height*0.07);
            r.height = cvRound(r.height*0.8);
            rectangle(img, r.tl(), r.br(), Scalar(0,255,0), 3);
        }

        imwrite(filename,img);
}
<|endoftext|>


<commit_before>/*
 * experimental.cc
 *
 *  Created on: May 1, 2015
 *      Author: isovic
 */

#include "graphmap/graphmap.h"
#include "graphmap/filter_anchors.h"

int GraphMap::AnchoredPostProcessRegionWithLCS_(ScoreRegistry* local_score, MappingData* mapping_data, const std::vector<Index *> &indexes, const SingleSequence* read, const ProgramParameters* parameters) {
  LOG_DEBUG_SPEC("Entering function. [time: %.2f sec, RSS: %ld MB, peakRSS: %ld MB] current_readid = %ld, current_local_score = %ld\n", (((float) (clock())) / CLOCKS_PER_SEC), getCurrentRSS() / (1024 * 1024), getPeakRSS() / (1024 * 1024), read->get_sequence_id(), local_score->get_scores_id());
  int lcskpp_length = 0;
  std::vector<int> lcskpp_indices;
  CalcLCSFromLocalScoresCacheFriendly_(&(local_score->get_registry_entries()), false, 0, 0, &lcskpp_length, &lcskpp_indices);
  if (lcskpp_length == 0) {
    LogSystem::GetInstance().Log(VERBOSE_LEVEL_ALL_DEBUG, read->get_sequence_id() == parameters->debug_read, FormatString("Current local scores: %ld, lcskpp_length == 0 || best_score == NULL\n", local_score->get_scores_id()), "ExperimentalPostProcessRegionWithLCS");
    return 1;
  }

  if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
    LOG_DEBUG_SPEC("After LCSk:\n", local_score->get_scores_id());
    for (int64_t i = 0; i < lcskpp_indices.size(); i++) {
      LOG_DEBUG_SPEC_NO_HEADER("[%ld] %s\n", i, local_score->get_registry_entries().VerboseToString(lcskpp_indices[i]).c_str());
    }
    LOG_DEBUG_SPEC_NEWLINE;
  }

//  std::reverse(first_filtered_lcskpp_indices.begin(), first_filtered_lcskpp_indices.end());

  /// Filter the LCSk anchors.
  std::vector<ClusterAndIndices *> clusters;
  std::vector<int> cluster_indices;
  std::vector<int32_t> cluster_ids;

  /// Filter the LCSk anchors, first pass. This pass filters outliers, but does not generate clusters.
  std::vector<int> first_filtered_lcskpp_indices;
  std::vector<int> second_filtered_lcskpp_indices;

  FilterAnchorsByChaining(read, local_score, parameters, lcskpp_indices, parameters->error_rate/2 + 0.01f, 200.0f, 0, 50, 2, first_filtered_lcskpp_indices, NULL);
  FilterAnchorsByDiff(read, local_score, parameters, first_filtered_lcskpp_indices, second_filtered_lcskpp_indices);
  GenerateClusters(2, 50, 50, 0.0, second_filtered_lcskpp_indices, local_score, mapping_data, indexes, read, parameters, clusters, cluster_indices, &cluster_ids);

  // Find the L1 parameters (median line and the confidence intervals).
  float l_diff = read->get_sequence_length() * parameters->error_rate;
  float maximum_allowed_deviation = l_diff * sqrt(2.0f) / 2.0f;
  float sigma_L2 = 0.0f, confidence_L1 = 0.0f;
  int64_t k = 0, l = 0;
  // Actuall L1 calculation.
  int ret_L1 = CalculateL1ParametersWithMaximumDeviation_(local_score, cluster_indices, maximum_allowed_deviation, &k, &l, &sigma_L2, &confidence_L1);
  // Sanity check.
  if (ret_L1) {
    LOG_DEBUG_SPEC("An error occured, L1 function (I) returned with %d!\n", ret_L1);
    if (ret_L1 == 1) {  LOG_DEBUG_SPEC("  lcskpp_indices.size() == 0\n"); }
    else if (ret_L1 == 2) { LOG_DEBUG_SPEC("  num_points_under_max_dev_threshold == 0\n"); }

    #ifndef RELEASE_VERSION
      if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
        LOG_DEBUG_SPEC("Writing all anchors to file scores-%ld.\n",  local_score->get_scores_id());
        VerboseLocalScoresToFile(FormatString("temp/local_scores/scores-%ld.csv", local_score->get_scores_id()), read, local_score, NULL, 0, 0, false);
        LOG_DEBUG_SPEC("Writing LCSk anchors to file LCS-%ld.\n",  local_score->get_scores_id());
        VerboseLocalScoresToFile(FormatString("temp/local_scores/LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &lcskpp_indices, 0, 0, false);
        LOG_DEBUG_SPEC("Writing LCSk anchors to file LCSL1-%ld.\n",  local_score->get_scores_id());
        VerboseLocalScoresToFile(FormatString("temp/local_scores/LCSL1-%ld.csv", local_score->get_scores_id()), read, local_score, &second_filtered_lcskpp_indices, 0, 0, false);
        LOG_DEBUG_SPEC("Writing LCSk anchors to file double_LCS-%ld.\n",  local_score->get_scores_id());
        VerboseLocalScoresToFile(FormatString("temp/local_scores/double_LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &cluster_indices, 0, 0, false, &cluster_ids);
      }
    #endif

    return 1;
  }
  float allowed_L1_deviation = 3.0f * confidence_L1;

  // Count the number of covered bases, and find the first and last element of the LCSk.
  int64_t indexfirst = -1;
  int64_t indexlast = -1;

  int64_t covered_bases = 0;
  int64_t covered_bases_query = 0, covered_bases_reference = 0;
  int64_t num_covering_kmers = 0;
  LOG_DEBUG_SPEC("Counting the covered bases and finding the first and the last brick index.\n");
  for (uint64_t i = 0; i < cluster_indices.size(); i++) {
    covered_bases_query += local_score->get_registry_entries().covered_bases_queries[cluster_indices[i]];
    covered_bases_reference += local_score->get_registry_entries().covered_bases_references[cluster_indices[i]];
    num_covering_kmers += local_score->get_registry_entries().num_kmers[cluster_indices[i]];
  }
  covered_bases = std::max(covered_bases_query, covered_bases_reference);

  if (cluster_indices.size() > 0) {
    indexfirst = cluster_indices.back();
    indexlast = cluster_indices.front();
  }

  // There are no valid graph paths! All scores were dismissed because of high deviation.
  // This is most likely a false positive.
  if (indexfirst == -1 || indexlast == -1) {
    LOG_DEBUG_SPEC("An error occured, indexfirst = %ld, indexlast = %ld\n", indexfirst, indexlast);
    return 1;
  }

  MappingResults mapping_info;
  mapping_info.lcs_length = lcskpp_length;
  mapping_info.cov_bases_query = covered_bases_query;
  mapping_info.cov_bases_ref = covered_bases_reference;
  mapping_info.cov_bases_max = covered_bases;
  mapping_info.query_coords.start = local_score->get_registry_entries().query_starts[indexlast];
  mapping_info.query_coords.end = local_score->get_registry_entries().query_ends[indexfirst];
  mapping_info.ref_coords.start = local_score->get_registry_entries().reference_starts[indexlast];
  mapping_info.ref_coords.end = local_score->get_registry_entries().reference_ends[indexfirst];
  mapping_info.num_covering_kmers = num_covering_kmers;
  mapping_info.deviation = confidence_L1;
  mapping_info.is_reverse = (local_score->get_region().reference_id >= indexes[0]->get_num_sequences_forward());
  mapping_info.local_score_id = local_score->get_scores_id();

  #ifndef RELEASE_VERSION
    LOG_DEBUG_SPEC("Clusters:\n");
  #endif

  for (int64_t i=0; i<clusters.size(); i++) {
    if (clusters[i]) {
        Cluster mapping_cluster;
        mapping_cluster.query = clusters[i]->query;
        mapping_cluster.ref = clusters[i]->ref;
        mapping_info.clusters.push_back(mapping_cluster);
      #ifndef RELEASE_VERSION
        int64_t reference_start = indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id];
        int64_t region_start = local_score->get_region().start;
        LOG_DEBUG_SPEC("start(%ld, %ld), end(%ld, %ld)\tstart(%ld, %ld), end(%ld, %ld)\n",
                       mapping_cluster.query.start, mapping_cluster.ref.start, mapping_cluster.query.end, mapping_cluster.ref.end,
                       mapping_cluster.query.start, mapping_cluster.ref.start - reference_start, mapping_cluster.query.end, mapping_cluster.ref.end - reference_start);
      #endif
    }
  }

  L1Results l1_info;
  l1_info.l1_l = l;
  l1_info.l1_k = 1.0f;
  l1_info.l1_lmin = l - l_diff;
  l1_info.l1_lmax = l + l_diff;
  l1_info.l1_confidence_abs = confidence_L1;
  l1_info.l1_std = sigma_L2;
  l1_info.l1_rough_start = l1_info.l1_k * 0 + l1_info.l1_lmin;
  l1_info.l1_rough_end = l1_info.l1_k * read->get_sequence_length() + l1_info.l1_lmax;
  if (l1_info.l1_rough_start < indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id])
    l1_info.l1_rough_start = indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id];
  if (l1_info.l1_rough_end >= (indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id] + indexes[0]->get_reference_lengths()[local_score->get_region().reference_id]))
    l1_info.l1_rough_end = (indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id] + indexes[0]->get_reference_lengths()[local_score->get_region().reference_id]) - 1;

  mapping_info.is_mapped = true;

  PathGraphEntry *new_entry = new PathGraphEntry(indexes[0], read, parameters, (Region &) local_score->get_region(), &mapping_info, &l1_info);

  LogSystem::GetInstance().Log(VERBOSE_LEVEL_HIGH_DEBUG, read->get_sequence_id() == parameters->debug_read, "\n", "[]");
  mapping_data->intermediate_mappings.push_back(new_entry);

  #ifndef RELEASE_VERSION
    if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
      LOG_DEBUG_SPEC("Writing all anchors to file scores-%ld.\n",  local_score->get_scores_id());
      VerboseLocalScoresToFile(FormatString("temp/local_scores/scores-%ld.csv", local_score->get_scores_id()), read, local_score, NULL, 0, 0, false);
      LOG_DEBUG_SPEC("Writing LCSk anchors to file LCS-%ld.\n",  local_score->get_scores_id());
      VerboseLocalScoresToFile(FormatString("temp/local_scores/LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &lcskpp_indices, 0, 0, false, NULL);
      LOG_DEBUG_SPEC("Writing cluster anchors to file LCSL1-%ld.\n",  local_score->get_scores_id());
      VerboseLocalScoresToFile(FormatString("temp/local_scores/LCSL1-%ld.csv", local_score->get_scores_id()), read, local_score, &second_filtered_lcskpp_indices, 0, 0, false);
      LOG_DEBUG_SPEC("Writing cluster anchors (again) to file double_LCS-%ld.\n",  local_score->get_scores_id());
      VerboseLocalScoresToFile(FormatString("temp/local_scores/double_LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &cluster_indices, l, 3.0f * confidence_L1, false, &cluster_ids);

      LOG_DEBUG_SPEC("LCSk clusters:\n");
      for (int64_t i=0; i<clusters.size(); i++) {
        LOG_DEBUG_SPEC_NO_HEADER("[%ld] num_anchors: %ld, length: %ld, coverage: %ld, query.start = %ld, query.end = %ld\n", i, clusters[i]->num_anchors, (clusters[i]->query.end - clusters[i]->query.start), clusters[i]->coverage, clusters[i]->query.start, clusters[i]->query.end);
      }
      LOG_DEBUG_SPEC_NEWLINE;
      LOG_DEBUG_SPEC("mapping_info.clusters:\n");
      for (int64_t i=0; i<mapping_info.clusters.size(); i++) {
        LOG_DEBUG_SPEC_NO_HEADER("[%ld] query.start = %ld, query.end = %ld, ref.start = %ld, ref.end = %ld\n", i, mapping_info.clusters[i].query.start, mapping_info.clusters[i].query.end, mapping_info.clusters[i].ref.start, mapping_info.clusters[i].ref.end);
      }
      LOG_DEBUG_SPEC_NEWLINE;
      VerboseClustersToFile_(FormatString("temp/clusters/clusters-read-%ld.csv", read->get_sequence_id()), local_score, mapping_data, indexes, read, parameters, clusters);
    }
    LOG_DEBUG_SPEC("Exiting function. [time: %.2f sec, RSS: %ld MB, peakRSS: %ld MB]\n", (((float) (clock())) / CLOCKS_PER_SEC), getCurrentRSS() / (1024 * 1024), getPeakRSS() / (1024 * 1024));
  #endif

  for (int64_t i=0; i<clusters.size(); i++) {
    if (clusters[i]) {
      delete clusters[i];
    }
  }

  return 0;
}
<commit_msg>Minor parametrization of filter calls.<commit_after>/*
 * experimental.cc
 *
 *  Created on: May 1, 2015
 *      Author: isovic
 */

#include "graphmap/graphmap.h"
#include "graphmap/filter_anchors.h"

int GraphMap::AnchoredPostProcessRegionWithLCS_(ScoreRegistry* local_score, MappingData* mapping_data, const std::vector<Index *> &indexes, const SingleSequence* read, const ProgramParameters* parameters) {
  LOG_DEBUG_SPEC("Entering function. [time: %.2f sec, RSS: %ld MB, peakRSS: %ld MB] current_readid = %ld, current_local_score = %ld\n", (((float) (clock())) / CLOCKS_PER_SEC), getCurrentRSS() / (1024 * 1024), getPeakRSS() / (1024 * 1024), read->get_sequence_id(), local_score->get_scores_id());
  int lcskpp_length = 0;
  std::vector<int> lcskpp_indices;
  CalcLCSFromLocalScoresCacheFriendly_(&(local_score->get_registry_entries()), false, 0, 0, &lcskpp_length, &lcskpp_indices);
  if (lcskpp_length == 0) {
    LogSystem::GetInstance().Log(VERBOSE_LEVEL_ALL_DEBUG, read->get_sequence_id() == parameters->debug_read, FormatString("Current local scores: %ld, lcskpp_length == 0 || best_score == NULL\n", local_score->get_scores_id()), "ExperimentalPostProcessRegionWithLCS");
    return 1;
  }

  if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
    LOG_DEBUG_SPEC("After LCSk:\n", local_score->get_scores_id());
    for (int64_t i = 0; i < lcskpp_indices.size(); i++) {
      LOG_DEBUG_SPEC_NO_HEADER("[%ld] %s\n", i, local_score->get_registry_entries().VerboseToString(lcskpp_indices[i]).c_str());
    }
    LOG_DEBUG_SPEC_NEWLINE;
  }

//  std::reverse(first_filtered_lcskpp_indices.begin(), first_filtered_lcskpp_indices.end());

  /// Filter the LCSk anchors.
  std::vector<ClusterAndIndices *> clusters;
  std::vector<int> cluster_indices;
  std::vector<int32_t> cluster_ids;

  /// Filter the LCSk anchors, first pass. This pass filters outliers, but does not generate clusters.
  std::vector<int> first_filtered_lcskpp_indices;
  std::vector<int> second_filtered_lcskpp_indices;

  // Parameters for anchor filtering.
  double indel_bandwidth_margin = parameters->error_rate/2 + 0.01f;
  int32_t max_dist = 200;
  int64_t min_covered_bases = 50; // TODO: need to experiment with this: std::min((int64_t) (read->get_sequence_length() * 0.10f), (int64_t) 50);
  int64_t cluster_size_cutoff = 2; // TODO: need to experiment with this. 1; // 2
  FilterAnchorsByChaining(read, local_score, parameters, lcskpp_indices, indel_bandwidth_margin, max_dist, 0, min_covered_bases, cluster_size_cutoff, first_filtered_lcskpp_indices, NULL);
  FilterAnchorsByDiff(read, local_score, parameters, first_filtered_lcskpp_indices, second_filtered_lcskpp_indices);
//  FilterAnchorsByChaining(read, local_score, parameters, lcskpp_indices, parameters->error_rate/2 + 0.01f, 200.0f, 0, 50, 2, first_filtered_lcskpp_indices, NULL);
//  FilterAnchorsByDiff(read, local_score, parameters, first_filtered_lcskpp_indices, second_filtered_lcskpp_indices);

  // Parameters for cluster filtering.
  int64_t min_num_anchors_in_cluster = 2; // TODO: need to experiment with this. 1; // 2;
  int64_t min_cluster_length = min_covered_bases; // 50;
  int64_t min_cluster_covered_bases = min_cluster_length; // 50;
  float min_cluster_coverage = 0.0f;
  GenerateClusters(min_num_anchors_in_cluster, min_cluster_length, min_cluster_covered_bases, min_cluster_coverage,
                   second_filtered_lcskpp_indices, local_score, mapping_data, indexes, read, parameters, clusters, cluster_indices, &cluster_ids);
//  GenerateClusters(2, 50, 50, 0.0, second_filtered_lcskpp_indices, local_score, mapping_data, indexes, read, parameters, clusters, cluster_indices, &cluster_ids);

  // Find the L1 parameters (median line and the confidence intervals).
  float l_diff = read->get_sequence_length() * parameters->error_rate;
  float maximum_allowed_deviation = l_diff * sqrt(2.0f) / 2.0f;
  float sigma_L2 = 0.0f, confidence_L1 = 0.0f;
  int64_t k = 0, l = 0;
  // Actual L1 calculation.
  int ret_L1 = CalculateL1ParametersWithMaximumDeviation_(local_score, cluster_indices, maximum_allowed_deviation, &k, &l, &sigma_L2, &confidence_L1);
  // Sanity check.
  if (ret_L1) {
    LOG_DEBUG_SPEC("An error occured, L1 function (I) returned with %d!\n", ret_L1);
    if (ret_L1 == 1) {  LOG_DEBUG_SPEC("  lcskpp_indices.size() == 0\n"); }
    else if (ret_L1 == 2) { LOG_DEBUG_SPEC("  num_points_under_max_dev_threshold == 0\n"); }

    #ifndef RELEASE_VERSION
      if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
        LOG_DEBUG_SPEC("Writing all anchors to file scores-%ld.\n",  local_score->get_scores_id());
        VerboseLocalScoresToFile(FormatString("temp/local_scores/scores-%ld.csv", local_score->get_scores_id()), read, local_score, NULL, 0, 0, false);
        LOG_DEBUG_SPEC("Writing LCSk anchors to file LCS-%ld.\n",  local_score->get_scores_id());
        VerboseLocalScoresToFile(FormatString("temp/local_scores/LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &lcskpp_indices, 0, 0, false);
        LOG_DEBUG_SPEC("Writing LCSk anchors to file LCSL1-%ld.\n",  local_score->get_scores_id());
        VerboseLocalScoresToFile(FormatString("temp/local_scores/LCSL1-%ld.csv", local_score->get_scores_id()), read, local_score, &second_filtered_lcskpp_indices, 0, 0, false);
        LOG_DEBUG_SPEC("Writing LCSk anchors to file double_LCS-%ld.\n",  local_score->get_scores_id());
        VerboseLocalScoresToFile(FormatString("temp/local_scores/double_LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &cluster_indices, 0, 0, false, &cluster_ids);
      }
    #endif

    return 1;
  }
  float allowed_L1_deviation = 3.0f * confidence_L1;

  // Count the number of covered bases, and find the first and last element of the LCSk.
  int64_t indexfirst = -1;
  int64_t indexlast = -1;

  int64_t covered_bases = 0;
  int64_t covered_bases_query = 0, covered_bases_reference = 0;
  int64_t num_covering_kmers = 0;
  LOG_DEBUG_SPEC("Counting the covered bases and finding the first and the last brick index.\n");
  for (uint64_t i = 0; i < cluster_indices.size(); i++) {
    covered_bases_query += local_score->get_registry_entries().covered_bases_queries[cluster_indices[i]];
    covered_bases_reference += local_score->get_registry_entries().covered_bases_references[cluster_indices[i]];
    num_covering_kmers += local_score->get_registry_entries().num_kmers[cluster_indices[i]];
  }
  covered_bases = std::max(covered_bases_query, covered_bases_reference);

  if (cluster_indices.size() > 0) {
    indexfirst = cluster_indices.back();
    indexlast = cluster_indices.front();
  }

  // There are no valid graph paths! All scores were dismissed because of high deviation.
  // This is most likely a false positive.
  if (indexfirst == -1 || indexlast == -1) {
    LOG_DEBUG_SPEC("An error occured, indexfirst = %ld, indexlast = %ld\n", indexfirst, indexlast);
    return 1;
  }

  MappingResults mapping_info;
  mapping_info.lcs_length = lcskpp_length;
  mapping_info.cov_bases_query = covered_bases_query;
  mapping_info.cov_bases_ref = covered_bases_reference;
  mapping_info.cov_bases_max = covered_bases;
  mapping_info.query_coords.start = local_score->get_registry_entries().query_starts[indexlast];
  mapping_info.query_coords.end = local_score->get_registry_entries().query_ends[indexfirst];
  mapping_info.ref_coords.start = local_score->get_registry_entries().reference_starts[indexlast];
  mapping_info.ref_coords.end = local_score->get_registry_entries().reference_ends[indexfirst];
  mapping_info.num_covering_kmers = num_covering_kmers;
  mapping_info.deviation = confidence_L1;
  mapping_info.is_reverse = (local_score->get_region().reference_id >= indexes[0]->get_num_sequences_forward());
  mapping_info.local_score_id = local_score->get_scores_id();

  #ifndef RELEASE_VERSION
    LOG_DEBUG_SPEC("Clusters:\n");
  #endif

  for (int64_t i=0; i<clusters.size(); i++) {
    if (clusters[i]) {
        Cluster mapping_cluster;
        mapping_cluster.query = clusters[i]->query;
        mapping_cluster.ref = clusters[i]->ref;
        mapping_info.clusters.push_back(mapping_cluster);
      #ifndef RELEASE_VERSION
        int64_t reference_start = indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id];
        int64_t region_start = local_score->get_region().start;
        LOG_DEBUG_SPEC("start(%ld, %ld), end(%ld, %ld)\tstart(%ld, %ld), end(%ld, %ld)\n",
                       mapping_cluster.query.start, mapping_cluster.ref.start, mapping_cluster.query.end, mapping_cluster.ref.end,
                       mapping_cluster.query.start, mapping_cluster.ref.start - reference_start, mapping_cluster.query.end, mapping_cluster.ref.end - reference_start);
      #endif
    }
  }

  L1Results l1_info;
  l1_info.l1_l = l;
  l1_info.l1_k = 1.0f;
  l1_info.l1_lmin = l - l_diff;
  l1_info.l1_lmax = l + l_diff;
  l1_info.l1_confidence_abs = confidence_L1;
  l1_info.l1_std = sigma_L2;
  l1_info.l1_rough_start = l1_info.l1_k * 0 + l1_info.l1_lmin;
  l1_info.l1_rough_end = l1_info.l1_k * read->get_sequence_length() + l1_info.l1_lmax;
  if (l1_info.l1_rough_start < indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id])
    l1_info.l1_rough_start = indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id];
  if (l1_info.l1_rough_end >= (indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id] + indexes[0]->get_reference_lengths()[local_score->get_region().reference_id]))
    l1_info.l1_rough_end = (indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id] + indexes[0]->get_reference_lengths()[local_score->get_region().reference_id]) - 1;

  mapping_info.is_mapped = true;

  PathGraphEntry *new_entry = new PathGraphEntry(indexes[0], read, parameters, (Region &) local_score->get_region(), &mapping_info, &l1_info);

  LogSystem::GetInstance().Log(VERBOSE_LEVEL_HIGH_DEBUG, read->get_sequence_id() == parameters->debug_read, "\n", "[]");
  mapping_data->intermediate_mappings.push_back(new_entry);

  #ifndef RELEASE_VERSION
    if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
      LOG_DEBUG_SPEC("Writing all anchors to file scores-%ld.\n",  local_score->get_scores_id());
      VerboseLocalScoresToFile(FormatString("temp/local_scores/scores-%ld.csv", local_score->get_scores_id()), read, local_score, NULL, 0, 0, false);
      LOG_DEBUG_SPEC("Writing LCSk anchors to file LCS-%ld.\n",  local_score->get_scores_id());
      VerboseLocalScoresToFile(FormatString("temp/local_scores/LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &lcskpp_indices, 0, 0, false, NULL);
      LOG_DEBUG_SPEC("Writing cluster anchors to file LCSL1-%ld.\n",  local_score->get_scores_id());
      VerboseLocalScoresToFile(FormatString("temp/local_scores/LCSL1-%ld.csv", local_score->get_scores_id()), read, local_score, &second_filtered_lcskpp_indices, 0, 0, false);
      LOG_DEBUG_SPEC("Writing cluster anchors (again) to file double_LCS-%ld.\n",  local_score->get_scores_id());
      VerboseLocalScoresToFile(FormatString("temp/local_scores/double_LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &cluster_indices, l, 3.0f * confidence_L1, false, &cluster_ids);

      LOG_DEBUG_SPEC("LCSk clusters:\n");
      for (int64_t i=0; i<clusters.size(); i++) {
        LOG_DEBUG_SPEC_NO_HEADER("[%ld] num_anchors: %ld, length: %ld, coverage: %ld, query.start = %ld, query.end = %ld\n", i, clusters[i]->num_anchors, (clusters[i]->query.end - clusters[i]->query.start), clusters[i]->coverage, clusters[i]->query.start, clusters[i]->query.end);
      }
      LOG_DEBUG_SPEC_NEWLINE;
      LOG_DEBUG_SPEC("mapping_info.clusters:\n");
      for (int64_t i=0; i<mapping_info.clusters.size(); i++) {
        LOG_DEBUG_SPEC_NO_HEADER("[%ld] query.start = %ld, query.end = %ld, ref.start = %ld, ref.end = %ld\n", i, mapping_info.clusters[i].query.start, mapping_info.clusters[i].query.end, mapping_info.clusters[i].ref.start, mapping_info.clusters[i].ref.end);
      }
      LOG_DEBUG_SPEC_NEWLINE;
      VerboseClustersToFile_(FormatString("temp/clusters/clusters-read-%ld.csv", read->get_sequence_id()), local_score, mapping_data, indexes, read, parameters, clusters);
    }
    LOG_DEBUG_SPEC("Exiting function. [time: %.2f sec, RSS: %ld MB, peakRSS: %ld MB]\n", (((float) (clock())) / CLOCKS_PER_SEC), getCurrentRSS() / (1024 * 1024), getPeakRSS() / (1024 * 1024));
  #endif

  for (int64_t i=0; i<clusters.size(); i++) {
    if (clusters[i]) {
      delete clusters[i];
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <chartsql/qtree/CallExpressionNode.h>

using namespace fnord;

namespace csql {

CallExpressionNode::CallExpressionNode(
    const String& symbol,
    Vector<RefPtr<ValueExpressionNode>> arguments) :
    symbol_(symbol),
    arguments_(arguments) {}

Vector<RefPtr<ValueExpressionNode>> CallExpressionNode::arguments() const {
  return arguments_;
}

const String& CallExpressionNode::symbol() const {
  return symbol_;
}

RefPtr<QueryTreeNode> CallExpressionNode::deepCopy() const {
  Vector<RefPtr<ValueExpressionNode>> args;
  for (const auto& arg : arguments_) {
    args.emplace_back(arg->deepCopyAs<ValueExpressionNode>());
  }

  return new CallExpressionNode(symbol_, args);
}

} // namespace csql

<commit_msg>impl CallExpressionNode::toSQL<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <chartsql/qtree/CallExpressionNode.h>

using namespace fnord;

namespace csql {

CallExpressionNode::CallExpressionNode(
    const String& symbol,
    Vector<RefPtr<ValueExpressionNode>> arguments) :
    symbol_(symbol),
    arguments_(arguments) {}

Vector<RefPtr<ValueExpressionNode>> CallExpressionNode::arguments() const {
  return arguments_;
}

const String& CallExpressionNode::symbol() const {
  return symbol_;
}

RefPtr<QueryTreeNode> CallExpressionNode::deepCopy() const {
  Vector<RefPtr<ValueExpressionNode>> args;
  for (const auto& arg : arguments_) {
    args.emplace_back(arg->deepCopyAs<ValueExpressionNode>());
  }

  return new CallExpressionNode(symbol_, args);
}

String CallExpressionNode::toSQL() const {
  Vector<String> args_sql;
  for (const auto& a : arguments_) {
    args_sql.emplace_back(a->toSQL());
  }

  return StringUtil::format(
      "$0($1)",
      symbol_,
      StringUtil::join(args_sql, ","));
}

} // namespace csql

<|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Arman Pazouki
// =============================================================================
//
// Utility function to print the save fluid, bce, and boundary data into file
// =============================================================================
#include "chrono_fsi/utils/ChUtilsPrintSph.h"
#include "chrono_fsi/ChDeviceUtils.cuh"
#include "chrono_fsi/ChParams.cuh"
#include <fstream>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <thrust/reduce.h>

namespace chrono {
namespace fsi {
namespace utils {
//*******************************************************************************************************************************
void PrintToFile(const thrust::device_vector<Real3> &posRadD,
                 const thrust::device_vector<Real3> &velMasD,
                 const thrust::device_vector<Real4> &rhoPresMuD,
                 const thrust::host_vector<int4> &referenceArray,
                 const std::string &out_dir,
		 bool printToParaview) {

  thrust::host_vector<Real3> posRadH = posRadD;
  thrust::host_vector<Real3> velMasH = velMasD;
  thrust::host_vector<Real4> rhoPresMuH = rhoPresMuD;

  char fileCounter[5];
  static int dumNumChar = -1;
  dumNumChar++;
  sprintf(fileCounter, "%d", dumNumChar);

  //*****************************************************
  const std::string nameFluid = out_dir + std::string("/fluid") +
                                std::string(fileCounter) + std::string(".csv");

  std::ofstream fileNameFluidParticles;
  fileNameFluidParticles.open(nameFluid);
  std::stringstream ssFluidParticles;
  if(printToParaview)
     ssFluidParticles << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";

  for (int i = referenceArray[0].x; i < referenceArray[0].y; i++) {
    Real3 pos = posRadH[i];
    Real3 vel = velMasH[i];
    Real4 rP = rhoPresMuH[i];
    Real velMag = length(vel);
    ssFluidParticles << pos.x << ", " << pos.y << ", " << pos.z << ", " << vel.x
                     << ", " << vel.y << ", " << vel.z << ", " << velMag << ", "
                     << rP.x << ", " << rP.y << ", " << rP.w << ", "
                     << std::endl;
  }
  fileNameFluidParticles << ssFluidParticles.str();
  fileNameFluidParticles.close();
  //*****************************************************
  const std::string nameFluidBoundaries =
      out_dir + std::string("/fluid_boundary") + std::string(fileCounter) +
      std::string(".csv");

  std::ofstream fileNameFluidBoundaries;
  fileNameFluidBoundaries.open(nameFluidBoundaries);
  std::stringstream ssFluidBoundaryParticles;
    if(printToParaview)
     ssFluidParticles << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";

  //		ssFluidBoundaryParticles.precision(20);
  for (int i = referenceArray[0].x; i < referenceArray[1].y; i++) {
    Real3 pos = posRadH[i];
    Real3 vel = velMasH[i];
    Real4 rP = rhoPresMuH[i];
    Real velMag = length(vel);
    ssFluidBoundaryParticles << pos.x << ", " << pos.y << ", " << pos.z << ", "
                             << vel.x << ", " << vel.y << ", " << vel.z << ", "
                             << velMag << ", " << rP.x << ", " << rP.y << ", "
                             << rP.z << ", " << rP.w << ", " << std::endl;
  }
  fileNameFluidBoundaries << ssFluidBoundaryParticles.str();
  fileNameFluidBoundaries.close();
  //*****************************************************
  const std::string nameBCE = out_dir + std::string("/BCE") +
                              std::string(fileCounter) + std::string(".csv");

  std::ofstream fileNameBCE;
  fileNameBCE.open(nameBCE);
  std::stringstream ssBCE;
  //		ssFluidBoundaryParticles.precision(20);
  if(printToParaview)
     ssFluidParticles << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";

  int refSize = referenceArray.size();
  if (refSize > 2) {
    for (int i = referenceArray[2].x; i < referenceArray[refSize - 1].y; i++) {
      Real3 pos = posRadH[i];
      Real3 vel = velMasH[i];
      Real4 rP = rhoPresMuH[i];
      Real velMag = length(vel);

      ssBCE << pos.x << ", " << pos.y << ", " << pos.z << ", " << vel.x << ", "
            << vel.y << ", " << vel.z << ", " << velMag << ", " << rP.x << ", "
            << rP.y << ", " << rP.z << ", " << rP.w << ", " << std::endl;
    }
  }
  fileNameBCE << ssBCE.str();
  fileNameBCE.close();
  //*****************************************************
  posRadH.clear();
  velMasH.clear();
  rhoPresMuH.clear();
}

} // end namespace utils
} // end namespace fsi
} // end namespace chrono
<commit_msg>bug fix in exporting to paraview file<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Arman Pazouki
// =============================================================================
//
// Utility function to print the save fluid, bce, and boundary data into file
// =============================================================================
#include "chrono_fsi/utils/ChUtilsPrintSph.h"
#include "chrono_fsi/ChDeviceUtils.cuh"
#include "chrono_fsi/ChParams.cuh"
#include <fstream>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <thrust/reduce.h>

namespace chrono {
namespace fsi {
namespace utils {
//*******************************************************************************************************************************
void PrintToFile(const thrust::device_vector<Real3> &posRadD,
                 const thrust::device_vector<Real3> &velMasD,
                 const thrust::device_vector<Real4> &rhoPresMuD,
                 const thrust::host_vector<int4> &referenceArray,
                 const std::string &out_dir,
		 bool printToParaview) {

  thrust::host_vector<Real3> posRadH = posRadD;
  thrust::host_vector<Real3> velMasH = velMasD;
  thrust::host_vector<Real4> rhoPresMuH = rhoPresMuD;

  char fileCounter[5];
  static int dumNumChar = -1;
  dumNumChar++;
  sprintf(fileCounter, "%d", dumNumChar);

  //*****************************************************
  const std::string nameFluid = out_dir + std::string("/fluid") +
                                std::string(fileCounter) + std::string(".csv");

  std::ofstream fileNameFluidParticles;
  fileNameFluidParticles.open(nameFluid);
  std::stringstream ssFluidParticles;
  if(printToParaview)
     ssFluidParticles << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";

  for (int i = referenceArray[0].x; i < referenceArray[0].y; i++) {
    Real3 pos = posRadH[i];
    Real3 vel = velMasH[i];
    Real4 rP = rhoPresMuH[i];
    Real velMag = length(vel);
    ssFluidParticles << pos.x << ", " << pos.y << ", " << pos.z << ", " << vel.x
                     << ", " << vel.y << ", " << vel.z << ", " << velMag << ", "
                     << rP.x << ", " << rP.y << ", " << rP.w << ", "
                     << std::endl;
  }
  fileNameFluidParticles << ssFluidParticles.str();
  fileNameFluidParticles.close();
  //*****************************************************
  const std::string nameFluidBoundaries =
      out_dir + std::string("/fluid_boundary") + std::string(fileCounter) +
      std::string(".csv");

  std::ofstream fileNameFluidBoundaries;
  fileNameFluidBoundaries.open(nameFluidBoundaries);
  std::stringstream ssFluidBoundaryParticles;
    if(printToParaview)
     ssFluidBoundaryParticles << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";

  //		ssFluidBoundaryParticles.precision(20);
  for (int i = referenceArray[0].x; i < referenceArray[1].y; i++) {
    Real3 pos = posRadH[i];
    Real3 vel = velMasH[i];
    Real4 rP = rhoPresMuH[i];
    Real velMag = length(vel);
    ssFluidBoundaryParticles << pos.x << ", " << pos.y << ", " << pos.z << ", "
                             << vel.x << ", " << vel.y << ", " << vel.z << ", "
                             << velMag << ", " << rP.x << ", " << rP.y << ", "
                             << rP.z << ", " << rP.w << ", " << std::endl;
  }
  fileNameFluidBoundaries << ssFluidBoundaryParticles.str();
  fileNameFluidBoundaries.close();
  //*****************************************************
  const std::string nameBCE = out_dir + std::string("/BCE") +
                              std::string(fileCounter) + std::string(".csv");

  std::ofstream fileNameBCE;
  fileNameBCE.open(nameBCE);
  std::stringstream ssBCE;
  //		ssFluidBoundaryParticles.precision(20);
  if(printToParaview)
     ssBCE << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";

  int refSize = referenceArray.size();
  if (refSize > 2) {
    for (int i = referenceArray[2].x; i < referenceArray[refSize - 1].y; i++) {
      Real3 pos = posRadH[i];
      Real3 vel = velMasH[i];
      Real4 rP = rhoPresMuH[i];
      Real velMag = length(vel);

      ssBCE << pos.x << ", " << pos.y << ", " << pos.z << ", " << vel.x << ", "
            << vel.y << ", " << vel.z << ", " << velMag << ", " << rP.x << ", "
            << rP.y << ", " << rP.z << ", " << rP.w << ", " << std::endl;
    }
  }
  fileNameBCE << ssBCE.str();
  fileNameBCE.close();
  //*****************************************************
  posRadH.clear();
  velMasH.clear();
  rhoPresMuH.clear();
}

} // end namespace utils
} // end namespace fsi
} // end namespace chrono
<|endoftext|>


<commit_before><commit_msg>remove empty file, leftover from r384<commit_after><|endoftext|>