<commit_before>#include <unistd.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <algorithm>
#include <vector>
#include <math.h>
#include <sstream>
using namespace std;
const string VERSION = "0.4.0";
const int MAX_READ_LENGTH = 50000000;

class Stats {
    public:
        unsigned long int total_bp;

        // Read stats
        vector<unsigned int> read_length;
        vector<unsigned int> read_length_count;
        unsigned long int read_total;
        unsigned int read_min;
        unsigned int read_max;
        double read_mean;
        double read_std;
        double read_median;
        double read_25th;
        double read_75th;

        // Qual stats
        vector<double> per_read_qual;
        vector<unsigned int> per_base_qual;
        vector<unsigned int> per_base_count;
        int phred;
        unsigned int qual_min;
        unsigned int qual_max;
        double qual_sum;
        double qual_mean;
        double qual_median;
        double qual_25th;
        double qual_75th;
        double qual_std;

        void init(void) {
            read_total = 0;
            total_bp = 0;
            qual_sum = 0;
            read_length_count.resize(MAX_READ_LENGTH,0);
            per_base_qual.resize(MAX_READ_LENGTH,0);
            per_base_count.resize(MAX_READ_LENGTH,0);
            phred = 33;
        }

        double get_percentile(vector<double> array, size_t size, float percentile) {
            if (size % 2 == 0) {
                int p = int(size * percentile - 1);
                return (array[p] + array[p]) / 2.0;
            } else {
                int p = int(size * percentile);
                return array[p];
            }
        }

        double get_std(vector<double> array, double mean) {
            double temp = 0;
            for (unsigned int i = 0; i < read_total; i++) {
                temp += pow(((array[i]-phred) - mean), 2);
            }
            return sqrt(temp / read_total);
        }

        double get_percentile(vector<unsigned int> array, size_t size, float percentile) {
            if (size % 2 == 0) {
                int p = int(size * percentile - 1);
                return (array[p] + array[p]) / 2.0;
            } else {
                int p = int(size * percentile);
                return array[p];
            }
        }

        double get_std(vector<unsigned int> array, double mean) {
            double temp = 0;
            for (unsigned int i = 0; i < read_total; i++) {
                temp += pow((array[i] - mean), 2);
            }
            return sqrt(temp / read_total);
        }

        void transform_quality(string qual) {
            unsigned int total = 0;
            total_bp += qual.length();
            read_length_count[qual.length()]++;
            for (unsigned int i = 0; i < qual.length(); i++) {
                unsigned int qual_val = (unsigned int)qual[i];
                per_base_qual[i] += qual_val;
                per_base_count[i]++;
                total += qual_val;
            }
            double avg_qual = total / qual.length();
            qual_sum += avg_qual;
            per_read_qual.push_back(avg_qual);
        }

        void read_stats(void) {
            sort(read_length.begin(), read_length.end());
            read_min = read_length.front();
            read_mean = total_bp / float(read_total);
            read_std = get_std(read_length, read_mean);
            read_max = read_length.back();
            read_25th = get_percentile(read_length, read_length.size(), 0.25);
            read_median = get_percentile(read_length, read_length.size(), 0.50);
            read_75th = get_percentile(read_length, read_length.size(), 0.75);
        }

        void qual_stats(void) {
            sort(per_read_qual.begin(), per_read_qual.end());
            qual_min = per_read_qual.front() - phred;
            qual_mean = (qual_sum / read_total) - phred;
            qual_std = get_std(per_read_qual, qual_mean);
            qual_max = per_read_qual.back() - phred;
            qual_25th = get_percentile(per_read_qual, per_read_qual.size(), 0.25) - phred;
            qual_median = get_percentile(per_read_qual, per_read_qual.size(), 0.50) - phred;
            qual_75th = get_percentile(per_read_qual, per_read_qual.size(), 0.75) - phred;
        }

        void jsonify_stats(float GENOME_SIZE) {
            string t1 = "    ";
            string t2 = "        ";
            cout << "{" << endl;
            cout << t1 << "\"qc_stats\": {" << endl;
            cout << t2 << "\"total_bp\":" << total_bp << "," << endl;
            if (GENOME_SIZE == 1)  {
                cout << t2 << "\"coverage\": 0.00," << endl;
            } else {
                cout << t2 << "\"coverage\":" << total_bp / GENOME_SIZE << "," << endl;
            }
            cout << t2 << "\"read_total\":" << read_total << "," << endl;
            cout << t2 << "\"read_min\":" << read_min << "," << endl;
            cout << t2 << "\"read_mean\":" << read_mean << "," << endl;
            cout << t2 << "\"read_std\":" << read_std << "," << endl;
            cout << t2 << "\"read_median\":" << read_median << "," << endl;
            cout << t2 << "\"read_max\":" << read_max << "," << endl;
            cout << t2 << "\"read_25th\":" << read_25th << "," << endl;
            cout << t2 << "\"read_75th\":" << read_75th << "," << endl;
            cout << t2 << "\"qual_min\":" << qual_min << "," << endl;
            cout << t2 << "\"qual_mean\":" << qual_mean << "," << endl;
            cout << t2 << "\"qual_std\":" << qual_std << "," << endl;
            cout << t2 << "\"qual_max\":" << qual_max << "," << endl;
            cout << t2 << "\"qual_median\":" << qual_median << "," << endl;
            cout << t2 << "\"qual_25th\":" << qual_25th << "," << endl;
            cout << t2 << "\"qual_75th\":" << qual_75th << endl;
            cout << t1 << "}," << endl;
            cout << t1 << "\"read_lengths\": {" << endl;
            for (unsigned int i = read_min; i <= read_max; i++) {
                if (i % 5 == 0) {
                    cout << endl;
                }
                cout << t2 << "\"" << i << "\":" << read_length_count[i];
                if (i < read_max) {
                    cout << ",";
                }
            }
            cout << endl << t1 << "}," << endl;
            cout << t1 << "\"per_base_quality\": {" << endl;
            for (unsigned int i = 0; i < read_max; i++) {
                if (i % 5 == 0 && i != 0) {
                    cout << endl;
                }
                cout << t2 << "\"" << i + 1 << "\":" << (per_base_qual[i] / float(per_base_count[i])) - phred;
                if (i < read_max - 1) {
                    cout << ",";
                }
            }
            cout << endl << t1 << "}" << endl;
            cout << "}" << endl;
        }
};

static int usage()
{
    cout << "Usage: cat FASTQ | fastq-scan [options]" << endl;
    cout << "Version: " << VERSION << endl;
    cout << endl;
    cout << "Optional arguments:" << endl;
    cout << "    -g INT   Genome size for calculating estimated sequencing coverage. (Default 1)" << endl;
    cout << "    -p INT   ASCII offset for input quality scores, can be 33 or 64. (Default 33)" << endl;
    cout << "    -v       Print version information and exit" << endl;
    cout << "    -h       Show this message and exit" << endl;
    cout << endl;
    return 0;
}

static int version()
{
    cout << "fastq-scan " << VERSION << endl;
    return 0;
}

int main(int argc, char **argv) {
    // Read command line
    float GENOME_SIZE =  1.0;
    int PHRED_OFFSET = 33;
    int opt;
    while ((opt = getopt(argc, argv, "g:p:vh")) >= 0) {
        switch (opt) {
            case 'g': GENOME_SIZE = atof(optarg); break;
            case 'p': PHRED_OFFSET = atoi(optarg); break;
            case 'v': return version();
            case 'h': return usage();
        }
    }
    if (!(PHRED_OFFSET == 33 || PHRED_OFFSET == 64)) {
        cerr << "Invalid value for -p (" << PHRED_OFFSET << "), only 33 or 64 are valid" << endl;
        return 1;
    }
    if (isatty(0)) return usage();

    // Parse FASTQ
    Stats stats;
    stats.init();
    stats.phred = PHRED_OFFSET;
    string name, seq, plus, qual;
    ifstream in("/dev/stdin", ios::in);
    while(true) {
        if(!getline(in, name, '\n')) break;
        if(!getline(in, seq, '\n')) break;
        if(!getline(in, plus, '\n')) break;
        if(!getline(in, qual, '\n')) break;
        stats.read_length.push_back(seq.length());
        stats.read_total++;
        stats.transform_quality(qual);
    }
    in.close();

    // Determine Stats
    stats.read_stats();
    stats.qual_stats();
    stats.jsonify_stats(GENOME_SIZE);
    return 0;
}
<commit_msg>Treat genome size of 0 the same as 1<commit_after>#include <unistd.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <algorithm>
#include <vector>
#include <math.h>
#include <sstream>
using namespace std;
const string VERSION = "0.4.1";
const int MAX_READ_LENGTH = 50000000;

class Stats {
    public:
        unsigned long int total_bp;

        // Read stats
        vector<unsigned int> read_length;
        vector<unsigned int> read_length_count;
        unsigned long int read_total;
        unsigned int read_min;
        unsigned int read_max;
        double read_mean;
        double read_std;
        double read_median;
        double read_25th;
        double read_75th;

        // Qual stats
        vector<double> per_read_qual;
        vector<unsigned int> per_base_qual;
        vector<unsigned int> per_base_count;
        int phred;
        unsigned int qual_min;
        unsigned int qual_max;
        double qual_sum;
        double qual_mean;
        double qual_median;
        double qual_25th;
        double qual_75th;
        double qual_std;

        void init(void) {
            read_total = 0;
            total_bp = 0;
            qual_sum = 0;
            read_length_count.resize(MAX_READ_LENGTH,0);
            per_base_qual.resize(MAX_READ_LENGTH,0);
            per_base_count.resize(MAX_READ_LENGTH,0);
            phred = 33;
        }

        double get_percentile(vector<double> array, size_t size, float percentile) {
            if (size % 2 == 0) {
                int p = int(size * percentile - 1);
                return (array[p] + array[p]) / 2.0;
            } else {
                int p = int(size * percentile);
                return array[p];
            }
        }

        double get_std(vector<double> array, double mean) {
            double temp = 0;
            for (unsigned int i = 0; i < read_total; i++) {
                temp += pow(((array[i]-phred) - mean), 2);
            }
            return sqrt(temp / read_total);
        }

        double get_percentile(vector<unsigned int> array, size_t size, float percentile) {
            if (size % 2 == 0) {
                int p = int(size * percentile - 1);
                return (array[p] + array[p]) / 2.0;
            } else {
                int p = int(size * percentile);
                return array[p];
            }
        }

        double get_std(vector<unsigned int> array, double mean) {
            double temp = 0;
            for (unsigned int i = 0; i < read_total; i++) {
                temp += pow((array[i] - mean), 2);
            }
            return sqrt(temp / read_total);
        }

        void transform_quality(string qual) {
            unsigned int total = 0;
            total_bp += qual.length();
            read_length_count[qual.length()]++;
            for (unsigned int i = 0; i < qual.length(); i++) {
                unsigned int qual_val = (unsigned int)qual[i];
                per_base_qual[i] += qual_val;
                per_base_count[i]++;
                total += qual_val;
            }
            double avg_qual = total / qual.length();
            qual_sum += avg_qual;
            per_read_qual.push_back(avg_qual);
        }

        void read_stats(void) {
            sort(read_length.begin(), read_length.end());
            read_min = read_length.front();
            read_mean = total_bp / float(read_total);
            read_std = get_std(read_length, read_mean);
            read_max = read_length.back();
            read_25th = get_percentile(read_length, read_length.size(), 0.25);
            read_median = get_percentile(read_length, read_length.size(), 0.50);
            read_75th = get_percentile(read_length, read_length.size(), 0.75);
        }

        void qual_stats(void) {
            sort(per_read_qual.begin(), per_read_qual.end());
            qual_min = per_read_qual.front() - phred;
            qual_mean = (qual_sum / read_total) - phred;
            qual_std = get_std(per_read_qual, qual_mean);
            qual_max = per_read_qual.back() - phred;
            qual_25th = get_percentile(per_read_qual, per_read_qual.size(), 0.25) - phred;
            qual_median = get_percentile(per_read_qual, per_read_qual.size(), 0.50) - phred;
            qual_75th = get_percentile(per_read_qual, per_read_qual.size(), 0.75) - phred;
        }

        void jsonify_stats(float GENOME_SIZE) {
            string t1 = "    ";
            string t2 = "        ";
            cout << "{" << endl;
            cout << t1 << "\"qc_stats\": {" << endl;
            cout << t2 << "\"total_bp\":" << total_bp << "," << endl;
            if (GENOME_SIZE <= 1)  {
                cout << t2 << "\"coverage\": 0.00," << endl;
            } else {
                cout << t2 << "\"coverage\":" << total_bp / GENOME_SIZE << "," << endl;
            }
            cout << t2 << "\"read_total\":" << read_total << "," << endl;
            cout << t2 << "\"read_min\":" << read_min << "," << endl;
            cout << t2 << "\"read_mean\":" << read_mean << "," << endl;
            cout << t2 << "\"read_std\":" << read_std << "," << endl;
            cout << t2 << "\"read_median\":" << read_median << "," << endl;
            cout << t2 << "\"read_max\":" << read_max << "," << endl;
            cout << t2 << "\"read_25th\":" << read_25th << "," << endl;
            cout << t2 << "\"read_75th\":" << read_75th << "," << endl;
            cout << t2 << "\"qual_min\":" << qual_min << "," << endl;
            cout << t2 << "\"qual_mean\":" << qual_mean << "," << endl;
            cout << t2 << "\"qual_std\":" << qual_std << "," << endl;
            cout << t2 << "\"qual_max\":" << qual_max << "," << endl;
            cout << t2 << "\"qual_median\":" << qual_median << "," << endl;
            cout << t2 << "\"qual_25th\":" << qual_25th << "," << endl;
            cout << t2 << "\"qual_75th\":" << qual_75th << endl;
            cout << t1 << "}," << endl;
            cout << t1 << "\"read_lengths\": {" << endl;
            for (unsigned int i = read_min; i <= read_max; i++) {
                if (i % 5 == 0) {
                    cout << endl;
                }
                cout << t2 << "\"" << i << "\":" << read_length_count[i];
                if (i < read_max) {
                    cout << ",";
                }
            }
            cout << endl << t1 << "}," << endl;
            cout << t1 << "\"per_base_quality\": {" << endl;
            for (unsigned int i = 0; i < read_max; i++) {
                if (i % 5 == 0 && i != 0) {
                    cout << endl;
                }
                cout << t2 << "\"" << i + 1 << "\":" << (per_base_qual[i] / float(per_base_count[i])) - phred;
                if (i < read_max - 1) {
                    cout << ",";
                }
            }
            cout << endl << t1 << "}" << endl;
            cout << "}" << endl;
        }
};

static int usage()
{
    cout << "Usage: cat FASTQ | fastq-scan [options]" << endl;
    cout << "Version: " << VERSION << endl;
    cout << endl;
    cout << "Optional arguments:" << endl;
    cout << "    -g INT   Genome size for calculating estimated sequencing coverage. (Default 1)" << endl;
    cout << "    -p INT   ASCII offset for input quality scores, can be 33 or 64. (Default 33)" << endl;
    cout << "    -v       Print version information and exit" << endl;
    cout << "    -h       Show this message and exit" << endl;
    cout << endl;
    return 0;
}

static int version()
{
    cout << "fastq-scan " << VERSION << endl;
    return 0;
}

int main(int argc, char **argv) {
    // Read command line
    float GENOME_SIZE =  1.0;
    int PHRED_OFFSET = 33;
    int opt;
    while ((opt = getopt(argc, argv, "g:p:vh")) >= 0) {
        switch (opt) {
            case 'g': GENOME_SIZE = atof(optarg); break;
            case 'p': PHRED_OFFSET = atoi(optarg); break;
            case 'v': return version();
            case 'h': return usage();
        }
    }
    if (!(PHRED_OFFSET == 33 || PHRED_OFFSET == 64)) {
        cerr << "Invalid value for -p (" << PHRED_OFFSET << "), only 33 or 64 are valid" << endl;
        return 1;
    } else if (GENOME_SIZE < 0)) {
        cerr << "Invalid value for -g (" << GENOME_SIZE << "), value muse be >= 0" << endl;
        return 1;
    }

    if (isatty(0)) return usage();

    // Parse FASTQ
    Stats stats;
    stats.init();
    stats.phred = PHRED_OFFSET;
    string name, seq, plus, qual;
    ifstream in("/dev/stdin", ios::in);
    while(true) {
        if(!getline(in, name, '\n')) break;
        if(!getline(in, seq, '\n')) break;
        if(!getline(in, plus, '\n')) break;
        if(!getline(in, qual, '\n')) break;
        stats.read_length.push_back(seq.length());
        stats.read_total++;
        stats.transform_quality(qual);
    }
    in.close();

    // Determine Stats
    stats.read_stats();
    stats.qual_stats();
    stats.jsonify_stats(GENOME_SIZE);
    return 0;
}
<|endoftext|>


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

#ifndef DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
#define DUNE_GDT_ASSEMBLER_GRIDWALKER_HH

#include <vector>
#include <memory>
#include <type_traits>

#include <dune/stuff/grid/boundaryinfo.hh>

namespace Dune {
namespace GDT {
namespace Functor {

template< class GridViewImp >
class Codim0
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;

  virtual ~Codim0() {}

  virtual void prepare() {}

  virtual void apply_local(const EntityType& entity) = 0;

  virtual void finalize() {}
}; // class Codim0

template< class GridViewImp >
class Codim1
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity  EntityType;
  typedef typename GridViewType::Intersection                 IntersectionType;

  virtual ~Codim1() {}

  virtual void prepare() {}

  virtual void apply_local(const IntersectionType& intersection) = 0;

  virtual void finalize() {}
}; // class Codim1

} // namespace Functor
namespace ApplyOn {

/**
 *  \brief Interface for functors to tell on which entity to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const
{
  ...
}
\endcode
 */
template< class GridViewImp >
class WhichEntity
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;

  virtual ~ WhichEntity() {}

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const = 0;
}; // class WhichEntity

/**
 *  \brief Selects all entities.
 */
template< class GridViewImp >
class AllEntities
  : public WhichEntity< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const DS_FINAL
  {
    return true;
  }
}; // class AllEntities

/**
 *  \brief Selects entities which have a boundary intersection.
 */
template< class GridViewImp >
class BoundaryEntities
  : public WhichEntity< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& entity) const DS_FINAL
  {
    return entity.hasBoundaryIntersections();
  }
}; // class BoundaryEntities

/**
 *  \brief Interface for functors to tell on which intersection to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const
{
  ...
}
\endcode
 */
template< class GridViewImp >
class WhichIntersection
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~ WhichIntersection< GridViewImp >() {}

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& /*intersection*/) const = 0;
}; // class WhichIntersection< GridViewImp >

/**
 *  \brief Selects all intersections.
 */
template< class GridViewImp >
class AllIntersections
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& /*intersection*/) const DS_FINAL
  {
    return true;
  }
}; // class AllIntersections

/**
 *  \brief Selects each inner intersection.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used.
 */
template< class GridViewImp >
class InnerIntersections
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_FINAL
  {
    return intersection.neighbor() && !intersection.boundary();
  }
}; // class InnerIntersections

/**
 *  \brief Selects each inner intersection only once.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used, and true is returned, if the index of the inside() entity is smaller than the index of the outside()
 *  entity.
 */
template< class GridViewImp >
class InnerIntersectionsPrimally
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_FINAL
  {
    if (intersection.neighbor() && !intersection.boundary()) {
      const auto insideEntityPtr = intersection.inside();
      const auto& insideEntity = *insideEntityPtr;
      const auto outsideNeighborPtr = intersection.outside();
      const auto& outsideNeighbor = *outsideNeighborPtr;
      return grid_view.indexSet().index(insideEntity) < grid_view.indexSet().index(outsideNeighbor);
    } else
      return false;
  }
}; // class InnerIntersections

template< class GridViewImp >
class BoundaryIntersections
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_FINAL
  {
    return intersection.boundary();
  }
}; // class BoundaryIntersections

template< class GridViewImp >
class DirichletIntersections
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection           IntersectionType;
  typedef Stuff::GridboundaryInterface< IntersectionType >  BoundaryInfoType;

  DirichletIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {}

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_FINAL
  {
    return boundary_info_.dirichlet(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class DirichletIntersections

template< class GridViewImp >
class NeumannIntersections
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection           IntersectionType;
  typedef Stuff::GridboundaryInterface< IntersectionType >  BoundaryInfoType;

  NeumannIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {}

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_FINAL
  {
    return boundary_info_.neumann(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class NeumannIntersections

} // namespace ApplyOn

template< class GridViewImp >
class GridWalker
{
  typedef GridWalker< GridViewImp > ThisType;
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity  EntityType;
  typedef typename GridViewType::Intersection                 IntersectionType;

protected:
  typedef Stuff::GridboundaryInterface< IntersectionType > BoundaryInfoType;

  class Codim0Object
    : public Functor::Codim0< GridViewType >
  {
  public:
    ~ Codim0Object() {}
    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const = 0;
  };

  template< class Codim0FunctorType >
  class Codim0FunctorWrapper
    : public Codim0Object
  {
  public:
    Codim0FunctorWrapper(Codim0FunctorType& wrapped_functor,
                         const ApplyOn::WhichEntity< GridViewType >* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {}

    virtual ~Codim0FunctorWrapper() {}

    virtual void prepare() DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_FINAL
    {
      return where_->apply_on(grid_view, entity);
    }

    virtual void apply_local(const EntityType& entity) DS_FINAL
    {
      wrapped_functor_.apply_local(entity);
    }

    virtual void finalize() DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim0FunctorType& wrapped_functor_;
    std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
  }; // class Codim0FunctorWrapper

  class Codim1Object
    : public Functor::Codim1< GridViewType >
  {
  public:
    ~ Codim1Object() {}
    virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const = 0;
  };

  template< class Codim1FunctorType >
  class Codim1FunctorWrapper
    : public Codim1Object
  {
  public:
    Codim1FunctorWrapper(Codim1FunctorType& wrapped_functor,
                         const ApplyOn::WhichIntersection< GridViewType >* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {}

    virtual void prepare() DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_FINAL
    {
      return where_->apply_on(grid_view, intersection);
    }

    virtual void apply_local(const IntersectionType& intersection) DS_FINAL
    {
      wrapped_functor_.apply_local(intersection);
    }

    virtual void finalize() DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim1FunctorType& wrapped_functor_;
    std::unique_ptr< const ApplyOn::WhichIntersection< GridViewType > > where_;
  }; // class Codim1FunctorWrapper

public:
  GridWalker(const GridViewType& grid_view)
    : grid_view_(grid_view)
  {}

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  void add(Functor::Codim0< GridViewType >& functor,
           const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
  {
    codim0_functors_.emplace_back(new Codim0FunctorWrapper< Functor::Codim0< GridViewType > >(functor, where));
  }

  void add(Functor::Codim1< GridViewType >& functor,
           const ApplyOn::WhichIntersection< GridViewType >* where
              = new ApplyOn::AllIntersections< GridViewType >())
  {
    codim1_functors_.emplace_back(new Codim1FunctorWrapper< Functor::Codim1< GridViewType > >(functor, where));
  }

  void walk(const bool clear_stack = true)
  {
    // prepare functors
    for (auto& functor : codim0_functors_)
      functor->prepare();
    for (auto& functor : codim1_functors_)
      functor->prepare();

    // only do something, if we have to
    if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {
      // walk the grid
      const auto entity_it_end = grid_view_.template end< 0 >();
      for(auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it ) {
        const EntityType& entity = *entity_it;

        // apply codim0 functors
        for (auto& functor : codim0_functors_)
          if (functor->apply_on(grid_view_, entity)) functor->apply_local(entity);

        // only walk the intersections, if there are codim1 functors present
        if (codim1_functors_.size() > 0) {
          // walk the intersections
          const auto intersection_it_end = grid_view_.iend(entity);
          for (auto intersection_it = grid_view_.ibegin(entity);
               intersection_it != intersection_it_end;
               ++intersection_it) {
            const auto& intersection = *intersection_it;

            // apply codim1 functors
            for (auto& functor : codim1_functors_)
              if (functor->apply_on(grid_view_, intersection)) functor->apply_local(intersection);

          } // walk the intersections
        } // only walk the intersections, if there are codim1 functors present
      } // walk the grid
    } // only do something, if we have to

    // finalize functors
    for (auto& functor : codim0_functors_)
      functor->finalize();
    for (auto& functor : codim1_functors_)
      functor->finalize();

    // clear the stack of functors
    if (clear_stack)
      clear();
  } // ... walk()

  void clear()
  {
    codim0_functors_ = std::vector< std::unique_ptr< Codim0Object > >();
    codim1_functors_ = std::vector< std::unique_ptr< Codim1Object > >();
  }

protected:
  const GridViewType& grid_view_;
  std::vector< std::unique_ptr< Codim0Object > > codim0_functors_;
  std::vector< std::unique_ptr< Codim1Object > > codim1_functors_;
}; // class GridWalker

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
<commit_msg>[assembler.gridwalker] added override and final keywords<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
#define DUNE_GDT_ASSEMBLER_GRIDWALKER_HH

#include <vector>
#include <memory>
#include <type_traits>

#include <dune/stuff/grid/boundaryinfo.hh>

namespace Dune {
namespace GDT {
namespace Functor {

template< class GridViewImp >
class Codim0
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;

  virtual ~Codim0() {}

  virtual void prepare() {}

  virtual void apply_local(const EntityType& entity) = 0;

  virtual void finalize() {}
}; // class Codim0

template< class GridViewImp >
class Codim1
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity  EntityType;
  typedef typename GridViewType::Intersection                 IntersectionType;

  virtual ~Codim1() {}

  virtual void prepare() {}

  virtual void apply_local(const IntersectionType& intersection) = 0;

  virtual void finalize() {}
}; // class Codim1

} // namespace Functor
namespace ApplyOn {

/**
 *  \brief Interface for functors to tell on which entity to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const
{
  ...
}
\endcode
 */
template< class GridViewImp >
class WhichEntity
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;

  virtual ~ WhichEntity() {}

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const = 0;
}; // class WhichEntity

/**
 *  \brief Selects all entities.
 */
template< class GridViewImp >
class AllEntities
  : public WhichEntity< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const DS_OVERRIDE DS_FINAL
  {
    return true;
  }
}; // class AllEntities

/**
 *  \brief Selects entities which have a boundary intersection.
 */
template< class GridViewImp >
class BoundaryEntities
  : public WhichEntity< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& entity) const DS_OVERRIDE DS_FINAL
  {
    return entity.hasBoundaryIntersections();
  }
}; // class BoundaryEntities

/**
 *  \brief Interface for functors to tell on which intersection to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const
{
  ...
}
\endcode
 */
template< class GridViewImp >
class WhichIntersection
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~ WhichIntersection< GridViewImp >() {}

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& /*intersection*/) const = 0;
}; // class WhichIntersection< GridViewImp >

/**
 *  \brief Selects all intersections.
 */
template< class GridViewImp >
class AllIntersections
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& /*intersection*/) const DS_OVERRIDE DS_FINAL
  {
    return true;
  }
}; // class AllIntersections

/**
 *  \brief Selects each inner intersection.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used.
 */
template< class GridViewImp >
class InnerIntersections
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return intersection.neighbor() && !intersection.boundary();
  }
}; // class InnerIntersections

/**
 *  \brief Selects each inner intersection only once.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used, and true is returned, if the index of the inside() entity is smaller than the index of the outside()
 *  entity.
 */
template< class GridViewImp >
class InnerIntersectionsPrimally
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    if (intersection.neighbor() && !intersection.boundary()) {
      const auto insideEntityPtr = intersection.inside();
      const auto& insideEntity = *insideEntityPtr;
      const auto outsideNeighborPtr = intersection.outside();
      const auto& outsideNeighbor = *outsideNeighborPtr;
      return grid_view.indexSet().index(insideEntity) < grid_view.indexSet().index(outsideNeighbor);
    } else
      return false;
  }
}; // class InnerIntersections

template< class GridViewImp >
class BoundaryIntersections
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return intersection.boundary();
  }
}; // class BoundaryIntersections

template< class GridViewImp >
class DirichletIntersections
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection           IntersectionType;
  typedef Stuff::GridboundaryInterface< IntersectionType >  BoundaryInfoType;

  DirichletIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {}

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return boundary_info_.dirichlet(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class DirichletIntersections

template< class GridViewImp >
class NeumannIntersections
  : public WhichIntersection< GridViewImp >
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection           IntersectionType;
  typedef Stuff::GridboundaryInterface< IntersectionType >  BoundaryInfoType;

  NeumannIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {}

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return boundary_info_.neumann(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class NeumannIntersections

} // namespace ApplyOn

template< class GridViewImp >
class GridWalker
{
  typedef GridWalker< GridViewImp > ThisType;
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim< 0 >::Entity  EntityType;
  typedef typename GridViewType::Intersection                 IntersectionType;

protected:
  typedef Stuff::GridboundaryInterface< IntersectionType > BoundaryInfoType;

  class Codim0Object
    : public Functor::Codim0< GridViewType >
  {
  public:
    ~ Codim0Object() {}
    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const = 0;
  };

  template< class Codim0FunctorType >
  class Codim0FunctorWrapper
    : public Codim0Object
  {
  public:
    Codim0FunctorWrapper(Codim0FunctorType& wrapped_functor,
                         const ApplyOn::WhichEntity< GridViewType >* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {}

    virtual ~Codim0FunctorWrapper() {}

    virtual void prepare() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL
    {
      return where_->apply_on(grid_view, entity);
    }

    virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.apply_local(entity);
    }

    virtual void finalize() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim0FunctorType& wrapped_functor_;
    std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
  }; // class Codim0FunctorWrapper

  class Codim1Object
    : public Functor::Codim1< GridViewType >
  {
  public:
    ~ Codim1Object() {}
    virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const = 0;
  };

  template< class Codim1FunctorType >
  class Codim1FunctorWrapper
    : public Codim1Object
  {
  public:
    Codim1FunctorWrapper(Codim1FunctorType& wrapped_functor,
                         const ApplyOn::WhichIntersection< GridViewType >* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {}

    virtual void prepare() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
    {
      return where_->apply_on(grid_view, intersection);
    }

    virtual void apply_local(const IntersectionType& intersection) DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.apply_local(intersection);
    }

    virtual void finalize() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim1FunctorType& wrapped_functor_;
    std::unique_ptr< const ApplyOn::WhichIntersection< GridViewType > > where_;
  }; // class Codim1FunctorWrapper

public:
  GridWalker(const GridViewType& grid_view)
    : grid_view_(grid_view)
  {}

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  void add(Functor::Codim0< GridViewType >& functor,
           const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
  {
    codim0_functors_.emplace_back(new Codim0FunctorWrapper< Functor::Codim0< GridViewType > >(functor, where));
  }

  void add(Functor::Codim1< GridViewType >& functor,
           const ApplyOn::WhichIntersection< GridViewType >* where
              = new ApplyOn::AllIntersections< GridViewType >())
  {
    codim1_functors_.emplace_back(new Codim1FunctorWrapper< Functor::Codim1< GridViewType > >(functor, where));
  }

  void walk(const bool clear_stack = true)
  {
    // prepare functors
    for (auto& functor : codim0_functors_)
      functor->prepare();
    for (auto& functor : codim1_functors_)
      functor->prepare();

    // only do something, if we have to
    if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {
      // walk the grid
      const auto entity_it_end = grid_view_.template end< 0 >();
      for(auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it ) {
        const EntityType& entity = *entity_it;

        // apply codim0 functors
        for (auto& functor : codim0_functors_)
          if (functor->apply_on(grid_view_, entity)) functor->apply_local(entity);

        // only walk the intersections, if there are codim1 functors present
        if (codim1_functors_.size() > 0) {
          // walk the intersections
          const auto intersection_it_end = grid_view_.iend(entity);
          for (auto intersection_it = grid_view_.ibegin(entity);
               intersection_it != intersection_it_end;
               ++intersection_it) {
            const auto& intersection = *intersection_it;

            // apply codim1 functors
            for (auto& functor : codim1_functors_)
              if (functor->apply_on(grid_view_, intersection)) functor->apply_local(intersection);

          } // walk the intersections
        } // only walk the intersections, if there are codim1 functors present
      } // walk the grid
    } // only do something, if we have to

    // finalize functors
    for (auto& functor : codim0_functors_)
      functor->finalize();
    for (auto& functor : codim1_functors_)
      functor->finalize();

    // clear the stack of functors
    if (clear_stack)
      clear();
  } // ... walk(...)

  void clear()
  {
    codim0_functors_ = std::vector< std::unique_ptr< Codim0Object > >();
    codim1_functors_ = std::vector< std::unique_ptr< Codim1Object > >();
  } // ... clear()

protected:
  const GridViewType& grid_view_;
  std::vector< std::unique_ptr< Codim0Object > > codim0_functors_;
  std::vector< std::unique_ptr< Codim1Object > > codim1_functors_;
}; // class GridWalker

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
<|endoftext|>


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

#ifndef DUNE_GDT_OPERATOR_PROJECTIONS_HH
#define DUNE_GDT_OPERATOR_PROJECTIONS_HH

#include <vector>
#include <type_traits>
#include <limits>

#include <dune/common/fvector.hh>

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/grid/intersection.hh>
#include <dune/stuff/common/vector.hh>

#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/space/continuouslagrange/fem.hh>
#include <dune/gdt/space/continuouslagrange/fem-localfunctions.hh>
#include <dune/gdt/space/discontinuouslagrange/fem-localfunctions.hh>

namespace Dune {
namespace GDT {
namespace ProjectionOperator {

/**
 *  \note If you add other dimension/polorder/space combinations, do not forget to add a testcase in tests/operators.cc
 */
template <class GridPartImp>
class L2
{
  typedef GridPartImp GridPartType;
  typedef typename GridPartType::template Codim<0>::EntityType EntityType;
  typedef typename GridPartType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridPartType::dimension;

public:
  L2(const GridPartType& grid_part)
    : grid_part_(grid_part)
  {
  }

  /**
   *  \brief  Does an L2 projection by using the lagrange points.
   */
  template <class GP, int p, class R, int r, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, R, r, 1>& source,
             DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<GP, p, R, r, 1>, V>& range) const
  {
    // clear range
    Stuff::Common::clear(range.vector());
    typedef DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<GP, p, R, r, 1>, V> RangeFunctionType;
    typedef typename RangeFunctionType::RangeType RangeType;
    RangeType local_source_value(0);
    // walk the grid
    const auto entity_it_end = grid_part_.template end<0>();
    for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity           = *entity_it;
      const auto local_source      = source.local_function(entity);
      auto local_range             = range.local_discrete_function(entity);
      auto& local_range_DoF_vector = local_range.vector();
      const auto lagrange_points = range.space().backend().lagrangePointSet(entity);
      assert(lagrange_points.nop() == local_range_DoF_vector.size());
      // and do the work
      for (size_t ii = 0; ii < lagrange_points.nop(); ++ii) {
        const auto& lagrange_point = lagrange_points.point(ii);
        local_source->evaluate(lagrange_point, local_source_value);
        local_range_DoF_vector.set(ii, local_source_value);
      }
    } // walk the grid
  } // ... apply(... ContinuousLagrangeSpace::FemWrapper ...)

  /**
   *  \brief  Does an L2 projection by using the lagrange points.
   */
  template <class GP, int p, class R, int r, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, R, r, 1>& source,
             DiscreteFunction<ContinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, p, R, r, 1>, V>& range) const
  {
    // clear range
    Stuff::Common::clear(range.vector());
    typedef DiscreteFunction<ContinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, p, R, r, 1>, V> RangeFunctionType;
    typedef typename RangeFunctionType::RangeType RangeType;
    RangeType local_source_value(0);
    // walk the grid
    const auto entity_it_end = grid_part_.template end<0>();
    for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity           = *entity_it;
      const auto local_source      = source.local_function(entity);
      auto local_range             = range.local_discrete_function(entity);
      auto& local_range_DoF_vector = local_range.vector();
      const auto lagrange_points = range.space().lagrange_points(entity);
      assert(lagrange_points.size() == local_range_DoF_vector.size());
      // and do the work
      for (size_t ii = 0; ii < lagrange_points.size(); ++ii) {
        const auto& lagrange_point = lagrange_points[ii];
        local_source->evaluate(lagrange_point, local_source_value);
        local_range_DoF_vector.set(ii, local_source_value);
      }
    } // walk the grid
  } // ... apply(... ContinuousLagrangeSpace::FemLocalfunctionsWrapper ...)

  /**
   *  \brief  Does an L2 projection by solving the local problems.
   */
  template <class GP, int p, class R, int r, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, R, r, 1>& source,
             DiscreteFunction<DiscontinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, p, R, r, 1>, V>& range) const
  {
    typedef DiscontinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, p, R, r, 1> SpaceType;
    typedef typename SpaceType::BaseFunctionSetType::RangeType RangeType;
    // clear
    Stuff::Common::clear(range.vector());
    // walk the grid
    RangeType source_value(0);
    std::vector<RangeType> basis_values(range.space().mapper().maxNumDofs());
    const auto entity_it_end = grid_part_.template end<0>();
    for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      // prepare
      const auto& entity      = *entity_it;
      const auto local_basis  = range.space().baseFunctionSet(entity);
      const auto local_source = source.local_function(entity);
      auto local_range = range.local_discrete_function(entity);
      DynamicMatrix<R> local_matrix(local_basis.size(), local_basis.size(), R(0));
      DynamicVector<R> local_vector(local_basis.size(), R(0));
      // create quadrature
      const size_t quadrature_order = std::max(local_source->order(), local_range.order());
      assert((2 * quadrature_order + 1) < std::numeric_limits<int>::max());
      const auto& quadrature =
          QuadratureRules<DomainFieldType, dimDomain>::rule(entity.type(), int(2 * quadrature_order + 1));
      // loop over all quadrature points
      for (const auto& quadrature_point : quadrature) {
        const auto local_point         = quadrature_point.position();
        const auto quadrature_weight   = quadrature_point.weight();
        const auto integration_element = entity.geometry().integrationElement(local_point);
        // evaluate
        local_basis.evaluate(local_point, basis_values);
        local_source->evaluate(local_point, source_value);
        // compute integrals
        for (size_t ii = 0; ii < local_basis.size(); ++ii) {
          local_vector[ii] += integration_element * quadrature_weight * (source_value * basis_values[ii]);
          auto& local_matrix_row = local_matrix[ii];
          for (size_t jj = 0; jj < local_basis.size(); ++jj) {
            local_matrix_row[jj] += integration_element * quadrature_weight * (basis_values[ii] * basis_values[jj]);
          }
        }
      } // loop over all quadrature points
      // compute local DoFs
      DynamicVector<R> local_DoFs(local_basis.size(), 0);
      local_matrix.solve(local_DoFs, local_vector);
      // set local DoFs
      auto local_range_vector = local_range.vector();
      for (size_t ii = 0; ii < local_range_vector.size(); ++ii)
        local_range_vector.set(ii, local_DoFs[ii]);
    } // walk the grid
  } // ... apply(... DiscontinuousLagrangeSpace::FemLocalfunctionsWrapper ...)

private:
  const GridPartType& grid_part_;
}; // class L2

template <class GridPartImp>
class Dirichlet
{
public:
  typedef GridPartImp GridPartType;
  typedef Stuff::GridboundaryInterface<typename GridPartType::IntersectionType> BoundaryInfoType;

private:
  typedef typename GridPartType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridPartType::dimension;
  typedef FieldVector<DomainFieldType, dimDomain> DomainType;

  typedef typename GridPartType::template Codim<0>::EntityType EntityType;

public:
  Dirichlet(const GridPartType& grid_part, const BoundaryInfoType& boundary_info)
    : grid_part_(grid_part)
    , boundary_info_(boundary_info)
  {
  }

  template <class R, class GP, int p, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, R, 1, 1>& source,
             DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<GP, p, R, 1, 1>, V>& range) const
  {
    typedef DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<GP, p, R, 1, 1>, V> RangeType;
    // clear range
    range.vector().backend() *= 0.0;
    // walk the grid
    const auto entity_it_end = grid_part_.template end<0>();
    for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity = *entity_it;
      // only consider entities with boundary intersections
      if (entity.hasBoundaryIntersections()) {
        const auto source_local_function = source.local_function(entity);
        auto range_local_function        = range.local_discrete_function(entity);
        auto range_local_DoF_vector      = range_local_function.vector();
        const auto lagrangePointSet      = range.space().backend().lagrangePointSet(entity);
        // get the lagrange points' coordinates
        typedef typename RangeType::SpaceType::BackendType::LagrangePointSetType::CoordinateType
            LagrangePointCoordinateType;
        std::vector<LagrangePointCoordinateType> lagrangePoints(lagrangePointSet.nop(), LagrangePointCoordinateType(0));
        for (size_t ii = 0; ii < lagrangePointSet.nop(); ++ii)
          lagrangePoints[ii] = entity.geometry().global(lagrangePointSet.point(ii));
        // walk the intersections
        const auto intersection_it_end = grid_part_.iend(entity);
        for (auto intersection_it = grid_part_.ibegin(entity); intersection_it != intersection_it_end;
             ++intersection_it) {
          const auto& intersection = *intersection_it;
          // only consider dirichlet boundary intersection
          if (boundary_info_.dirichlet(intersection)) {
            // loop over all lagrange points
            for (size_t ii = 0; ii < lagrangePointSet.nop(); ++ii) {
              // if dof lies on the boundary intersection
              if (Dune::Stuff::Grid::intersectionContains(intersection, lagrangePoints[ii])) {
                // set the corresponding target dof
                range_local_DoF_vector.set(ii, source_local_function->evaluate(lagrangePointSet.point(ii)));
              } // if dof lies on the boundary intersection
            } // loop over all lagrange points
          } // only consider dirichlet boundary intersection
        } // walk the intersections
      } // only consider entities with boundary intersection
    } // walk the grid
  } // ... apply(...) const

  template <class R, class GP, int p, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, R, 1, 1>& source,
             DiscreteFunction<ContinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, p, R, 1, 1>, V>& range) const
  {
    typedef ContinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, p, R, 1, 1> RangeSpaceType;
    // checks
    static_assert(dimDomain == 2, "This does not work for other dimensions!");
    static_assert(p == 1, "Not tested for higher polynomial orders!");
    FieldVector<R, 1> tmp_source_value(R(0));
    // clear range
    range.vector().backend() *= 0.0;
    // walk the grid
    const auto entity_it_end = grid_part_.template end<0>();
    for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity = *entity_it;
      // only work if we are at the boundary
      if (entity.hasBoundaryIntersections()) {
        // get the local quantities
        const auto local_source      = source.local_function(entity);
        auto local_range             = range.local_discrete_function(entity);
        auto& local_range_DoF_vector = local_range.vector();
        // get local finite elements
        // * we are a CG space
        const auto cg_finite_element      = range.space().backend().finiteElement(entity);
        const auto& cg_local_coefficients = cg_finite_element.localCoefficients();
        // * but we also need a local DG finite element
        typedef Dune::DGLocalFiniteElement<typename RangeSpaceType::Traits::FiniteElementType> DgFiniteElementType;
        const DgFiniteElementType dg_finite_element(entity.type(), p);
        const auto& dg_local_coefficients = dg_finite_element.localCoefficients();
        assert(dg_local_coefficients.size() == cg_local_coefficients.size() && "Wrong finite element given!");

        // first we loop over all vertices of the entity
        std::vector<DomainType> global_vertices(entity.template count<dimDomain>(), DomainType(0));
        std::vector<size_t> local_DoF_ids(global_vertices.size(), 0);
        for (size_t local_vertex_id = 0; local_vertex_id < global_vertices.size(); ++local_vertex_id) {
          // get the vertex
          const auto vertexPtr             = entity.template subEntity<dimDomain>(local_vertex_id);
          const auto& vertex               = *vertexPtr;
          global_vertices[local_vertex_id] = vertex.geometry().center();
          // find the global DoF id to this vertex, therefore
          // loop over all local DoFs
          for (size_t ii = 0; ii < dg_local_coefficients.size(); ++ii) {
            const auto& entity_cg_local_key = cg_local_coefficients.localKey(ii);
            if (entity_cg_local_key.subEntity() == local_vertex_id) {
              // get the local DoF to this vertex
              const auto& entity_dg_local_key = dg_local_coefficients.localKey(ii);
              assert(entity_cg_local_key.codim() == dimDomain && "Wrong finite element given!");
              local_DoF_ids[local_vertex_id] = entity_dg_local_key.index();
              // there must be one and only one for a polorder 1 lagrange basis
              break;
            }
          } // loop over all local DoFs
        } // loop over all vertices of the entity

        // then we walk the intersections
        const auto intersection_it_end = grid_part_.iend(entity);
        for (auto intersection_it = grid_part_.ibegin(entity); intersection_it != intersection_it_end;
             ++intersection_it) {
          const auto& intersection = *intersection_it;
          if (boundary_info_.dirichlet(intersection)) {
            const auto& intersection_geometry = intersection.geometry();
            // and walk its corners (i.e. the vertices in 2d)
            for (size_t local_intersection_corner_id = 0;
                 int(local_intersection_corner_id) < intersection_geometry.corners();
                 ++local_intersection_corner_id) {
              const auto global_intersection_corner = intersection_geometry.corner(local_intersection_corner_id);
              // to check which vertex this corner is
              // loop over all vertices of the entity again
              for (size_t local_vertex_id = 0; local_vertex_id < global_vertices.size(); ++local_vertex_id) {
                // and check for equality
                if (Stuff::Common::FloatCmp::eq(global_intersection_corner, global_vertices[local_vertex_id])) {
                  // this vertex is on the dirichlet boundary
                  // * so we evaluate the source
                  local_source->evaluate(global_intersection_corner, tmp_source_value);
                  // * and set the corresponding local DoF
                  local_range_DoF_vector.set(local_DoF_ids[local_vertex_id], tmp_source_value[0]);
                }
              } // loop over all vertices of the entity
            } // walk its corners
          }
        } // walk the intersections
      }
    } // walk the grid
  } // ... apply(...) const

private:
  const GridPartType& grid_part_;
  const BoundaryInfoType& boundary_info_;
}; // class Dirichlet

} // namespace ProjectionOperator
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATOR_PROJECTIONS_HH
<commit_msg>[operator.projections] rewrote Dirichlet<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_OPERATOR_PROJECTIONS_HH
#define DUNE_GDT_OPERATOR_PROJECTIONS_HH

#include <vector>
#include <type_traits>
#include <limits>

#include <dune/common/fvector.hh>

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/grid/intersection.hh>
#include <dune/stuff/common/vector.hh>

#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/space/continuouslagrange/fem.hh>
#include <dune/gdt/space/continuouslagrange/fem-localfunctions.hh>
#include <dune/gdt/space/discontinuouslagrange/fem-localfunctions.hh>

namespace Dune {
namespace GDT {
namespace ProjectionOperator {

/**
 *  \note If you add other dimension/polorder/space combinations, do not forget to add a testcase in tests/operators.cc
 */
template <class GridPartImp>
class L2
{
  typedef GridPartImp GridPartType;
  typedef typename GridPartType::template Codim<0>::EntityType EntityType;
  typedef typename GridPartType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridPartType::dimension;

public:
  L2(const GridPartType& grid_part)
    : grid_part_(grid_part)
  {
  }

  /**
   *  \brief  Does an L2 projection by using the lagrange points.
   */
  template <class GP, int p, class R, int r, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, R, r, 1>& source,
             DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<GP, p, R, r, 1>, V>& range) const
  {
    // clear range
    Stuff::Common::clear(range.vector());
    typedef DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<GP, p, R, r, 1>, V> RangeFunctionType;
    typedef typename RangeFunctionType::RangeType RangeType;
    RangeType local_source_value(0);
    // walk the grid
    const auto entity_it_end = grid_part_.template end<0>();
    for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity           = *entity_it;
      const auto local_source      = source.local_function(entity);
      auto local_range             = range.local_discrete_function(entity);
      auto& local_range_DoF_vector = local_range.vector();
      const auto lagrange_points = range.space().backend().lagrangePointSet(entity);
      assert(lagrange_points.nop() == local_range_DoF_vector.size());
      // and do the work
      for (size_t ii = 0; ii < lagrange_points.nop(); ++ii) {
        const auto& lagrange_point = lagrange_points.point(ii);
        local_source->evaluate(lagrange_point, local_source_value);
        local_range_DoF_vector.set(ii, local_source_value);
      }
    } // walk the grid
  } // ... apply(... ContinuousLagrangeSpace::FemWrapper ...)

  /**
   *  \brief  Does an L2 projection by using the lagrange points.
   */
  template <class GP, int p, class R, int r, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, R, r, 1>& source,
             DiscreteFunction<ContinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, p, R, r, 1>, V>& range) const
  {
    // clear range
    Stuff::Common::clear(range.vector());
    typedef DiscreteFunction<ContinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, p, R, r, 1>, V> RangeFunctionType;
    typedef typename RangeFunctionType::RangeType RangeType;
    RangeType local_source_value(0);
    // walk the grid
    const auto entity_it_end = grid_part_.template end<0>();
    for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity           = *entity_it;
      const auto local_source      = source.local_function(entity);
      auto local_range             = range.local_discrete_function(entity);
      auto& local_range_DoF_vector = local_range.vector();
      const auto lagrange_points = range.space().lagrange_points(entity);
      assert(lagrange_points.size() == local_range_DoF_vector.size());
      // and do the work
      for (size_t ii = 0; ii < lagrange_points.size(); ++ii) {
        const auto& lagrange_point = lagrange_points[ii];
        local_source->evaluate(lagrange_point, local_source_value);
        local_range_DoF_vector.set(ii, local_source_value);
      }
    } // walk the grid
  } // ... apply(... ContinuousLagrangeSpace::FemLocalfunctionsWrapper ...)

  /**
   *  \brief  Does an L2 projection by solving the local problems.
   */
  template <class GP, int p, class R, int r, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, R, r, 1>& source,
             DiscreteFunction<DiscontinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, p, R, r, 1>, V>& range) const
  {
    typedef DiscontinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, p, R, r, 1> SpaceType;
    typedef typename SpaceType::BaseFunctionSetType::RangeType RangeType;
    // clear
    Stuff::Common::clear(range.vector());
    // walk the grid
    RangeType source_value(0);
    std::vector<RangeType> basis_values(range.space().mapper().maxNumDofs());
    const auto entity_it_end = grid_part_.template end<0>();
    for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      // prepare
      const auto& entity      = *entity_it;
      const auto local_basis  = range.space().baseFunctionSet(entity);
      const auto local_source = source.local_function(entity);
      auto local_range = range.local_discrete_function(entity);
      DynamicMatrix<R> local_matrix(local_basis.size(), local_basis.size(), R(0));
      DynamicVector<R> local_vector(local_basis.size(), R(0));
      // create quadrature
      const size_t quadrature_order = std::max(local_source->order(), local_range.order());
      assert((2 * quadrature_order + 1) < std::numeric_limits<int>::max());
      const auto& quadrature =
          QuadratureRules<DomainFieldType, dimDomain>::rule(entity.type(), int(2 * quadrature_order + 1));
      // loop over all quadrature points
      for (const auto& quadrature_point : quadrature) {
        const auto local_point         = quadrature_point.position();
        const auto quadrature_weight   = quadrature_point.weight();
        const auto integration_element = entity.geometry().integrationElement(local_point);
        // evaluate
        local_basis.evaluate(local_point, basis_values);
        local_source->evaluate(local_point, source_value);
        // compute integrals
        for (size_t ii = 0; ii < local_basis.size(); ++ii) {
          local_vector[ii] += integration_element * quadrature_weight * (source_value * basis_values[ii]);
          auto& local_matrix_row = local_matrix[ii];
          for (size_t jj = 0; jj < local_basis.size(); ++jj) {
            local_matrix_row[jj] += integration_element * quadrature_weight * (basis_values[ii] * basis_values[jj]);
          }
        }
      } // loop over all quadrature points
      // compute local DoFs
      DynamicVector<R> local_DoFs(local_basis.size(), 0);
      local_matrix.solve(local_DoFs, local_vector);
      // set local DoFs
      auto local_range_vector = local_range.vector();
      for (size_t ii = 0; ii < local_range_vector.size(); ++ii)
        local_range_vector.set(ii, local_DoFs[ii]);
    } // walk the grid
  } // ... apply(... DiscontinuousLagrangeSpace::FemLocalfunctionsWrapper ...)

private:
  const GridPartType& grid_part_;
}; // class L2

/**
 *  \note If you add other dimension/polorder/space combinations, do not forget to add a testcase in tests/operators.cc
 */
template <class GridPartImp>
class Dirichlet
{
public:
  typedef GridPartImp GridPartType;
  typedef Stuff::GridboundaryInterface<typename GridPartType::IntersectionType> BoundaryInfoType;

private:
  typedef typename GridPartType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridPartType::dimension;
  typedef FieldVector<DomainFieldType, dimDomain> DomainType;

  typedef typename GridPartType::template Codim<0>::EntityType EntityType;

public:
  Dirichlet(const GridPartType& grid_part, const BoundaryInfoType& boundary_info)
    : grid_part_(grid_part)
    , boundary_info_(boundary_info)
  {
  }

  /**
   *  \brief  Does a dirichlet projection in the sense that the lagrange point set on each entity is matched against
   *          those vertices of the entity, which lie on the dirichlet boundary.
   */
  template <class R, class GP, int p, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, R, 1, 1>& source,
             DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<GP, p, R, 1, 1>, V>& range) const
  {
    static_assert(p == 1, "This is untested for other polynomial orders! If this works just remove this assert!");
    // clear range
    Stuff::Common::clear(range.vector());
    // walk the grid
    const auto entity_it_end = grid_part_.template end<0>();
    for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity           = *entity_it;
      const auto local_source      = source.local_function(entity);
      auto local_range             = range.local_discrete_function(entity);
      auto& local_range_DoF_vector = local_range.vector();
      const auto lagrange_points = range.space().backend().lagrangePointSet(entity);
      std::vector<DomainType> points(lagrange_points.nop(), DomainType(0));
      for (size_t ii = 0; ii < lagrange_points.nop(); ++ii)
        points[ii] = lagrange_points.point(ii);
      // and do the work (see below)
      apply_local(entity, points, local_source, local_range_DoF_vector);
    } // walk the grid
  } // ... apply(...) const

  /**
   *  \brief  Does a dirichlet projection in the sense that the lagrange point set on each entity is matched against
   *          those vertices of the entity, which lie on the dirichlet boundary.
   */
  template <class R, class GP, class V>
  void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, R, 1, 1>& source,
             DiscreteFunction<ContinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, 1, R, 1, 1>, V>& range) const
  {
    // checks
    typedef ContinuousLagrangeSpace::FemLocalfunctionsWrapper<GP, 1, R, 1, 1> SpaceType;
    static_assert(SpaceType::dimDomain == dimDomain, "Dimensions do not match!");
    static_assert(dimDomain == 2, "This is untested for other dimensions! If this works just remove this assert!");
    // clear range
    Stuff::Common::clear(range.vector());
    // walk the grid
    const auto entity_it_end = grid_part_.template end<0>();
    for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity           = *entity_it;
      const auto local_source      = source.local_function(entity);
      auto local_range             = range.local_discrete_function(entity);
      auto& local_range_DoF_vector = local_range.vector();
      const auto lagrange_points   = range.space().lagrange_points(entity);
      // and do the work (see below)
      apply_local(entity, lagrange_points, local_source, local_range_DoF_vector);
    } // walk the grid
  } // ... apply(...) const

private:
  template <class LagrangePointsType, class LocalSourceType, class LocalRangeVectorType>
  void apply_local(const EntityType& entity, const LagrangePointsType& lagrange_points,
                   const LocalSourceType& local_source, LocalRangeVectorType& local_range_DoF_vector) const
  {
    // walk the intersections
    const auto intersection_it_end = grid_part_.iend(entity);
    for (auto intersection_it = grid_part_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) {
      const auto& intersection = *intersection_it;
      // only work on boundary intersections
      if (boundary_info_.dirichlet(intersection)) {
        const auto& intersection_geometry = intersection.geometry();
        // and walk its corners (i.e. the vertices in 2d)
        for (int local_intersection_corner_id = 0; local_intersection_corner_id < intersection_geometry.corners();
             ++local_intersection_corner_id) {
          const auto local_vertex = entity.geometry().local(intersection_geometry.corner(local_intersection_corner_id));
          // loop over all local lagrange points
          for (size_t lagrange_point_id = 0; lagrange_point_id < lagrange_points.size(); ++lagrange_point_id) {
            const auto& lagrange_point = lagrange_points[lagrange_point_id];
            // and check for equality
            if (Stuff::Common::FloatCmp::eq(local_vertex, lagrange_point)) {
              // this lagrange point is on the dirichlet boundary
              // so we evaluate the source and set the corresponding local DoF
              local_range_DoF_vector.set(lagrange_point_id, local_source->evaluate(lagrange_point));
            }
          } // loop over all local lagrange points
        } // walk its corners
      } // only work on boundary intersections
    } // walk the intersections
  } // ... apply_local(...)

  const GridPartType& grid_part_;
  const BoundaryInfoType& boundary_info_;
}; // class Dirichlet

} // namespace ProjectionOperator
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATOR_PROJECTIONS_HH
<|endoftext|>


<commit_before>#include "opencv-cam-calib-test.hpp"

bool left_camera_on = false;
bool right_camera_on = false;

bool quiet_mode = false;

dc1394_t        *d;
dc1394camera_t  *camera = NULL;

dc1394_t        *d2;
dc1394camera_t  *camera2 = NULL;

RecordingManager recording_manager;

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

    // --- setup control-c handling ---
    struct sigaction sigIntHandler;

    sigIntHandler.sa_handler = control_c_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;

    sigaction(SIGINT, &sigIntHandler, NULL);
    // --- end ctrl-c handling code ---

    Mat m1_mat, d1_mat, m2_mat, d2_mat;

    OpenCvStereoConfig stereo_config;
    string config_file = "";

    ConciseArgs parser(argc, argv);
    parser.add(config_file, "c", "config", "Configuration file containing camera GUIDs, etc.", true);
    parser.add(left_camera_on, "l", "left-camera", "View just the left camera, requires stereo_camera_calibrate/M1 and D1-single.xml to exist");

    parser.add(right_camera_on, "r", "right-camera", "View just the right camera, requires stereo_camera_calibrate/M2 and D2-single.xml to exist");

    parser.add(quiet_mode, "q", "quiet", "Reduce text output.");
    parser.parse();

    // parse the config file
    if (ParseConfigFile(config_file, &stereo_config) != true) {
        fprintf(stderr, "Failed to parse configuration file, quitting.\n");
        return -1;
    }

    string config_dir_prefix = "";

    if (config_file.find_last_of('/') != string::npos) {
        config_dir_prefix = config_file.substr(0, config_file.find_last_of('/'));

        if (!config_dir_prefix.empty()) {
            config_dir_prefix = string(config_dir_prefix) + "/";
        }
    }

    recording_manager.Init(stereo_config);
    recording_manager.SetQuietMode(quiet_mode);

    // read in parameter values
    if (left_camera_on == false && right_camera_on == false) {
        // stereo mode
        left_camera_on = true;
        right_camera_on = true;
    }

    lcm_t * lcm;
    lcm = lcm_create (stereo_config.lcmUrl.c_str());

    uint64 guid = stereo_config.guidLeft;
    uint64 guid2 = stereo_config.guidRight;

    dc1394error_t   err;

    d = dc1394_new ();
    d2 = dc1394_new ();

    if (!d)
        g_critical("Could not create dc1394 context");

    string file1, file2;

    if (left_camera_on) {

        file1 = config_dir_prefix + "stereo_camera_calibrate/M1-single.xml";
        file2 = config_dir_prefix + "stereo_camera_calibrate/D1-single.xml";

        printf("Attemping to load camera paramters:\n\t%s\n\t%s\n", file1.c_str(), file2.c_str());

        CvMat *M1p = (CvMat *)cvLoad(file1.c_str(), NULL,NULL,NULL);
        if (M1p == NULL)
        {
            fprintf(stderr, "Error: Failed to load stereo_camera_calibrate/M1-single.xml\n");
            exit(-1);
        } else {
            m1_mat = Mat(M1p, true);
        }

        CvMat *D1p = (CvMat *)cvLoad(file2.c_str(), NULL,NULL,NULL);
        if (D1p == NULL)
        {
            fprintf(stderr, "Error: Failed to load stereo_camera_calibrate/D1-single.xml\n");
            exit(-1);
        } else {
            d1_mat = Mat(D1p, true);
        }
        printf("done.\n");

        printf("Attempting to start left camera...\n");
        camera = dc1394_camera_new (d, guid);
        if (!camera)
            g_critical("Could not create dc1394 camera");

        err = setup_gray_capture(camera, DC1394_VIDEO_MODE_FORMAT7_1);
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera), "Could not setup camera");

        err = dc1394_feature_set_power(camera, DC1394_FEATURE_EXPOSURE, DC1394_ON);
        DC1394_ERR_RTN(err,"Could not turn on the exposure feature");

        err = dc1394_feature_set_mode(camera, DC1394_FEATURE_EXPOSURE, DC1394_FEATURE_MODE_ONE_PUSH_AUTO);
        DC1394_ERR_RTN(err,"Could not turn on Auto-exposure");

        err = dc1394_video_set_transmission(camera, DC1394_ON);
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera), "Could not start camera iso transmission");

        printf("done.\n");
    }

    if (right_camera_on) {

        file1 = config_dir_prefix + "stereo_camera_calibrate/M2-single.xml";

        file2 = config_dir_prefix + "stereo_camera_calibrate/D2-single.xml";

        printf("Attemping to load camera paramters:\n\t%s\n\t%s\n", file1.c_str(), file2.c_str());

        CvMat *M2p = (CvMat *)cvLoad(file1.c_str(), NULL,NULL,NULL);
        if (M2p == NULL)
        {
            fprintf(stderr, "Error: Failed to load stereo_camera_calibrate/M2-single.xml\n");
            exit(-1);
        } else {
            m2_mat = Mat(M2p, true);
        }

        CvMat *D2p = (CvMat *)cvLoad(file2.c_str(), NULL,NULL,NULL);
        if (D2p == NULL)
        {
            fprintf(stderr, "Error: Failed to load stereo_camera_calibrate/D2-single.xml\n");
            exit(-1);
        } else {
            d2_mat = Mat(D2p, true);
        }
        printf("done.\n");

        printf("Attempting to start right camera...\n");
        camera2 = dc1394_camera_new (d2, guid2);
        if (!camera2)
            g_critical("Could not create dc1394 camera for camera 2");

        // setup

        //err = setup_gray_capture(camera2, DC1394_VIDEO_MODE_FORMAT7_1);
        // this is setup_gray_capture, except I increased the dma buffer size
        {
            dc1394error_t err;

            err=dc1394_camera_reset(camera2);
            DC1394_ERR_RTN(err, "Could not reset camera");

            err = dc1394_video_set_iso_speed(camera2, DC1394_ISO_SPEED_200);
            DC1394_ERR_RTN(err,"Could not setup camera ISO speed");

            err=dc1394_video_set_mode(camera2, DC1394_VIDEO_MODE_FORMAT7_1);
            DC1394_ERR_RTN(err,"Could not set video mode");

            err=dc1394_capture_setup(camera2, 16, DC1394_CAPTURE_FLAGS_DEFAULT);
            DC1394_ERR_RTN(err,"Could not setup camera - make sure that the video mode is supported by your camera");

        }
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera2), "Could not setup camera number 2");

        // enable auto-exposure
        // turn on the auto exposure feature

        // enable auto-exposure
        // turn on the auto exposure feature
        err = dc1394_feature_set_power(camera2, DC1394_FEATURE_EXPOSURE, DC1394_ON);
        DC1394_ERR_RTN(err,"Could not turn on the exposure feature for cam2");

        err = dc1394_feature_set_mode(camera2, DC1394_FEATURE_EXPOSURE, DC1394_FEATURE_MODE_ONE_PUSH_AUTO);
        DC1394_ERR_RTN(err,"Could not turn on Auto-exposure for cam2");

        // enable camera

        err = dc1394_video_set_transmission(camera2, DC1394_ON);
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera2), "Could not start camera iso transmission for camera number 2");

        printf("done.\n");
    }

    if (left_camera_on) {
        InitBrightnessSettings(camera, camera2);
    } else {
        InitBrightnessSettings(camera2, NULL);
    }

    // now we've loaded the calibrations, start showing images!

    // init display windows
    if (left_camera_on) {
    	namedWindow("Input Left", CV_WINDOW_AUTOSIZE);
    	moveWindow("Input Left", 100, 100);

    	namedWindow("Undistort Left", CV_WINDOW_AUTOSIZE);
    	moveWindow("Undistort Left", 100, 369);
    }

    if (right_camera_on) {
    	namedWindow("Input Right", CV_WINDOW_AUTOSIZE);
    	moveWindow("Input Right", 478, 100);

    	namedWindow("Undistort Right", CV_WINDOW_AUTOSIZE);
    	moveWindow("Undistort Right", 478, 369);
    }

    if (left_camera_on && right_camera_on) {
        MatchBrightnessSettings(camera, camera2, true);
    }

    bool done = false;

    Mat left, right;

    // grab init images
    if (left_camera_on) {
        left = GetFrameFormat7(camera);
    }

    if (right_camera_on) {
        right = GetFrameFormat7(camera2);
    }

    if (left_camera_on && right_camera_on) {
        // stereo recording

        if (recording_manager.InitRecording(left, right) != true) {
            // failed to init recording, things are going bad.  bail.
            return -1;
        }
    } else {
        // mono recording

        recording_manager.RestartRecHud();
    }

    // flush buffer
    for (int i = 0; i < 100; i++) {
        if (left_camera_on) {
            left = GetFrameFormat7(camera);
        }
        if (right_camera_on) {
            right = GetFrameFormat7(camera2);
        }
    }

    int numFrames = 0;
    unsigned long elapsed;

    // start the framerate clock
    struct timeval start, now;
    gettimeofday( &start, NULL );

    while (done == false) {
        // grab frames

        if (left_camera_on) {
            left = GetFrameFormat7(camera);

            // use calibration to undistort image
            Mat left_ud;
            undistort(left, left_ud, m1_mat, d1_mat);

            // display
            //imshow("Input Left", left);

            //imshow("Undistort Left", left_ud);
        }

        if (right_camera_on) {
            // flush buffer
            //usleep(900000);
            FlushCameraBuffer(camera2);

            right = GetFrameFormat7(camera2);
            // use calibration to undistort image
            Mat right_ud;
            //undistort(right, right_ud, m2_mat, d2_mat);

            //imshow("Input Right", right);

            //imshow("Undistort Right", right_ud);
        }
        if (left_camera_on && right_camera_on) {
            // stereo recording
        } else {
            Mat img;
            if (left_camera_on) {
                img = left;
            } else {
                img = right;
            }

            recording_manager.RecFrameHud(img, false, "mono");

        }

        lcmt_stereo msg;
        msg.timestamp = getTimestampNow();
        msg.number_of_points = 0;
        msg.frame_number = numFrames;

        msg.video_number = recording_manager.GetHudVideoNumber();

        // publish the LCM message
        lcmt_stereo_publish(lcm, "stereo-mono", &msg);

        numFrames ++;

        if (quiet_mode == false || numFrames % 100 == 0) {
            // compute framerate
            gettimeofday( &now, NULL );

            elapsed = (now.tv_usec / 1000 + now.tv_sec * 1000) -
            (start.tv_usec / 1000 + start.tv_sec * 1000);

            printf("\r%d frames (%lu ms) - %4.1f fps | %4.1f ms/frame", numFrames, elapsed, (float)numFrames/elapsed * 1000, elapsed/(float)numFrames);
            fflush(stdout);
        }

        //char key = waitKey(5);

         //switch (key) {
            //case 'q':
                //done = true;
                //break;
        //}

        usleep(30000);
        //usleep(900000);
    }

    CleanUp();

    return 0;

}

void CleanUp() {

    //cout << "\tpress ctrl+\\ to quit while writing video." << endl;

    //recording_manager.FlushBufferToDisk();

    if (left_camera_on) {

        StopCapture(d, camera);
    }

    if (right_camera_on) {
        StopCapture(d2, camera2);
    }
}

/**
 * Cleanly handles and exit from a command-line
 * ctrl-c signal.
 *
 * @param s
 *
 */
void control_c_handler(int s)
{
    cout << endl << "exiting via ctrl-c" << endl;

    CleanUp();

    exit(0);
}
<commit_msg>Corrects the left camera buffer parameters.<commit_after>#include "opencv-cam-calib-test.hpp"

bool left_camera_on = false;
bool right_camera_on = false;

bool quiet_mode = false;

dc1394_t        *d;
dc1394camera_t  *camera = NULL;

dc1394_t        *d2;
dc1394camera_t  *camera2 = NULL;

RecordingManager recording_manager;

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

    // --- setup control-c handling ---
    struct sigaction sigIntHandler;

    sigIntHandler.sa_handler = control_c_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;

    sigaction(SIGINT, &sigIntHandler, NULL);
    // --- end ctrl-c handling code ---

    Mat m1_mat, d1_mat, m2_mat, d2_mat;

    OpenCvStereoConfig stereo_config;
    string config_file = "";

    ConciseArgs parser(argc, argv);
    parser.add(config_file, "c", "config", "Configuration file containing camera GUIDs, etc.", true);
    parser.add(left_camera_on, "l", "left-camera", "View just the left camera, requires stereo_camera_calibrate/M1 and D1-single.xml to exist");

    parser.add(right_camera_on, "r", "right-camera", "View just the right camera, requires stereo_camera_calibrate/M2 and D2-single.xml to exist");

    parser.add(quiet_mode, "q", "quiet", "Reduce text output.");
    parser.parse();

    // parse the config file
    if (ParseConfigFile(config_file, &stereo_config) != true) {
        fprintf(stderr, "Failed to parse configuration file, quitting.\n");
        return -1;
    }

    string config_dir_prefix = "";

    if (config_file.find_last_of('/') != string::npos) {
        config_dir_prefix = config_file.substr(0, config_file.find_last_of('/'));

        if (!config_dir_prefix.empty()) {
            config_dir_prefix = string(config_dir_prefix) + "/";
        }
    }

    recording_manager.Init(stereo_config);
    recording_manager.SetQuietMode(quiet_mode);

    // read in parameter values
    if (left_camera_on == false && right_camera_on == false) {
        // stereo mode
        left_camera_on = true;
        right_camera_on = true;
    }

    lcm_t * lcm;
    lcm = lcm_create (stereo_config.lcmUrl.c_str());

    uint64 guid = stereo_config.guidLeft;
    uint64 guid2 = stereo_config.guidRight;

    dc1394error_t   err;

    d = dc1394_new ();
    d2 = dc1394_new ();

    if (!d)
        g_critical("Could not create dc1394 context");

    string file1, file2;

    if (left_camera_on) {

        file1 = config_dir_prefix + "stereo_camera_calibrate/M1-single.xml";
        file2 = config_dir_prefix + "stereo_camera_calibrate/D1-single.xml";

        printf("Attemping to load camera paramters:\n\t%s\n\t%s\n", file1.c_str(), file2.c_str());

        CvMat *M1p = (CvMat *)cvLoad(file1.c_str(), NULL,NULL,NULL);
        if (M1p == NULL)
        {
            fprintf(stderr, "Error: Failed to load stereo_camera_calibrate/M1-single.xml\n");
            exit(-1);
        } else {
            m1_mat = Mat(M1p, true);
        }

        CvMat *D1p = (CvMat *)cvLoad(file2.c_str(), NULL,NULL,NULL);
        if (D1p == NULL)
        {
            fprintf(stderr, "Error: Failed to load stereo_camera_calibrate/D1-single.xml\n");
            exit(-1);
        } else {
            d1_mat = Mat(D1p, true);
        }
        printf("done.\n");

        printf("Attempting to start left camera...\n");
        camera = dc1394_camera_new (d, guid);
        if (!camera)
            g_critical("Could not create dc1394 camera");

        // this is setup_gray_capture, except I increased the dma buffer size
        {
            dc1394error_t err;

            err=dc1394_camera_reset(camera);
            DC1394_ERR_RTN(err, "Could not reset camera");

            err = dc1394_video_set_iso_speed(camera, DC1394_ISO_SPEED_200);
            DC1394_ERR_RTN(err,"Could not setup camera ISO speed");

            err=dc1394_video_set_mode(camera, DC1394_VIDEO_MODE_FORMAT7_1);
            DC1394_ERR_RTN(err,"Could not set video mode");

            err=dc1394_capture_setup(camera, 16, DC1394_CAPTURE_FLAGS_DEFAULT);
            DC1394_ERR_RTN(err,"Could not setup camera - make sure that the video mode is supported by your camera");

        }

        err = dc1394_feature_set_power(camera, DC1394_FEATURE_EXPOSURE, DC1394_ON);
        DC1394_ERR_RTN(err,"Could not turn on the exposure feature");

        err = dc1394_feature_set_mode(camera, DC1394_FEATURE_EXPOSURE, DC1394_FEATURE_MODE_ONE_PUSH_AUTO);
        DC1394_ERR_RTN(err,"Could not turn on Auto-exposure");

        err = dc1394_video_set_transmission(camera, DC1394_ON);
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera), "Could not start camera iso transmission");

        printf("done.\n");
    }

    if (right_camera_on) {

        file1 = config_dir_prefix + "stereo_camera_calibrate/M2-single.xml";

        file2 = config_dir_prefix + "stereo_camera_calibrate/D2-single.xml";

        printf("Attemping to load camera paramters:\n\t%s\n\t%s\n", file1.c_str(), file2.c_str());

        CvMat *M2p = (CvMat *)cvLoad(file1.c_str(), NULL,NULL,NULL);
        if (M2p == NULL)
        {
            fprintf(stderr, "Error: Failed to load stereo_camera_calibrate/M2-single.xml\n");
            exit(-1);
        } else {
            m2_mat = Mat(M2p, true);
        }

        CvMat *D2p = (CvMat *)cvLoad(file2.c_str(), NULL,NULL,NULL);
        if (D2p == NULL)
        {
            fprintf(stderr, "Error: Failed to load stereo_camera_calibrate/D2-single.xml\n");
            exit(-1);
        } else {
            d2_mat = Mat(D2p, true);
        }
        printf("done.\n");

        printf("Attempting to start right camera...\n");
        camera2 = dc1394_camera_new (d2, guid2);
        if (!camera2)
            g_critical("Could not create dc1394 camera for camera 2");

        // setup

        //err = setup_gray_capture(camera2, DC1394_VIDEO_MODE_FORMAT7_1);
        // this is setup_gray_capture, except I increased the dma buffer size
        {
            dc1394error_t err;

            err=dc1394_camera_reset(camera2);
            DC1394_ERR_RTN(err, "Could not reset camera");

            err = dc1394_video_set_iso_speed(camera2, DC1394_ISO_SPEED_200);
            DC1394_ERR_RTN(err,"Could not setup camera ISO speed");

            err=dc1394_video_set_mode(camera2, DC1394_VIDEO_MODE_FORMAT7_1);
            DC1394_ERR_RTN(err,"Could not set video mode");

            err=dc1394_capture_setup(camera2, 16, DC1394_CAPTURE_FLAGS_DEFAULT);
            DC1394_ERR_RTN(err,"Could not setup camera - make sure that the video mode is supported by your camera");

        }
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera2), "Could not setup camera number 2");

        // enable auto-exposure
        // turn on the auto exposure feature

        // enable auto-exposure
        // turn on the auto exposure feature
        err = dc1394_feature_set_power(camera2, DC1394_FEATURE_EXPOSURE, DC1394_ON);
        DC1394_ERR_RTN(err,"Could not turn on the exposure feature for cam2");

        err = dc1394_feature_set_mode(camera2, DC1394_FEATURE_EXPOSURE, DC1394_FEATURE_MODE_ONE_PUSH_AUTO);
        DC1394_ERR_RTN(err,"Could not turn on Auto-exposure for cam2");

        // enable camera

        err = dc1394_video_set_transmission(camera2, DC1394_ON);
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera2), "Could not start camera iso transmission for camera number 2");

        printf("done.\n");
    }

    if (left_camera_on) {
        InitBrightnessSettings(camera, camera2);
    } else {
        InitBrightnessSettings(camera2, NULL);
    }

    // now we've loaded the calibrations, start showing images!

    // init display windows
    if (left_camera_on) {
    	namedWindow("Input Left", CV_WINDOW_AUTOSIZE);
    	moveWindow("Input Left", 100, 100);

    	namedWindow("Undistort Left", CV_WINDOW_AUTOSIZE);
    	moveWindow("Undistort Left", 100, 369);
    }

    if (right_camera_on) {
    	namedWindow("Input Right", CV_WINDOW_AUTOSIZE);
    	moveWindow("Input Right", 478, 100);

    	namedWindow("Undistort Right", CV_WINDOW_AUTOSIZE);
    	moveWindow("Undistort Right", 478, 369);
    }

    if (left_camera_on && right_camera_on) {
        MatchBrightnessSettings(camera, camera2, true);
    }

    bool done = false;

    Mat left, right;

    // grab init images
    if (left_camera_on) {
        left = GetFrameFormat7(camera);
    }

    if (right_camera_on) {
        right = GetFrameFormat7(camera2);
    }

    if (left_camera_on && right_camera_on) {
        // stereo recording

        if (recording_manager.InitRecording(left, right) != true) {
            // failed to init recording, things are going bad.  bail.
            return -1;
        }
    } else {
        // mono recording

        recording_manager.RestartRecHud();
    }

    // flush buffer
    for (int i = 0; i < 100; i++) {
        if (left_camera_on) {
            left = GetFrameFormat7(camera);
        }
        if (right_camera_on) {
            right = GetFrameFormat7(camera2);
        }
    }

    int numFrames = 0;
    unsigned long elapsed;

    // start the framerate clock
    struct timeval start, now;
    gettimeofday( &start, NULL );

    while (done == false) {
        // grab frames

        if (left_camera_on) {
            // flush buffer
            FlushCameraBuffer(camera);

            left = GetFrameFormat7(camera);

            // use calibration to undistort image
            Mat left_ud;
            undistort(left, left_ud, m1_mat, d1_mat);

            // display
            //imshow("Input Left", left);

            //imshow("Undistort Left", left_ud);
        }

        if (right_camera_on) {
            // flush buffer
            FlushCameraBuffer(camera2);

            right = GetFrameFormat7(camera2);
            // use calibration to undistort image
            Mat right_ud;
            //undistort(right, right_ud, m2_mat, d2_mat);

            //imshow("Input Right", right);

            //imshow("Undistort Right", right_ud);
        }
        if (left_camera_on && right_camera_on) {
            // stereo recording
        } else {
            Mat img;
            if (left_camera_on) {
                img = left;
            } else {
                img = right;
            }

            recording_manager.RecFrameHud(img, false, "mono");

        }

        lcmt_stereo msg;
        msg.timestamp = getTimestampNow();
        msg.number_of_points = 0;
        msg.frame_number = numFrames;

        msg.video_number = recording_manager.GetHudVideoNumber();

        // publish the LCM message
        lcmt_stereo_publish(lcm, "stereo-mono", &msg);

        numFrames ++;

        if (quiet_mode == false || numFrames % 100 == 0) {
            // compute framerate
            gettimeofday( &now, NULL );

            elapsed = (now.tv_usec / 1000 + now.tv_sec * 1000) -
            (start.tv_usec / 1000 + start.tv_sec * 1000);

            printf("\r%d frames (%lu ms) - %4.1f fps | %4.1f ms/frame", numFrames, elapsed, (float)numFrames/elapsed * 1000, elapsed/(float)numFrames);
            fflush(stdout);
        }

        //char key = waitKey(5);

         //switch (key) {
            //case 'q':
                //done = true;
                //break;
        //}

        usleep(30000);
        //usleep(900000);
    }

    CleanUp();

    return 0;

}

void CleanUp() {

    //cout << "\tpress ctrl+\\ to quit while writing video." << endl;

    //recording_manager.FlushBufferToDisk();

    if (left_camera_on) {

        StopCapture(d, camera);
    }

    if (right_camera_on) {
        StopCapture(d2, camera2);
    }
}

/**
 * Cleanly handles and exit from a command-line
 * ctrl-c signal.
 *
 * @param s
 *
 */
void control_c_handler(int s)
{
    cout << endl << "exiting via ctrl-c" << endl;

    CleanUp();

    exit(0);
}
<|endoftext|>


<commit_before>#include "robobo.h"
#include "configuration.cpp"
#include "servercapab.cpp"
#include "socket.cpp"

std::string input, command, currentNick;
std::vector<std::string> inputParams;
bool registered;

int main(int argc, char** argv) {
	ConfigReader config;
	Socket bot_socket (config.getServer(), config.getPort());
	bot_socket.sendMsg("NICK :RoBoBo");
	bot_socket.sendMsg("USER RoBoBo here " + config.getServer() + " :RoBoBo-IRC-BoBo IRC Bot");
	currentNick = "RoBoBo";
	while (true) {
		if (!bot_socket.isConnected()) {
			bot_socket.closeConnection();
			std::cout << "Disconnected from server." << std::endl;
			return 0;
		}
		input = bot_socket.receive();
		std::cout << input << std::endl;
		inputParams.clear();
		inputParams = bot_socket.parseLine(input);
		command = inputParams[1];
		std::cout << "Command/Numeric: " << command << std::endl;
		if (command == "001")
			registered = true;
		if (command == "005")
			handleCapab(inputParams);
		if (command == "433" && !registered) {
			currentNick += "_";
			bot_socket.sendMsg("NICK :" + currentNick);
		}
	}
}<commit_msg>Remove a line included to test the parser.<commit_after>#include "robobo.h"
#include "configuration.cpp"
#include "servercapab.cpp"
#include "socket.cpp"

std::string input, command, currentNick;
std::vector<std::string> inputParams;
bool registered;

int main(int argc, char** argv) {
	ConfigReader config;
	Socket bot_socket (config.getServer(), config.getPort());
	bot_socket.sendMsg("NICK :RoBoBo");
	bot_socket.sendMsg("USER RoBoBo here " + config.getServer() + " :RoBoBo-IRC-BoBo IRC Bot");
	currentNick = "RoBoBo";
	while (true) {
		if (!bot_socket.isConnected()) {
			bot_socket.closeConnection();
			std::cout << "Disconnected from server." << std::endl;
			return 0;
		}
		input = bot_socket.receive();
		std::cout << input << std::endl;
		inputParams.clear();
		inputParams = bot_socket.parseLine(input);
		command = inputParams[1];
		if (command == "001")
			registered = true;
		if (command == "005")
			handleCapab(inputParams);
		if (command == "433" && !registered) {
			currentNick += "_";
			bot_socket.sendMsg("NICK :" + currentNick);
		}
	}
}<|endoftext|>