<commit_before>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

typedef tr1::tuple<std::string, int, int, tr1::tuple<int,int>, int> Path_Idx_Cn_NPoints_WSize_t;
typedef TestBaseWithParam<Path_Idx_Cn_NPoints_WSize_t> Path_Idx_Cn_NPoints_WSize;

void FormTrackingPointsArray(vector<Point2f>& points, int width, int height, int nPointsX, int nPointsY)
{
    int stepX = width / nPointsX;
    int stepY = height / nPointsY;
    if (stepX < 1 || stepY < 1) FAIL() << "Specified points number is too big";

    points.clear();
    points.reserve(nPointsX * nPointsY);

    for( int x = stepX / 2; x < width; x += stepX )
    {
        for( int y = stepY / 2; y < height; y += stepY )
        {
            Point2f pt(static_cast<float>(x), static_cast<float>(y));
            points.push_back(pt);
        }
    }
}

PERF_TEST_P(Path_Idx_Cn_NPoints_WSize, OpticalFlowPyrLK_full, testing::Combine(
                testing::Values<std::string>("cv/optflow/frames/VGA_%02d.png", "cv/optflow/frames/720p_%02d.png"),
                testing::Range(1, 3),
                testing::Values(1, 3, 4),
                testing::Values(make_tuple(9, 9), make_tuple(15, 15)),
                testing::Values(7, 11, 25)
                )
            )
{
    string filename1 = getDataPath(cv::format(get<0>(GetParam()).c_str(), get<1>(GetParam())));
    string filename2 = getDataPath(cv::format(get<0>(GetParam()).c_str(), get<1>(GetParam()) + 1));
    Mat img1 = imread(filename1);
    Mat img2 = imread(filename2);
    if (img1.empty()) FAIL() << "Unable to load source image " << filename1;
    if (img2.empty()) FAIL() << "Unable to load source image " << filename2;

    int cn = get<2>(GetParam());
    int nPointsX = min(get<0>(get<3>(GetParam())), img1.cols);
    int nPointsY = min(get<1>(get<3>(GetParam())), img1.rows);
    int winSize = get<4>(GetParam());

    int maxLevel = 2;
    TermCriteria criteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 7, 0.001);
    int flags = 0;
    double minEigThreshold = 1e-4;

    Mat frame1, frame2;
    switch(cn)
    {
    case 1:
        cvtColor(img1, frame1, COLOR_BGR2GRAY, cn);
        cvtColor(img2, frame2, COLOR_BGR2GRAY, cn);
        break;
    case 3:
        frame1 = img1;
        frame2 = img2;
        break;
    case 4:
        cvtColor(img1, frame1, COLOR_BGR2BGRA, cn);
        cvtColor(img2, frame2, COLOR_BGR2BGRA, cn);
        break;
    default:
        FAIL() << "Unexpected number of channels: " << cn;
    }

    vector<Point2f> inPoints;
    vector<Point2f> outPoints;
    vector<uchar> status;
    vector<float> err;

    FormTrackingPointsArray(inPoints, frame1.cols, frame1.rows, nPointsX, nPointsY);
    outPoints.resize(inPoints.size());
    status.resize(inPoints.size());
    err.resize(inPoints.size());

    declare.in(frame1, frame2, inPoints).out(outPoints);

    TEST_CYCLE_N(30)
    {
        calcOpticalFlowPyrLK(frame1, frame2, inPoints, outPoints, status, err,
                             Size(winSize, winSize), maxLevel, criteria,
                             flags, minEigThreshold);
    }

    SANITY_CHECK(outPoints);
    SANITY_CHECK(status);
    SANITY_CHECK(err, 1e-5);
}

typedef tr1::tuple<std::string, int, int, tr1::tuple<int,int>, int, bool> Path_Idx_Cn_NPoints_WSize_Deriv_t;
typedef TestBaseWithParam<Path_Idx_Cn_NPoints_WSize_Deriv_t> Path_Idx_Cn_NPoints_WSize_Deriv;

PERF_TEST_P(Path_Idx_Cn_NPoints_WSize_Deriv, OpticalFlowPyrLK_self, testing::Combine(
                testing::Values<std::string>("cv/optflow/frames/VGA_%02d.png", "cv/optflow/frames/720p_%02d.png"),
                testing::Range(1, 3),
                testing::Values(1, 3, 4),
                testing::Values(make_tuple(9, 9), make_tuple(15, 15)),
                testing::Values(7, 11, 25),
                testing::Bool()
                )
            )
{
    string filename1 = getDataPath(cv::format(get<0>(GetParam()).c_str(), get<1>(GetParam())));
    string filename2 = getDataPath(cv::format(get<0>(GetParam()).c_str(), get<1>(GetParam()) + 1));
    Mat img1 = imread(filename1);
    Mat img2 = imread(filename2);
    if (img1.empty()) FAIL() << "Unable to load source image " << filename1;
    if (img2.empty()) FAIL() << "Unable to load source image " << filename2;

    int cn = get<2>(GetParam());
    int nPointsX = min(get<0>(get<3>(GetParam())), img1.cols);
    int nPointsY = min(get<1>(get<3>(GetParam())), img1.rows);
    int winSize = get<4>(GetParam());
    bool withDerivatives = get<5>(GetParam());

    int maxLevel = 2;
    TermCriteria criteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 7, 0.001);
    int flags = 0;
    double minEigThreshold = 1e-4;

    Mat frame1, frame2;
    switch(cn)
    {
    case 1:
        cvtColor(img1, frame1, COLOR_BGR2GRAY, cn);
        cvtColor(img2, frame2, COLOR_BGR2GRAY, cn);
        break;
    case 3:
        frame1 = img1;
        frame2 = img2;
        break;
    case 4:
        cvtColor(img1, frame1, COLOR_BGR2BGRA, cn);
        cvtColor(img2, frame2, COLOR_BGR2BGRA, cn);
        break;
    default:
        FAIL() << "Unexpected number of channels: " << cn;
    }

    vector<Point2f> inPoints;
    vector<Point2f> outPoints;
    vector<uchar> status;
    vector<float> err;

    FormTrackingPointsArray(inPoints, frame1.cols, frame1.rows, nPointsX, nPointsY);
    outPoints.resize(inPoints.size());
    status.resize(inPoints.size());
    err.resize(inPoints.size());

    std::vector<Mat> pyramid1, pyramid2;

    maxLevel = buildOpticalFlowPyramid(frame1, pyramid1, Size(winSize, winSize), maxLevel, withDerivatives);
    maxLevel = buildOpticalFlowPyramid(frame2, pyramid2, Size(winSize, winSize), maxLevel, withDerivatives);

    declare.in(pyramid1, pyramid2, inPoints).out(outPoints);

    TEST_CYCLE()
    {
        calcOpticalFlowPyrLK(pyramid1, pyramid2, inPoints, outPoints, status, err,
                             Size(winSize, winSize), maxLevel, criteria,
                             flags, minEigThreshold);
    }

    SANITY_CHECK(outPoints);
    SANITY_CHECK(status);
    SANITY_CHECK(err, 1e-5);
}

CV_ENUM(PyrBorderMode, BORDER_DEFAULT, BORDER_TRANSPARENT);
typedef tr1::tuple<std::string, int, bool, PyrBorderMode, bool> Path_Win_Deriv_Border_Reuse_t;
typedef TestBaseWithParam<Path_Win_Deriv_Border_Reuse_t> Path_Win_Deriv_Border_Reuse;

PERF_TEST_P(Path_Win_Deriv_Border_Reuse, OpticalFlowPyrLK_pyr, testing::Combine(
                testing::Values<std::string>("cv/optflow/frames/720p_01.png"),
                testing::Values(7, 11),
                testing::Bool(),
                testing::ValuesIn(PyrBorderMode::all()),
                testing::Bool()
                )
            )
{
    string filename = getDataPath(get<0>(GetParam()));
    Mat img = imread(filename);
    Size winSize(get<1>(GetParam()), get<1>(GetParam()));
    bool withDerivatives = get<2>(GetParam());
    int derivBorder = get<3>(GetParam());
    int pyrBorder = derivBorder;
    if(derivBorder != BORDER_TRANSPARENT)
    {
        derivBorder = BORDER_CONSTANT;
        pyrBorder = BORDER_REFLECT_101;
    }
    bool tryReuseInputImage = get<4>(GetParam());
    std::vector<Mat> pyramid;

    img.adjustROI(winSize.height, winSize.height, winSize.width, winSize.width);

    int maxLevel = buildOpticalFlowPyramid(img, pyramid, winSize, 1000, withDerivatives, BORDER_CONSTANT, BORDER_CONSTANT, tryReuseInputImage);

    declare.in(img).out(pyramid);

    TEST_CYCLE()
    {
        buildOpticalFlowPyramid(img, pyramid, winSize, maxLevel, withDerivatives, pyrBorder, derivBorder, tryReuseInputImage);
    }

    SANITY_CHECK(pyramid);
}<commit_msg>Adjust thresholds in sanity checks for calcOpticalFlowPyrLK<commit_after>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

typedef tr1::tuple<std::string, int, int, tr1::tuple<int,int>, int> Path_Idx_Cn_NPoints_WSize_t;
typedef TestBaseWithParam<Path_Idx_Cn_NPoints_WSize_t> Path_Idx_Cn_NPoints_WSize;

void FormTrackingPointsArray(vector<Point2f>& points, int width, int height, int nPointsX, int nPointsY)
{
    int stepX = width / nPointsX;
    int stepY = height / nPointsY;
    if (stepX < 1 || stepY < 1) FAIL() << "Specified points number is too big";

    points.clear();
    points.reserve(nPointsX * nPointsY);

    for( int x = stepX / 2; x < width; x += stepX )
    {
        for( int y = stepY / 2; y < height; y += stepY )
        {
            Point2f pt(static_cast<float>(x), static_cast<float>(y));
            points.push_back(pt);
        }
    }
}

PERF_TEST_P(Path_Idx_Cn_NPoints_WSize, OpticalFlowPyrLK_full, testing::Combine(
                testing::Values<std::string>("cv/optflow/frames/VGA_%02d.png", "cv/optflow/frames/720p_%02d.png"),
                testing::Range(1, 3),
                testing::Values(1, 3, 4),
                testing::Values(make_tuple(9, 9), make_tuple(15, 15)),
                testing::Values(7, 11, 25)
                )
            )
{
    string filename1 = getDataPath(cv::format(get<0>(GetParam()).c_str(), get<1>(GetParam())));
    string filename2 = getDataPath(cv::format(get<0>(GetParam()).c_str(), get<1>(GetParam()) + 1));
    Mat img1 = imread(filename1);
    Mat img2 = imread(filename2);
    if (img1.empty()) FAIL() << "Unable to load source image " << filename1;
    if (img2.empty()) FAIL() << "Unable to load source image " << filename2;

    int cn = get<2>(GetParam());
    int nPointsX = min(get<0>(get<3>(GetParam())), img1.cols);
    int nPointsY = min(get<1>(get<3>(GetParam())), img1.rows);
    int winSize = get<4>(GetParam());

    int maxLevel = 2;
    TermCriteria criteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 7, 0.001);
    int flags = 0;
    double minEigThreshold = 1e-4;

    Mat frame1, frame2;
    switch(cn)
    {
    case 1:
        cvtColor(img1, frame1, COLOR_BGR2GRAY, cn);
        cvtColor(img2, frame2, COLOR_BGR2GRAY, cn);
        break;
    case 3:
        frame1 = img1;
        frame2 = img2;
        break;
    case 4:
        cvtColor(img1, frame1, COLOR_BGR2BGRA, cn);
        cvtColor(img2, frame2, COLOR_BGR2BGRA, cn);
        break;
    default:
        FAIL() << "Unexpected number of channels: " << cn;
    }

    vector<Point2f> inPoints;
    vector<Point2f> outPoints;
    vector<uchar> status;
    vector<float> err;

    FormTrackingPointsArray(inPoints, frame1.cols, frame1.rows, nPointsX, nPointsY);
    outPoints.resize(inPoints.size());
    status.resize(inPoints.size());
    err.resize(inPoints.size());

    declare.in(frame1, frame2, inPoints).out(outPoints);

    TEST_CYCLE_N(30)
    {
        calcOpticalFlowPyrLK(frame1, frame2, inPoints, outPoints, status, err,
                             Size(winSize, winSize), maxLevel, criteria,
                             flags, minEigThreshold);
    }

    SANITY_CHECK(outPoints, 0.3);
    SANITY_CHECK(status);
    SANITY_CHECK(err, 2);
}

typedef tr1::tuple<std::string, int, int, tr1::tuple<int,int>, int, bool> Path_Idx_Cn_NPoints_WSize_Deriv_t;
typedef TestBaseWithParam<Path_Idx_Cn_NPoints_WSize_Deriv_t> Path_Idx_Cn_NPoints_WSize_Deriv;

PERF_TEST_P(Path_Idx_Cn_NPoints_WSize_Deriv, OpticalFlowPyrLK_self, testing::Combine(
                testing::Values<std::string>("cv/optflow/frames/VGA_%02d.png", "cv/optflow/frames/720p_%02d.png"),
                testing::Range(1, 3),
                testing::Values(1, 3, 4),
                testing::Values(make_tuple(9, 9), make_tuple(15, 15)),
                testing::Values(7, 11, 25),
                testing::Bool()
                )
            )
{
    string filename1 = getDataPath(cv::format(get<0>(GetParam()).c_str(), get<1>(GetParam())));
    string filename2 = getDataPath(cv::format(get<0>(GetParam()).c_str(), get<1>(GetParam()) + 1));
    Mat img1 = imread(filename1);
    Mat img2 = imread(filename2);
    if (img1.empty()) FAIL() << "Unable to load source image " << filename1;
    if (img2.empty()) FAIL() << "Unable to load source image " << filename2;

    int cn = get<2>(GetParam());
    int nPointsX = min(get<0>(get<3>(GetParam())), img1.cols);
    int nPointsY = min(get<1>(get<3>(GetParam())), img1.rows);
    int winSize = get<4>(GetParam());
    bool withDerivatives = get<5>(GetParam());

    int maxLevel = 2;
    TermCriteria criteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 7, 0.001);
    int flags = 0;
    double minEigThreshold = 1e-4;

    Mat frame1, frame2;
    switch(cn)
    {
    case 1:
        cvtColor(img1, frame1, COLOR_BGR2GRAY, cn);
        cvtColor(img2, frame2, COLOR_BGR2GRAY, cn);
        break;
    case 3:
        frame1 = img1;
        frame2 = img2;
        break;
    case 4:
        cvtColor(img1, frame1, COLOR_BGR2BGRA, cn);
        cvtColor(img2, frame2, COLOR_BGR2BGRA, cn);
        break;
    default:
        FAIL() << "Unexpected number of channels: " << cn;
    }

    vector<Point2f> inPoints;
    vector<Point2f> outPoints;
    vector<uchar> status;
    vector<float> err;

    FormTrackingPointsArray(inPoints, frame1.cols, frame1.rows, nPointsX, nPointsY);
    outPoints.resize(inPoints.size());
    status.resize(inPoints.size());
    err.resize(inPoints.size());

    std::vector<Mat> pyramid1, pyramid2;

    maxLevel = buildOpticalFlowPyramid(frame1, pyramid1, Size(winSize, winSize), maxLevel, withDerivatives);
    maxLevel = buildOpticalFlowPyramid(frame2, pyramid2, Size(winSize, winSize), maxLevel, withDerivatives);

    declare.in(pyramid1, pyramid2, inPoints).out(outPoints);

    TEST_CYCLE()
    {
        calcOpticalFlowPyrLK(pyramid1, pyramid2, inPoints, outPoints, status, err,
                             Size(winSize, winSize), maxLevel, criteria,
                             flags, minEigThreshold);
    }

    SANITY_CHECK(outPoints, 0.3);
    SANITY_CHECK(status);
    SANITY_CHECK(err, 2);
}

CV_ENUM(PyrBorderMode, BORDER_DEFAULT, BORDER_TRANSPARENT);
typedef tr1::tuple<std::string, int, bool, PyrBorderMode, bool> Path_Win_Deriv_Border_Reuse_t;
typedef TestBaseWithParam<Path_Win_Deriv_Border_Reuse_t> Path_Win_Deriv_Border_Reuse;

PERF_TEST_P(Path_Win_Deriv_Border_Reuse, OpticalFlowPyrLK_pyr, testing::Combine(
                testing::Values<std::string>("cv/optflow/frames/720p_01.png"),
                testing::Values(7, 11),
                testing::Bool(),
                testing::ValuesIn(PyrBorderMode::all()),
                testing::Bool()
                )
            )
{
    string filename = getDataPath(get<0>(GetParam()));
    Mat img = imread(filename);
    Size winSize(get<1>(GetParam()), get<1>(GetParam()));
    bool withDerivatives = get<2>(GetParam());
    int derivBorder = get<3>(GetParam());
    int pyrBorder = derivBorder;
    if(derivBorder != BORDER_TRANSPARENT)
    {
        derivBorder = BORDER_CONSTANT;
        pyrBorder = BORDER_REFLECT_101;
    }
    bool tryReuseInputImage = get<4>(GetParam());
    std::vector<Mat> pyramid;

    img.adjustROI(winSize.height, winSize.height, winSize.width, winSize.width);

    int maxLevel = buildOpticalFlowPyramid(img, pyramid, winSize, 1000, withDerivatives, BORDER_CONSTANT, BORDER_CONSTANT, tryReuseInputImage);

    declare.in(img).out(pyramid);

    TEST_CYCLE()
    {
        buildOpticalFlowPyramid(img, pyramid, winSize, maxLevel, withDerivatives, pyrBorder, derivBorder, tryReuseInputImage);
    }

    SANITY_CHECK(pyramid);
}<|endoftext|>


<commit_before>#include <boost/program_options.hpp>
#include "mm/ug_bitext.h"
#include <string>

using namespace std;
using namespace Moses;
using namespace sapt;

namespace po=boost::program_options;
typedef L2R_Token<SimpleWordId> Token;
typedef mmBitext<Token> mmbitext;
typedef Bitext<Token>::tsa tsa;

string bname, L1, L2, Q1, Q2;
size_t maxhits;
void interpret_args(int ac, char* av[]);

void
write_sentence
(Ttrack<Token> const& T, uint32_t const sid, TokenIndex const& V, ostream& out)
{
  Token const* t = T.sntStart(sid);
  Token const* e = T.sntEnd(sid);
  // size_t i = 0;
  while (t < e)
    {
      // out << i++ << ":";
      out << V[t->id()];
      if (++t < e) out << " ";
    }
}

bool
fill(string const& query, TSA<Token> const& tsa,
     TokenIndex const& V, bitvector& v)
{
  v.resize(tsa.getCorpus()->size());
  Bitext<Token>::iter m(&tsa);
  istringstream buf(query); string w;
  while (buf >> w)
    if (!m.extend(V[w]))
      return false;
  m.markSentences(v);
  return true;
}

int main(int argc, char* argv[])
{
  interpret_args(argc, argv);
  if (Q1.empty() && Q2.empty()) exit(0);

  mmbitext B; string w;
  B.open(bname, L1, L2);

  Bitext<Token>::iter m1(B.I1.get(), *B.V1, Q1);
  if (Q1.size() && m1.size() == 0) exit(0);

  Bitext<Token>::iter m2(B.I2.get(), *B.V2, Q2);
  if (Q2.size() && m2.size() == 0) exit(0);

  bitvector check(B.T1->size());
  if (Q1.size() == 0 || Q2.size() == 0) check.set();
  else (m2.markSentences(check));

  Bitext<Token>::iter& m = m1.size() ? m1 : m2;
  char const* x = m.lower_bound(-1);
  char const* stop = m.upper_bound(-1);
  uint64_t sid;
  ushort off;
  boost::taus88 rnd;
  size_t N = m.approxOccurrenceCount();
  maxhits = min(N, maxhits);
  size_t k = 0; // selected
  for (size_t i = 0; x < stop; ++i)
    {
      x = m.root->readSid(x,stop,sid);
      x = m.root->readOffset(x,stop,off);

      if (!check[sid]) continue;
      size_t r = (N - i) * rnd()/(rnd.max()+1.) + k;
      if (maxhits != N && r >= maxhits) continue;
      ++k;

      size_t s1,s2,e1,e2; int po_fwd=-1,po_bwd=-1;
      std::vector<unsigned char> caln;
      // cout << sid  << " " << B.docname(sid) << std::endl;
      if (!B.find_trg_phr_bounds(sid, off, off+m.size(),
				 s1,s2,e1,e2,po_fwd,po_bwd,
				 &caln, NULL, &m == &m2))
	{
	  // cout << "alignment failure" << std::endl;
	}

      std::cout << sid  << " " << B.docname(sid)
		<< " dfwd=" << po_fwd << " dbwd=" << po_bwd
		<< "\n";

      write_sentence(*B.T1, sid, *B.V1, std::cout); std::cout << "\n";
      write_sentence(*B.T2, sid, *B.V2, std::cout); std::cout << "\n";
      B.write_yawat_alignment(sid,
			      m1.size() ? &m1 : NULL,
			      m2.size() ? &m2 : NULL, std::cout);
      std::cout << std::endl;

    }
}

void
interpret_args(int ac, char* av[])
{
  po::variables_map vm;
  po::options_description o("Options");
  o.add_options()

    ("help,h",  "print this message")
    ("maxhits,n", po::value<size_t>(&maxhits)->default_value(25),
     "max. number of hits")
    ("q1", po::value<string>(&Q1), "query in L1")
    ("q2", po::value<string>(&Q2), "query in L2")
    ;

  po::options_description h("Hidden Options");
  h.add_options()
    ("bname", po::value<string>(&bname), "base name of corpus")
    ("L1", po::value<string>(&L1), "L1 tag")
    ("L2", po::value<string>(&L2), "L2 tag")
    ;

  h.add(o);
  po::positional_options_description a;
  a.add("bname",1);
  a.add("L1",1);
  a.add("L2",1);

  po::store(po::command_line_parser(ac,av)
            .options(h)
            .positional(a)
            .run(),vm);
  po::notify(vm);
  if (vm.count("help"))
    {
      std::cout << "\nusage:\n\t" << av[0]
           << " [options] [--q1=<L1string>] [--q2=<L2string>]" << std::endl;
      std::cout << o << std::endl;
      exit(0);
    }
}
<commit_msg>Adaptation to renamed functions in Bitext class.<commit_after>#include <boost/program_options.hpp>
#include "mm/ug_bitext.h"
#include <string>

using namespace std;
using namespace Moses;
using namespace sapt;

namespace po=boost::program_options;
typedef L2R_Token<SimpleWordId> Token;
typedef mmBitext<Token> mmbitext;
typedef Bitext<Token>::tsa tsa;

string bname, L1, L2, Q1, Q2;
size_t maxhits;
void interpret_args(int ac, char* av[]);

void
write_sentence
(Ttrack<Token> const& T, uint32_t const sid, TokenIndex const& V, ostream& out)
{
  Token const* t = T.sntStart(sid);
  Token const* e = T.sntEnd(sid);
  // size_t i = 0;
  while (t < e)
    {
      // out << i++ << ":";
      out << V[t->id()];
      if (++t < e) out << " ";
    }
}

bool
fill(string const& query, TSA<Token> const& tsa,
     TokenIndex const& V, bitvector& v)
{
  v.resize(tsa.getCorpus()->size());
  Bitext<Token>::iter m(&tsa);
  istringstream buf(query); string w;
  while (buf >> w)
    if (!m.extend(V[w]))
      return false;
  m.markSentences(v);
  return true;
}

int main(int argc, char* argv[])
{
  interpret_args(argc, argv);
  if (Q1.empty() && Q2.empty()) exit(0);

  boost::shared_ptr<mmbitext> B(new mmbitext); string w;
  B->open(bname, L1, L2);

  Bitext<Token>::iter m1(B->I1.get(), *B->V1, Q1);
  if (Q1.size() && m1.size() == 0) exit(0);

  Bitext<Token>::iter m2(B->I2.get(), *B->V2, Q2);
  if (Q2.size() && m2.size() == 0) exit(0);

  bitvector check(B->T1->size());
  if (Q1.size() == 0 || Q2.size() == 0) check.set();
  else (m2.markSentences(check));

  Bitext<Token>::iter& m = m1.size() ? m1 : m2;
  char const* x = m.lower_bound(-1);
  char const* stop = m.upper_bound(-1);
  uint64_t sid;
  ushort off;
  boost::taus88 rnd;
  size_t N = m.approxOccurrenceCount();
  maxhits = min(N, maxhits);
  size_t k = 0; // selected
  for (size_t i = 0; x < stop; ++i)
    {
      x = m.root->readSid(x,stop,sid);
      x = m.root->readOffset(x,stop,off);

      if (!check[sid]) continue;
      size_t r = (N - i) * rnd()/(rnd.max()+1.) + k;
      if (maxhits != N && r >= maxhits) continue;
      ++k;

      size_t s1,s2,e1,e2; int po_fwd=-1,po_bwd=-1;
      std::vector<unsigned char> caln;
      // cout << sid  << " " << B->docname(sid) << std::endl;
      if (!B->find_trg_phr_bounds(sid, off, off+m.size(),
				 s1,s2,e1,e2,po_fwd,po_bwd,
				 &caln, NULL, &m == &m2))
	{
	  // cout << "alignment failure" << std::endl;
	}

      std::cout << sid  << " " << B->sid2docname(sid)
		<< " dfwd=" << po_fwd << " dbwd=" << po_bwd
		<< "\n";

      write_sentence(*B->T1, sid, *B->V1, std::cout); std::cout << "\n";
      write_sentence(*B->T2, sid, *B->V2, std::cout); std::cout << "\n";
      B->write_yawat_alignment(sid,
			       m1.size() ? &m1 : NULL,
			       m2.size() ? &m2 : NULL, std::cout);
      std::cout << std::endl;

    }
}

void
interpret_args(int ac, char* av[])
{
  po::variables_map vm;
  po::options_description o("Options");
  o.add_options()

    ("help,h",  "print this message")
    ("maxhits,n", po::value<size_t>(&maxhits)->default_value(25),
     "max. number of hits")
    ("q1", po::value<string>(&Q1), "query in L1")
    ("q2", po::value<string>(&Q2), "query in L2")
    ;

  po::options_description h("Hidden Options");
  h.add_options()
    ("bname", po::value<string>(&bname), "base name of corpus")
    ("L1", po::value<string>(&L1), "L1 tag")
    ("L2", po::value<string>(&L2), "L2 tag")
    ;

  h.add(o);
  po::positional_options_description a;
  a.add("bname",1);
  a.add("L1",1);
  a.add("L2",1);

  po::store(po::command_line_parser(ac,av)
            .options(h)
            .positional(a)
            .run(),vm);
  po::notify(vm);
  if (vm.count("help"))
    {
      std::cout << "\nusage:\n\t" << av[0]
           << " [options] [--q1=<L1string>] [--q2=<L2string>]" << std::endl;
      std::cout << o << std::endl;
      exit(0);
    }
}
<|endoftext|>


<commit_before>//
//  MarksRenderer.cpp
//  G3MiOSSDK
//
//  Created by Diego Gomez Deck on 05/06/12.
//  Copyright (c) 2012 IGO Software SL. All rights reserved.
//

#include "MarksRenderer.hpp"
#include "Camera.hpp"

void MarksRenderer::initialize(const InitializationContext* ic) {

}

bool MarksRenderer::onTouchEvent(const TouchEvent* touchEvent) {
  return false;
}

int MarksRenderer::render(const RenderContext* rc) {
//  rc.getLogger()->logInfo("MarksRenderer::render()");

  IGL* gl = rc->getGL();

  gl->enableVerticesPosition();
  gl->enableTextures();

  gl->depthTest(false);
  gl->blend(true);

  const Vector3D radius = rc->getPlanet()->getRadii();
  const double minDistanceToCamera = (radius.x() + radius.y() + radius.z()) * 2;

  int marksSize = _marks.size();
  for (int i = 0; i < marksSize; i++) {
    Mark* mark = _marks[i];
    //rc->getLogger()->logInfo("Rendering Mark: \"%s\"", mark->getName().c_str());

    mark->render(rc, minDistanceToCamera);
  }

  gl->depthTest(true);
  gl->blend(false);

  gl->disableTextures();
  gl->disableVerticesPosition();

  return MAX_TIME_TO_RENDER;
}

//
//int MarksRenderer::Render(RenderContext &rc) {
//  // obtaing gl object reference
//  IGL *gl = rc.GetGL();
//  //Point3D po = View::GetInstance()->GetCamera()->GetPos();
//  //Vector3D c(po.x, po.y, po.z);
//  Vector3D c = View::GetInstance()->GetCamera()->GetPos();
//
//  gl->DepthTestEnabled(false);
//  gl->BlendingEnabled(true);
//
//  //DRAWING LOOP
//  Ellipsoid *ellipsoid = SceneController::GetInstance()->getGlobe()->GetEllipsoid();
//  Vector3D radius = ellipsoid->getRadii();
//  double minDist = (radius.X + radius.Y + radius.Z) / 3;
//  for (int i = 0; i < marks.markSet.size(); i++) {
//    Mark *m = marks.markSet.at(i);
//
//    Vector3D v = ellipsoid->ToVector3D(m->point);
//    Vector3D normal = Ellipsoid::CentricSurfaceNormal(v);
//    Vector3D vecCam = v.minus(c);
//
//    int textureID = getMarkTexID(rc, m);
//
//    // draw mark if close to the point and not eclipsed by the earth
//    if (vecCam.Magnitude() < minDist && normal.AngleBetween(vecCam) > PI / 2) {
//      gl->DrawBillBoard(textureID, (float) v.X, (float) v.Y, (float) v.Z);
//      m->setVisible(true);
//    } else
//      m->setVisible(false);
//  }
//
//  gl->DepthTestEnabled(true);
//  gl->BlendingEnabled(false);
//
//
//  return 9999;
//}
<commit_msg>solved bug with markRenderer<commit_after>//
//  MarksRenderer.cpp
//  G3MiOSSDK
//
//  Created by Diego Gomez Deck on 05/06/12.
//  Copyright (c) 2012 IGO Software SL. All rights reserved.
//

#include "MarksRenderer.hpp"
#include "Camera.hpp"

void MarksRenderer::initialize(const InitializationContext* ic) {

}

bool MarksRenderer::onTouchEvent(const TouchEvent* touchEvent) {
  return false;
}

int MarksRenderer::render(const RenderContext* rc) {
//  rc.getLogger()->logInfo("MarksRenderer::render()");

  IGL* gl = rc->getGL();

  gl->enableVerticesPosition();
  gl->enableTextures();

  gl->depthTest(false);
  gl->blend(true);

  const Vector3D radius = rc->getPlanet()->getRadii();
  const double minDistanceToCamera = (radius.x() + radius.y() + radius.z()) * 2;

  int marksSize = _marks.size();
  for (int i = 0; i < marksSize; i++) {
    Mark* mark = _marks[i];
    //rc->getLogger()->logInfo("Rendering Mark: \"%s\"", mark->getName().c_str());

    mark->render(rc, minDistanceToCamera);
  }

  gl->depthTest(true);
  gl->blend(false);

  gl->disableTextures();
  gl->disableVerticesPosition();
  gl->disableTexture2D();

  return MAX_TIME_TO_RENDER;
}

//
//int MarksRenderer::Render(RenderContext &rc) {
//  // obtaing gl object reference
//  IGL *gl = rc.GetGL();
//  //Point3D po = View::GetInstance()->GetCamera()->GetPos();
//  //Vector3D c(po.x, po.y, po.z);
//  Vector3D c = View::GetInstance()->GetCamera()->GetPos();
//
//  gl->DepthTestEnabled(false);
//  gl->BlendingEnabled(true);
//
//  //DRAWING LOOP
//  Ellipsoid *ellipsoid = SceneController::GetInstance()->getGlobe()->GetEllipsoid();
//  Vector3D radius = ellipsoid->getRadii();
//  double minDist = (radius.X + radius.Y + radius.Z) / 3;
//  for (int i = 0; i < marks.markSet.size(); i++) {
//    Mark *m = marks.markSet.at(i);
//
//    Vector3D v = ellipsoid->ToVector3D(m->point);
//    Vector3D normal = Ellipsoid::CentricSurfaceNormal(v);
//    Vector3D vecCam = v.minus(c);
//
//    int textureID = getMarkTexID(rc, m);
//
//    // draw mark if close to the point and not eclipsed by the earth
//    if (vecCam.Magnitude() < minDist && normal.AngleBetween(vecCam) > PI / 2) {
//      gl->DrawBillBoard(textureID, (float) v.X, (float) v.Y, (float) v.Z);
//      m->setVisible(true);
//    } else
//      m->setVisible(false);
//  }
//
//  gl->DepthTestEnabled(true);
//  gl->BlendingEnabled(false);
//
//
//  return 9999;
//}
<|endoftext|>


<commit_before>//
// Copyright Copyright 2009-2019, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//

#include "Cuti.h"
#include <dlib/misc_api.h>
#include "adapter.hpp"
#include "data_item.hpp"

using namespace std;
using namespace mtconnect;

TEST_CLASS(DataItemTest)
{
protected:
  std::unique_ptr<DataItem> m_dataItemA;
  std::unique_ptr<DataItem> m_dataItemB;
  std::unique_ptr<DataItem> m_dataItemC;

public:
  void testGetters();
  void testGetAttributes();
  void testHasNameAndSource();
  void testIsSample();
  void testComponent();
  void testGetCamel();
  void testConversion();
  void testCondition();
  void testTimeSeries();
  void testStatistic();
  void testSampleRate();
  void testDuplicates();
  void testFilter();
  void testReferences();

  void setUp();
  void tearDown();

  CPPUNIT_TEST_SUITE(DataItemTest);
  CPPUNIT_TEST(testGetters);
  CPPUNIT_TEST(testGetAttributes);
  CPPUNIT_TEST(testHasNameAndSource);
  CPPUNIT_TEST(testIsSample);
  CPPUNIT_TEST(testComponent);
  CPPUNIT_TEST(testGetCamel);
  CPPUNIT_TEST(testConversion);
  CPPUNIT_TEST(testCondition);
  CPPUNIT_TEST(testTimeSeries);
  CPPUNIT_TEST(testStatistic);
  CPPUNIT_TEST(testSampleRate);
  CPPUNIT_TEST(testDuplicates);
  CPPUNIT_TEST(testFilter);
  CPPUNIT_TEST_SUITE_END();
};

// Registers the fixture into the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION(DataItemTest);

void DataItemTest::setUp()
{
  std::map<string, string> attributes1, attributes2, attributes3;

  attributes1["id"] = "1";
  attributes1["name"] = "DataItemTest1";
  attributes1["type"] = "ACCELERATION";
  attributes1["category"] = "SAMPLE";
  attributes1["nativeUnits"] = "PERCENT";
  m_dataItemA = make_unique<DataItem>(attributes1);

  attributes2["id"] = "3";
  attributes2["name"] = "DataItemTest2";
  attributes2["type"] = "ACCELERATION";
  attributes2["subType"] = "ACTUAL";
  attributes2["category"] = "EVENT";
  attributes2["units"] = "REVOLUTION/MINUTE";
  attributes2["nativeScale"] = "1.0";
  attributes2["significantDigits"] = "1";
  attributes2["coordinateSystem"] = "testCoordinateSystem";
  m_dataItemB = make_unique<DataItem>(attributes2);

  attributes3["id"] = "4";
  attributes3["name"] = "DataItemTest3";
  attributes3["type"] = "LOAD";
  attributes3["category"] = "CONDITION";
  m_dataItemC = make_unique<DataItem>(attributes3);
}

void DataItemTest::tearDown()
{
  m_dataItemA.reset();
  m_dataItemB.reset();
  m_dataItemC.reset();
}

void DataItemTest::testGetters()
{
  CPPUNIT_ASSERT_EQUAL((string) "1", m_dataItemA->getId());
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest1", m_dataItemA->getName());
  CPPUNIT_ASSERT_EQUAL((string) "ACCELERATION", m_dataItemA->getType());
  CPPUNIT_ASSERT_EQUAL((string) "Acceleration", m_dataItemA->getElementName());
  CPPUNIT_ASSERT_EQUAL((string) "PERCENT", m_dataItemA->getNativeUnits());
  CPPUNIT_ASSERT(m_dataItemA->getSubType().empty());
  CPPUNIT_ASSERT(!m_dataItemA->hasNativeScale());

  CPPUNIT_ASSERT_EQUAL((string) "3", m_dataItemB->getId());
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest2", m_dataItemB->getName());
  CPPUNIT_ASSERT_EQUAL((string) "ACCELERATION", m_dataItemB->getType());
  CPPUNIT_ASSERT_EQUAL((string) "Acceleration", m_dataItemB->getElementName());
  CPPUNIT_ASSERT_EQUAL((string) "ACTUAL", m_dataItemB->getSubType());
  CPPUNIT_ASSERT_EQUAL(m_dataItemB->getNativeUnits(), m_dataItemB->getUnits());
  CPPUNIT_ASSERT_EQUAL(1.0f, m_dataItemB->getNativeScale());
}

void DataItemTest::testGetAttributes()
{
  const auto &attributes1 = m_dataItemA->getAttributes();
  CPPUNIT_ASSERT_EQUAL((string) "1", attributes1.at("id"));
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest1", attributes1.at("name"));
  CPPUNIT_ASSERT_EQUAL((string) "ACCELERATION", attributes1.at("type"));
  CPPUNIT_ASSERT(attributes1.find("subType") == attributes1.end());
  CPPUNIT_ASSERT_EQUAL((string) "PERCENT", attributes1.at("nativeUnits"));
  CPPUNIT_ASSERT(attributes1.find("getNativeScale") == attributes1.end());
  CPPUNIT_ASSERT(attributes1.find("coordinateSystem") == attributes1.end());

  const auto &attributes2 = m_dataItemB->getAttributes();
  CPPUNIT_ASSERT_EQUAL((string) "3", attributes2.at("id"));
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest2", attributes2.at("name"));
  CPPUNIT_ASSERT_EQUAL((string) "ACCELERATION", attributes2.at("type"));
  CPPUNIT_ASSERT_EQUAL((string) "ACTUAL", attributes2.at("subType"));
  CPPUNIT_ASSERT_EQUAL(attributes2.at("nativeUnits"), attributes2.at("units"));
  CPPUNIT_ASSERT_EQUAL((string) "1", attributes2.at("nativeScale"));
  CPPUNIT_ASSERT_EQUAL((string) "testCoordinateSystem",
                       attributes2.at("coordinateSystem"));
}

void DataItemTest::testHasNameAndSource()
{
  CPPUNIT_ASSERT(m_dataItemA->hasName("DataItemTest1"));
  CPPUNIT_ASSERT(m_dataItemB->hasName("DataItemTest2"));

  CPPUNIT_ASSERT(m_dataItemA->getSource().empty());
  CPPUNIT_ASSERT(m_dataItemB->getSource().empty());

  CPPUNIT_ASSERT(!m_dataItemB->hasName("DataItemTest2Source"));
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest2", m_dataItemB->getSourceOrName());

  m_dataItemB->addSource("DataItemTest2Source", "", "", "");
  CPPUNIT_ASSERT(m_dataItemB->hasName("DataItemTest2Source"));
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest2Source", m_dataItemB->getSource());
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest2Source", m_dataItemB->getSourceOrName());
}

void DataItemTest::testIsSample()
{
  CPPUNIT_ASSERT(m_dataItemA->isSample());
  CPPUNIT_ASSERT(!m_dataItemB->isSample());
}

void DataItemTest::testComponent()
{
  std::map<string, string> attributes1;
  attributes1["id"] = "3";
  attributes1["name"] = "AxesTestA";
  attributes1["uuid"] = "UniversalUniqueIdA";
  attributes1["sampleRate"] = "100.11";

  mtconnect::Component axes("Axes", attributes1);
  m_dataItemA->setComponent(axes);

  CPPUNIT_ASSERT(&axes == m_dataItemA->getComponent());
}

void DataItemTest::testGetCamel()
{
  string prefix;
  CPPUNIT_ASSERT(DataItem::getCamelType("", prefix).empty());
  CPPUNIT_ASSERT_EQUAL((string) "Camels", DataItem::getCamelType("CAMELS", prefix));
  CPPUNIT_ASSERT(prefix.empty());

  // Test the one exception to the rules...
  CPPUNIT_ASSERT_EQUAL((string) "PH", DataItem::getCamelType("PH", prefix));

  CPPUNIT_ASSERT_EQUAL((string) "CamelCase", DataItem::getCamelType("CAMEL_CASE", prefix));
  CPPUNIT_ASSERT_EQUAL((string) "ABCc", DataItem::getCamelType("A_B_CC", prefix));
  prefix.clear();
  CPPUNIT_ASSERT_EQUAL((string) "CamelCase", DataItem::getCamelType("x:CAMEL_CASE", prefix));
  CPPUNIT_ASSERT_EQUAL((string) "x", prefix);
}

void DataItemTest::testConversion()
{
  std::map<string, string> attributes1;
  attributes1["id"] = "p";
  attributes1["name"] = "position";
  attributes1["type"] = "POSITION";
  attributes1["category"] = "SAMPLE";
  attributes1["units"] = "MILLIMETER_3D";
  attributes1["nativeUnits"] = "INCH_3D";
  attributes1["coordinateSystem"] = "testCoordinateSystem";
  DataItem item1(attributes1);
  item1.conversionRequired();

  CPPUNIT_ASSERT_EQUAL((string) "25.4 50.8 76.2", item1.convertValue("1 2 3"));
  CPPUNIT_ASSERT_EQUAL((string) "25.4 50.8 76.2", item1.convertValue("1  2  3"));

  std::map<string, string> attributes2;
  attributes2["id"] = "p";
  attributes2["name"] = "position";
  attributes2["type"] = "POSITION";
  attributes2["category"] = "SAMPLE";
  attributes2["units"] = "DEGREE_3D";
  attributes2["nativeUnits"] = "RADIAN_3D";
  attributes2["coordinateSystem"] = "testCoordinateSystem";
  DataItem item2(attributes2);
  item2.conversionRequired();

  CPPUNIT_ASSERT_EQUAL((string) "57.29578 114.5916 171.8873", item2.convertValue("1 2 3"));

  std::map<string, string> attributes3;
  attributes3["id"] = "p";
  attributes3["name"] = "position";
  attributes3["type"] = "POSITION";
  attributes3["category"] = "SAMPLE";
  attributes3["units"] = "MILLIMETER";
  attributes3["nativeUnits"] = "MILLIMETER";
  attributes3["nativeScale"] = "10";
  attributes3["coordinateSystem"] = "testScale";
  DataItem item3(attributes3);
  item3.conversionRequired();

  CPPUNIT_ASSERT_EQUAL((string) "1.3", item3.convertValue("13"));

  std::map<string, string> attributes4;
  attributes4["id"] = "p";
  attributes4["name"] = "position";
  attributes4["type"] = "POSITION";
  attributes4["category"] = "SAMPLE";
  attributes4["units"] = "AMPERE";
  attributes4["nativeUnits"] = "KILOAMPERE";
  attributes4["coordinateSystem"] = "testScale";
  DataItem item4(attributes4);
  item4.conversionRequired();

  CPPUNIT_ASSERT_EQUAL((string) "130", item4.convertValue("0.13"));

  DataItem item5(attributes4);

  Adapter adapter("", "", 0);
  adapter.setConversionRequired(false);

  item5.setDataSource(&adapter);
  CPPUNIT_ASSERT(!item5.conversionRequired());

  CPPUNIT_ASSERT_EQUAL((string) "0.13", item5.convertValue("0.13"));

}

void DataItemTest::testCondition()
{
  CPPUNIT_ASSERT_EQUAL(DataItem::CONDITION, m_dataItemC->getCategory());
}

void DataItemTest::testTimeSeries()
{
  std::map<string, string> attributes1;

  attributes1["id"] = "1";
  attributes1["name"] = "DataItemTest1";
  attributes1["type"] = "POSITION";
  attributes1["category"] = "SAMPLE";
  attributes1["units"] = "MILLIMETER";
  attributes1["nativeUnits"] = "MILLIMETER";
  attributes1["representation"] = "TIME_SERIES";
  auto d = make_unique<DataItem>(attributes1);

  CPPUNIT_ASSERT_EQUAL(string("PositionTimeSeries"), d->getElementName());
  d.reset();

  attributes1.clear();
  attributes1["id"] = "1";
  attributes1["name"] = "DataItemTest1";
  attributes1["type"] = "POSITION";
  attributes1["category"] = "SAMPLE";
  attributes1["units"] = "MILLIMETER";
  attributes1["nativeUnits"] = "MILLIMETER";
  attributes1["representation"] = "VALUE";
  d = make_unique<DataItem>(attributes1);

  CPPUNIT_ASSERT_EQUAL(string("Position"), d->getElementName());
  d.reset();
}

void DataItemTest::testStatistic()
{
  std::map<string, string> attributes1;

  attributes1["id"] = "1";
  attributes1["name"] = "DataItemTest1";
  attributes1["type"] = "POSITION";
  attributes1["category"] = "SAMPLE";
  attributes1["units"] = "MILLIMETER";
  attributes1["nativeUnits"] = "MILLIMETER";
  attributes1["statistic"] = "AVERAGE";
  auto d = make_unique<DataItem>(attributes1);

  CPPUNIT_ASSERT_EQUAL(string("AVERAGE"), d->getStatistic());
  d.reset();
}

void DataItemTest::testSampleRate()
{
  std::map<string, string> attributes1;

  attributes1["id"] = "1";
  attributes1["name"] = "DataItemTest1";
  attributes1["type"] = "POSITION";
  attributes1["category"] = "SAMPLE";
  attributes1["units"] = "MILLIMETER";
  attributes1["nativeUnits"] = "MILLIMETER";
  attributes1["statistic"] = "AVERAGE";
  attributes1["representation"] = "TIME_SERIES";
  attributes1["sampleRate"] = "42000";
  auto d = make_unique<DataItem>(attributes1);

  CPPUNIT_ASSERT_EQUAL(string("42000"), d->getSampleRate());
  d.reset();
}

void DataItemTest::testDuplicates()
{
  CPPUNIT_ASSERT(!m_dataItemA->isDuplicate("FOO"));
  CPPUNIT_ASSERT(m_dataItemA->isDuplicate("FOO"));
  CPPUNIT_ASSERT(!m_dataItemA->isDuplicate("FOO2"));
}

void DataItemTest::testFilter()
{
  m_dataItemA->setMinmumDelta(5.0);

  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(5.0, 0.0));
  CPPUNIT_ASSERT(m_dataItemA->isFiltered(6.0, 0.0));
  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(10.1, 0.0));
  CPPUNIT_ASSERT(m_dataItemA->isFiltered(6.0, 0.0));
  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(5.0, 0.0));

  // Test period
  m_dataItemA->setMinmumDelta(1.0);
  m_dataItemA->setMinmumPeriod(1.0);

  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(1.0, 0.0));
  CPPUNIT_ASSERT(m_dataItemA->isFiltered(3.0, 0.1));
  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(5, 1.1));
  CPPUNIT_ASSERT(m_dataItemA->isFiltered(7.0, 2.0));
  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(9.0, 2.2));

}
<commit_msg>Fixed broken DataItem tests<commit_after>//
// Copyright Copyright 2009-2019, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//

#include "Cuti.h"
#include <dlib/misc_api.h>
#include "adapter.hpp"
#include "data_item.hpp"

using namespace std;
using namespace mtconnect;

TEST_CLASS(DataItemTest)
{
protected:
  std::unique_ptr<DataItem> m_dataItemA;
  std::unique_ptr<DataItem> m_dataItemB;
  std::unique_ptr<DataItem> m_dataItemC;

public:
  void testGetters();
  void testGetAttributes();
  void testHasNameAndSource();
  void testIsSample();
  void testComponent();
  void testGetCamel();
  void testConversion();
  void testCondition();
  void testTimeSeries();
  void testStatistic();
  void testSampleRate();
  void testDuplicates();
  void testFilter();
  void testReferences();

  SET_UP();
  TEAR_DOWN();

  CPPUNIT_TEST_SUITE(DataItemTest);
  CPPUNIT_TEST(testGetters);
  CPPUNIT_TEST(testGetAttributes);
  CPPUNIT_TEST(testHasNameAndSource);
  CPPUNIT_TEST(testIsSample);
  CPPUNIT_TEST(testComponent);
  CPPUNIT_TEST(testGetCamel);
  CPPUNIT_TEST(testConversion);
  CPPUNIT_TEST(testCondition);
  CPPUNIT_TEST(testTimeSeries);
  CPPUNIT_TEST(testStatistic);
  CPPUNIT_TEST(testSampleRate);
  CPPUNIT_TEST(testDuplicates);
  CPPUNIT_TEST(testFilter);
  CPPUNIT_TEST_SUITE_END();
};

// Registers the fixture into the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION(DataItemTest);

void DataItemTest::setUp()
{
  std::map<string, string> attributes1, attributes2, attributes3;

  attributes1["id"] = "1";
  attributes1["name"] = "DataItemTest1";
  attributes1["type"] = "ACCELERATION";
  attributes1["category"] = "SAMPLE";
  attributes1["nativeUnits"] = "PERCENT";
  m_dataItemA = make_unique<DataItem>(attributes1);

  attributes2["id"] = "3";
  attributes2["name"] = "DataItemTest2";
  attributes2["type"] = "ACCELERATION";
  attributes2["subType"] = "ACTUAL";
  attributes2["category"] = "EVENT";
  attributes2["units"] = "REVOLUTION/MINUTE";
  attributes2["nativeScale"] = "1.0";
  attributes2["significantDigits"] = "1";
  attributes2["coordinateSystem"] = "testCoordinateSystem";
  m_dataItemB = make_unique<DataItem>(attributes2);

  attributes3["id"] = "4";
  attributes3["name"] = "DataItemTest3";
  attributes3["type"] = "LOAD";
  attributes3["category"] = "CONDITION";
  m_dataItemC = make_unique<DataItem>(attributes3);
}

void DataItemTest::tearDown()
{
  m_dataItemA.reset();
  m_dataItemB.reset();
  m_dataItemC.reset();
}

void DataItemTest::testGetters()
{
  CPPUNIT_ASSERT_EQUAL((string) "1", m_dataItemA->getId());
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest1", m_dataItemA->getName());
  CPPUNIT_ASSERT_EQUAL((string) "ACCELERATION", m_dataItemA->getType());
  CPPUNIT_ASSERT_EQUAL((string) "Acceleration", m_dataItemA->getElementName());
  CPPUNIT_ASSERT_EQUAL((string) "PERCENT", m_dataItemA->getNativeUnits());
  CPPUNIT_ASSERT(m_dataItemA->getSubType().empty());
  CPPUNIT_ASSERT(!m_dataItemA->hasNativeScale());

  CPPUNIT_ASSERT_EQUAL((string) "3", m_dataItemB->getId());
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest2", m_dataItemB->getName());
  CPPUNIT_ASSERT_EQUAL((string) "ACCELERATION", m_dataItemB->getType());
  CPPUNIT_ASSERT_EQUAL((string) "Acceleration", m_dataItemB->getElementName());
  CPPUNIT_ASSERT_EQUAL((string) "ACTUAL", m_dataItemB->getSubType());
  CPPUNIT_ASSERT_EQUAL(m_dataItemB->getNativeUnits(), m_dataItemB->getUnits());
  CPPUNIT_ASSERT_EQUAL(1.0f, m_dataItemB->getNativeScale());
}

void DataItemTest::testGetAttributes()
{
  const auto &attributes1 = m_dataItemA->getAttributes();
  CPPUNIT_ASSERT_EQUAL((string) "1", attributes1.at("id"));
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest1", attributes1.at("name"));
  CPPUNIT_ASSERT_EQUAL((string) "ACCELERATION", attributes1.at("type"));
  CPPUNIT_ASSERT(attributes1.find("subType") == attributes1.end());
  CPPUNIT_ASSERT_EQUAL((string) "PERCENT", attributes1.at("nativeUnits"));
  CPPUNIT_ASSERT(attributes1.find("getNativeScale") == attributes1.end());
  CPPUNIT_ASSERT(attributes1.find("coordinateSystem") == attributes1.end());

  const auto &attributes2 = m_dataItemB->getAttributes();
  CPPUNIT_ASSERT_EQUAL((string) "3", attributes2.at("id"));
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest2", attributes2.at("name"));
  CPPUNIT_ASSERT_EQUAL((string) "ACCELERATION", attributes2.at("type"));
  CPPUNIT_ASSERT_EQUAL((string) "ACTUAL", attributes2.at("subType"));
  CPPUNIT_ASSERT_EQUAL(attributes2.at("nativeUnits"), attributes2.at("units"));
  CPPUNIT_ASSERT_EQUAL((string) "1", attributes2.at("nativeScale"));
  CPPUNIT_ASSERT_EQUAL((string) "testCoordinateSystem",
                       attributes2.at("coordinateSystem"));
}

void DataItemTest::testHasNameAndSource()
{
  CPPUNIT_ASSERT(m_dataItemA->hasName("DataItemTest1"));
  CPPUNIT_ASSERT(m_dataItemB->hasName("DataItemTest2"));

  CPPUNIT_ASSERT(m_dataItemA->getSource().empty());
  CPPUNIT_ASSERT(m_dataItemB->getSource().empty());

  CPPUNIT_ASSERT(!m_dataItemB->hasName("DataItemTest2Source"));
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest2", m_dataItemB->getSourceOrName());

  m_dataItemB->addSource("DataItemTest2Source", "", "", "");
  CPPUNIT_ASSERT(m_dataItemB->hasName("DataItemTest2Source"));
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest2Source", m_dataItemB->getSource());
  CPPUNIT_ASSERT_EQUAL((string) "DataItemTest2Source", m_dataItemB->getSourceOrName());
}

void DataItemTest::testIsSample()
{
  CPPUNIT_ASSERT(m_dataItemA->isSample());
  CPPUNIT_ASSERT(!m_dataItemB->isSample());
}

void DataItemTest::testComponent()
{
  std::map<string, string> attributes1;
  attributes1["id"] = "3";
  attributes1["name"] = "AxesTestA";
  attributes1["uuid"] = "UniversalUniqueIdA";
  attributes1["sampleRate"] = "100.11";

  mtconnect::Component axes("Axes", attributes1);
  m_dataItemA->setComponent(axes);

  CPPUNIT_ASSERT(&axes == m_dataItemA->getComponent());
}

void DataItemTest::testGetCamel()
{
  string prefix;
  CPPUNIT_ASSERT(DataItem::getCamelType("", prefix).empty());
  CPPUNIT_ASSERT_EQUAL((string) "Camels", DataItem::getCamelType("CAMELS", prefix));
  CPPUNIT_ASSERT(prefix.empty());

  // Test the one exception to the rules...
  CPPUNIT_ASSERT_EQUAL((string) "PH", DataItem::getCamelType("PH", prefix));

  CPPUNIT_ASSERT_EQUAL((string) "CamelCase", DataItem::getCamelType("CAMEL_CASE", prefix));
  CPPUNIT_ASSERT_EQUAL((string) "ABCc", DataItem::getCamelType("A_B_CC", prefix));
  prefix.clear();
  CPPUNIT_ASSERT_EQUAL((string) "CamelCase", DataItem::getCamelType("x:CAMEL_CASE", prefix));
  CPPUNIT_ASSERT_EQUAL((string) "x", prefix);
}

void DataItemTest::testConversion()
{
  std::map<string, string> attributes1;
  attributes1["id"] = "p";
  attributes1["name"] = "position";
  attributes1["type"] = "POSITION";
  attributes1["category"] = "SAMPLE";
  attributes1["units"] = "MILLIMETER_3D";
  attributes1["nativeUnits"] = "INCH_3D";
  attributes1["coordinateSystem"] = "testCoordinateSystem";
  DataItem item1(attributes1);
  item1.conversionRequired();

  CPPUNIT_ASSERT_EQUAL((string) "25.4 50.8 76.2", item1.convertValue("1 2 3"));
  CPPUNIT_ASSERT_EQUAL((string) "25.4 50.8 76.2", item1.convertValue("1  2  3"));

  std::map<string, string> attributes2;
  attributes2["id"] = "p";
  attributes2["name"] = "position";
  attributes2["type"] = "POSITION";
  attributes2["category"] = "SAMPLE";
  attributes2["units"] = "DEGREE_3D";
  attributes2["nativeUnits"] = "RADIAN_3D";
  attributes2["coordinateSystem"] = "testCoordinateSystem";
  DataItem item2(attributes2);
  item2.conversionRequired();

  CPPUNIT_ASSERT_EQUAL((string) "57.29578 114.5916 171.8873", item2.convertValue("1 2 3"));

  std::map<string, string> attributes3;
  attributes3["id"] = "p";
  attributes3["name"] = "position";
  attributes3["type"] = "POSITION";
  attributes3["category"] = "SAMPLE";
  attributes3["units"] = "MILLIMETER";
  attributes3["nativeUnits"] = "MILLIMETER";
  attributes3["nativeScale"] = "10";
  attributes3["coordinateSystem"] = "testScale";
  DataItem item3(attributes3);
  item3.conversionRequired();

  CPPUNIT_ASSERT_EQUAL((string) "1.3", item3.convertValue("13"));

  std::map<string, string> attributes4;
  attributes4["id"] = "p";
  attributes4["name"] = "position";
  attributes4["type"] = "POSITION";
  attributes4["category"] = "SAMPLE";
  attributes4["units"] = "AMPERE";
  attributes4["nativeUnits"] = "KILOAMPERE";
  attributes4["coordinateSystem"] = "testScale";
  DataItem item4(attributes4);
  item4.conversionRequired();

  CPPUNIT_ASSERT_EQUAL((string) "130", item4.convertValue("0.13"));

  DataItem item5(attributes4);

  Adapter adapter("", "", 0);
  adapter.setConversionRequired(false);

  item5.setDataSource(&adapter);
  CPPUNIT_ASSERT(!item5.conversionRequired());

  CPPUNIT_ASSERT_EQUAL((string) "0.13", item5.convertValue("0.13"));

}

void DataItemTest::testCondition()
{
  CPPUNIT_ASSERT_EQUAL(DataItem::CONDITION, m_dataItemC->getCategory());
}

void DataItemTest::testTimeSeries()
{
  std::map<string, string> attributes1;

  attributes1["id"] = "1";
  attributes1["name"] = "DataItemTest1";
  attributes1["type"] = "POSITION";
  attributes1["category"] = "SAMPLE";
  attributes1["units"] = "MILLIMETER";
  attributes1["nativeUnits"] = "MILLIMETER";
  attributes1["representation"] = "TIME_SERIES";
  auto d = make_unique<DataItem>(attributes1);

  CPPUNIT_ASSERT_EQUAL(string("PositionTimeSeries"), d->getElementName());
  d.reset();

  attributes1.clear();
  attributes1["id"] = "1";
  attributes1["name"] = "DataItemTest1";
  attributes1["type"] = "POSITION";
  attributes1["category"] = "SAMPLE";
  attributes1["units"] = "MILLIMETER";
  attributes1["nativeUnits"] = "MILLIMETER";
  attributes1["representation"] = "VALUE";
  d = make_unique<DataItem>(attributes1);

  CPPUNIT_ASSERT_EQUAL(string("Position"), d->getElementName());
  d.reset();
}

void DataItemTest::testStatistic()
{
  std::map<string, string> attributes1;

  attributes1["id"] = "1";
  attributes1["name"] = "DataItemTest1";
  attributes1["type"] = "POSITION";
  attributes1["category"] = "SAMPLE";
  attributes1["units"] = "MILLIMETER";
  attributes1["nativeUnits"] = "MILLIMETER";
  attributes1["statistic"] = "AVERAGE";
  auto d = make_unique<DataItem>(attributes1);

  CPPUNIT_ASSERT_EQUAL(string("AVERAGE"), d->getStatistic());
  d.reset();
}

void DataItemTest::testSampleRate()
{
  std::map<string, string> attributes1;

  attributes1["id"] = "1";
  attributes1["name"] = "DataItemTest1";
  attributes1["type"] = "POSITION";
  attributes1["category"] = "SAMPLE";
  attributes1["units"] = "MILLIMETER";
  attributes1["nativeUnits"] = "MILLIMETER";
  attributes1["statistic"] = "AVERAGE";
  attributes1["representation"] = "TIME_SERIES";
  attributes1["sampleRate"] = "42000";
  auto d = make_unique<DataItem>(attributes1);

  CPPUNIT_ASSERT_EQUAL(string("42000"), d->getSampleRate());
  d.reset();
}

void DataItemTest::testDuplicates()
{
  CPPUNIT_ASSERT(!m_dataItemA->isDuplicate("FOO"));
  CPPUNIT_ASSERT(m_dataItemA->isDuplicate("FOO"));
  CPPUNIT_ASSERT(!m_dataItemA->isDuplicate("FOO2"));
}

void DataItemTest::testFilter()
{
  m_dataItemA->setMinmumDelta(5.0);

  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(5.0, 0.0));
  CPPUNIT_ASSERT(m_dataItemA->isFiltered(6.0, 0.0));
  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(10.1, 0.0));
  CPPUNIT_ASSERT(m_dataItemA->isFiltered(6.0, 0.0));
  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(5.0, 0.0));

  // Test period
  m_dataItemA->setMinmumDelta(1.0);
  m_dataItemA->setMinmumPeriod(1.0);

  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(1.0, 0.0));
  CPPUNIT_ASSERT(m_dataItemA->isFiltered(3.0, 0.1));
  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(5, 1.1));
  CPPUNIT_ASSERT(m_dataItemA->isFiltered(7.0, 2.0));
  CPPUNIT_ASSERT(!m_dataItemA->isFiltered(9.0, 2.2));

}
<|endoftext|>


<commit_before>#ifndef INC_AL_OVERLAY_TEXT_OPENGL_HPP
#define INC_AL_OVERLAY_TEXT_OPENGL_HPP

/*	Allocore --
	Multimedia / virtual environment application class library

	Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
	Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
	All Rights Reserved.

	Permission to use, copy, modify, distribute, and distribute modified versions
	of this software and its documentation without fee and without a signed
	licensing agreement, is hereby granted, provided that the above copyright
	notice, the list of contributors, this paragraph and the following two paragraphs
	appear in all copies, modifications, and distributions.

	IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
	SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
	OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
	BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
	THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
	PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
	HEREUNDER IS PROVIDED "AS IS". REGENTS HAS  NO OBLIGATION TO PROVIDE
	MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

	File description:
	A printf for OpenGL windows:

	File author(s):
	Graham Wakefield, 2010, grrrwaaa@gmail.com
*/

#include "allocore/graphics/al_Graphics.hpp"
#include "allocore/graphics/al_Font.hpp"

/*!
	A printf for OpenGL windows:
 */

namespace al {

class OverlayText {
public:

	OverlayText(std::string fontfile, int maxlines = 20)
	: font(fontfile), mMaxlines(maxlines) {}

	void printf(std::string line) {
		lines.push_back(line);
	}
	void printf(const char * fmt, ...) {
		static char line[1024];
		va_list args;
		va_start(args, fmt);
		vsnprintf(line, 1024, fmt, args);
		va_end(args);
		lines.push_back(line);
	}

	void draw() {
		gl.pushMatrix();
		// because OpenGL/font is upside-down:
		gl.scale(1, -1, 1);
		for (std::vector<std::string>::iterator it = lines.begin(); it != lines.end(); it++) {
			gl.translate(0, -font.size(), 0);
			//gl.translate(0.5, 0.5, 0);
			font.render(gl, *it);
		}
		gl.popMatrix();
		if (lines.size() > mMaxlines) lines.clear();
	}

	void clear() {
		lines.clear();
	}

	std::vector<std::string> lines;
	Graphics gl;
	Font font;
	int mMaxlines;
};

} // al::

#endif
<commit_msg>scrolling mode to overlaytext<commit_after>#ifndef INC_AL_OVERLAY_TEXT_OPENGL_HPP
#define INC_AL_OVERLAY_TEXT_OPENGL_HPP

/*	Allocore --
	Multimedia / virtual environment application class library

	Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
	Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
	All Rights Reserved.

	Permission to use, copy, modify, distribute, and distribute modified versions
	of this software and its documentation without fee and without a signed
	licensing agreement, is hereby granted, provided that the above copyright
	notice, the list of contributors, this paragraph and the following two paragraphs
	appear in all copies, modifications, and distributions.

	IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
	SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
	OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
	BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
	THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
	PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
	HEREUNDER IS PROVIDED "AS IS". REGENTS HAS  NO OBLIGATION TO PROVIDE
	MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

	File description:
	A printf for OpenGL windows:

	File author(s):
	Graham Wakefield, 2010, grrrwaaa@gmail.com
*/

#include "allocore/graphics/al_Graphics.hpp"
#include "allocore/graphics/al_Font.hpp"

/*!
	A printf for OpenGL windows:
 */

namespace al {

class OverlayText {
public:

	OverlayText(std::string fontfile, int maxlines = 20)
	: font(fontfile), mMaxlines(maxlines) {}

	void printf(std::string line) {
		lines.push_back(line);
	}
	void printf(const char * fmt, ...) {
		static char line[1024];
		va_list args;
		va_start(args, fmt);
		vsnprintf(line, 1024, fmt, args);
		va_end(args);
		lines.push_back(line);
	}

	void draw() {
		while (lines.size() > mMaxlines) lines.pop_front();
		gl.pushMatrix();
		// because OpenGL/font is upside-down:
		gl.scale(1, -1, 1);
		for (std::list<std::string>::iterator it = lines.begin(); it != lines.end(); it++) {
			gl.translate(0, -font.size(), 0);
			//gl.translate(0.5, 0.5, 0);
			font.render(gl, *it);
		}
		gl.popMatrix();
	}

	void clear() {
		lines.clear();
	}

	std::list<std::string> lines;
	Graphics gl;
	Font font;
	int mMaxlines;
};

} // al::

#endif
<|endoftext|>


<commit_before>//  (C) Copyright Gennadiy Rozental 2011-2012.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : defines test case family based on data generator
// ***************************************************************************

#ifndef BOOST_TEST_DATA_TEST_CASE_HPP_102211GER
#define BOOST_TEST_DATA_TEST_CASE_HPP_102211GER

// Boost.Test
#include <boost/test/data/config.hpp>
#include <boost/test/data/dataset.hpp>

// Boost
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_shifted_binary_params.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/preprocessor/comparison/equal.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/punctuation/comma.hpp>

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

namespace boost {
namespace unit_test {
namespace data {

// ************************************************************************** //
// **************              test_case_template              ************** //
// ************************************************************************** //

namespace ds_detail {

template<typename TestCase,typename DS>
class test_case_gen : public test_unit_generator {
public:
    // Constructor
    test_case_gen( const_string tc_name, DS&& ds )
    : m_tc_name( ut_detail::normalize_test_case_name( tc_name ) )
    {
        data::for_each_sample( ds, *this );
    }
    test_case_gen( test_case_gen&& gen )
    : m_tc_name( gen.m_tc_name )
    , m_test_cases( std::move(gen.m_test_cases) )
    {}

    virtual test_unit* next() const
    {
        if( m_test_cases.empty() )
            return 0;

        test_unit* res = m_test_cases.front();
        m_test_cases.pop_front();

        return res;
    }

    // !! ?? variadics based implementation
#define TC_MAKE(z,arity,_)                                                          \
    template<BOOST_PP_ENUM_PARAMS(arity, typename Arg)>                             \
    void    operator()( BOOST_PP_ENUM_BINARY_PARAMS(arity, Arg, const& arg) ) const \
    {                                                                               \
        m_test_cases.push_back( new test_case( m_tc_name,                           \
            std::bind( &TestCase::test_method<BOOST_PP_ENUM_PARAMS(arity,Arg)>,     \
            BOOST_PP_ENUM_PARAMS(arity, arg) ) ) );                                 \
    }                                                                               \

    BOOST_PP_REPEAT_FROM_TO(1, 4, TC_MAKE, _)

private:
    // Data members
    std::string                     m_tc_name;
    mutable std::list<test_unit*>   m_test_cases;
};

//____________________________________________________________________________//

template<typename TestCase,typename DS>
test_case_gen<TestCase,DS>
make_test_case_gen( const_string tc_name, DS&& ds )
{
    return test_case_gen<TestCase,DS>( tc_name, std::forward<DS>(ds) );
}

//____________________________________________________________________________//

} // namespace ds_detail

// ************************************************************************** //
// **************            BOOST_DATA_TEST_CASE_N            ************** //
// ************************************************************************** //

#define BOOST_DATA_TEST_CASE_N_ARGS( arity )                            \
    BOOST_PP_IIF(BOOST_PP_EQUAL(arity, 1),                              \
        Arg0 const& sample,                                             \
        Arg0 const& sample0 )                                           \
    BOOST_PP_IIF(BOOST_PP_EQUAL(arity, 1),                              \
        BOOST_PP_EMPTY,                                                 \
        BOOST_PP_COMMA )()                                              \
    BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(arity, Arg, const& sample)      \
/**/

#define BOOST_DATA_TEST_CASE_N( arity, test_name, dataset )             \
struct test_name                                                        \
{                                                                       \
    template<BOOST_PP_ENUM_PARAMS(arity, typename Arg)>                 \
    static void test_method( BOOST_DATA_TEST_CASE_N_ARGS( arity ) );    \
};                                                                      \
                                                                        \
BOOST_AUTO_TU_REGISTRAR( test_name )(                                   \
    boost::unit_test::data::ds_detail::make_test_case_gen<test_name>(   \
          BOOST_STRINGIZE( test_name ), data::make(dataset) ),          \
    boost::unit_test::decorator::collector::instance() );               \
                                                                        \
    template<BOOST_PP_ENUM_PARAMS(arity, typename Arg)>                 \
    void test_name::test_method( BOOST_DATA_TEST_CASE_N_ARGS( arity ) ) \
/**/

// ************************************************************************** //
// **************             BOOST_DATA_TEST_CASE             ************** //
// ************************************************************************** //

#define BOOST_DATA_TEST_CASE( test_name, dataset )                      \
    BOOST_DATA_TEST_CASE_N( 1, test_name, dataset )

} // namespace data
} // namespace unit_test
} // namespace boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_DATA_TEST_CASE_HPP_102211GER

<commit_msg>updated interface<commit_after>//  (C) Copyright Gennadiy Rozental 2011-2012.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : defines test case family based on data generator
// ***************************************************************************

#ifndef BOOST_TEST_DATA_TEST_CASE_HPP_102211GER
#define BOOST_TEST_DATA_TEST_CASE_HPP_102211GER

// Boost.Test
#include <boost/test/data/config.hpp>
#include <boost/test/data/dataset.hpp>

// Boost
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>

#include <boost/preprocessor/variadic/to_seq.hpp>
#include <boost/preprocessor/variadic/size.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/enum.hpp>

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

namespace boost {
namespace unit_test {
namespace data {

// ************************************************************************** //
// **************              test_case_template              ************** //
// ************************************************************************** //

namespace ds_detail {

template<typename TestCase,typename DS>
class test_case_gen : public test_unit_generator {
public:
    // Constructor
    test_case_gen( const_string tc_name, DS&& ds )
    : m_tc_name( ut_detail::normalize_test_case_name( tc_name ) )
    {
        data::for_each_sample( ds, *this );
    }
    test_case_gen( test_case_gen&& gen )
    : m_tc_name( gen.m_tc_name )
    , m_test_cases( std::move(gen.m_test_cases) )
    {}

    virtual test_unit* next() const
    {
        if( m_test_cases.empty() )
            return 0;

        test_unit* res = m_test_cases.front();
        m_test_cases.pop_front();

        return res;
    }

    // !! ?? variadics based implementation
#define TC_MAKE(z,arity,_)                                                          \
    template<BOOST_PP_ENUM_PARAMS(arity, typename Arg)>                             \
    void    operator()( BOOST_PP_ENUM_BINARY_PARAMS(arity, Arg, const& arg) ) const \
    {                                                                               \
        m_test_cases.push_back( new test_case( m_tc_name,                           \
            std::bind( &TestCase::test_method<BOOST_PP_ENUM_PARAMS(arity,Arg)>,     \
            BOOST_PP_ENUM_PARAMS(arity, arg) ) ) );                                 \
    }                                                                               \

    BOOST_PP_REPEAT_FROM_TO(1, 4, TC_MAKE, _)

private:
    // Data members
    std::string                     m_tc_name;
    mutable std::list<test_unit*>   m_test_cases;
};

//____________________________________________________________________________//

template<typename TestCase,typename DS>
test_case_gen<TestCase,DS>
make_test_case_gen( const_string tc_name, DS&& ds )
{
    return test_case_gen<TestCase,DS>( tc_name, std::forward<DS>(ds) );
}

//____________________________________________________________________________//

} // namespace ds_detail

// ************************************************************************** //
// **************             BOOST_DATA_TEST_CASE             ************** //
// ************************************************************************** //

#define BOOST_DATA_TEST_CASE_PARAM(r, _, i, param)  (BOOST_PP_CAT(Arg, i) const& param)
#define BOOST_DATA_TEST_CONTEXT(r, _, param)  << BOOST_STRINGIZE(param) << " = " << param << "; "

#define BOOST_DATA_TEST_CASE_PARAMS( params )                           \
    BOOST_PP_SEQ_ENUM(                                                  \
        BOOST_PP_SEQ_FOR_EACH_I(BOOST_DATA_TEST_CASE_PARAM, _, params)) \
/**/

#define BOOST_DATA_TEST_CASE_IMPL( arity, test_name, dataset, params )  \
struct test_name                                                        \
{                                                                       \
    template<BOOST_PP_ENUM_PARAMS(arity, typename Arg)>                 \
    static void test_method( BOOST_DATA_TEST_CASE_PARAMS( params ) )    \
    {                                                                   \
        BOOST_TEST_CONTEXT( ""                                          \
            BOOST_PP_SEQ_FOR_EACH(BOOST_DATA_TEST_CONTEXT, _, params))  \
            _impl(BOOST_PP_SEQ_ENUM(params));                           \
    }                                                                   \
private:                                                                \
    template<BOOST_PP_ENUM_PARAMS(arity, typename Arg)>                 \
    static void _impl(BOOST_DATA_TEST_CASE_PARAMS( params ));           \
};                                                                      \
                                                                        \
BOOST_AUTO_TU_REGISTRAR( test_name )(                                   \
    boost::unit_test::data::ds_detail::make_test_case_gen<test_name>(   \
          BOOST_STRINGIZE( test_name ), data::make(dataset) ),          \
    boost::unit_test::decorator::collector::instance() );               \
                                                                        \
    template<BOOST_PP_ENUM_PARAMS(arity, typename Arg)>                 \
    void test_name::_impl( BOOST_DATA_TEST_CASE_PARAMS( params ) )      \
/**/

#define BOOST_DATA_TEST_CASE( test_name, dataset, ... )                 \
    BOOST_DATA_TEST_CASE_IMPL( BOOST_PP_VARIADIC_SIZE(__VA_ARGS__),     \
                               test_name, dataset,                      \
                               BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__) )  \
/**/

} // namespace data
} // namespace unit_test
} // namespace boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_DATA_TEST_CASE_HPP_102211GER

<|endoftext|>


<commit_before>#pragma once

#include <vector>
#include <string>

#include <lug/Graphics/Resource.hpp>
#include <lug/Graphics/Render/Mesh.hpp>

namespace lug {
namespace Graphics {

class Renderer;

namespace Builder {

class LUG_GRAPHICS_API Mesh {
public:
    class PrimitiveSet {
    public:
        PrimitiveSet() = default;

        PrimitiveSet(const PrimitiveSet&) = delete;
        PrimitiveSet(PrimitiveSet&&) = default;

        PrimitiveSet& operator=(const PrimitiveSet&) = delete;
        PrimitiveSet& operator=(PrimitiveSet&&) = delete;

        ~PrimitiveSet() = default;

        void setMode(Render::Mesh::PrimitiveSet::Mode mode);
        void setMaterial(Resource::SharedPtr<Render::Material> material);

        // TODO: Non raw mode

        // Raw mode
        void addAttributeBuffer(void* data, uint32_t size, Render::Mesh::PrimitiveSet::Attribute::Type type);

        Render::Mesh::PrimitiveSet::Mode getMode() const;
        Resource::SharedPtr<Render::Material> getMaterial() const;
        const std::vector<Render::Mesh::PrimitiveSet::Attribute>& getAttributes() const;

    private:
        Render::Mesh::PrimitiveSet::Mode _mode{Render::Mesh::PrimitiveSet::Mode::Triangles};
        Resource::SharedPtr<Render::Material> _material{nullptr};

        std::vector<Render::Mesh::PrimitiveSet::Attribute> _attributes;
    };

    friend class PrimitiveSet;

public:
    explicit Mesh(Renderer& renderer);

    Mesh(const Mesh&) = delete;
    Mesh(Mesh&&) = delete;

    Mesh& operator=(const Mesh&) = delete;
    Mesh& operator=(Mesh&&) = delete;

    virtual ~Mesh() = default;

    /**
     * @brief      Sets the name.
     * @param[in]  name  The name of the mesh.
     */
    void setName(const std::string& name);

    /**
     * @brief      Adds a primitive set to the builder and returns it.
     */
    PrimitiveSet* addPrimitiveSet();

    virtual Resource::SharedPtr<Render::Mesh> build() = 0;

protected:
    Renderer& _renderer;

    std::string _name;
    std::vector<PrimitiveSet> _primitiveSets;
};

#include <lug/Graphics/Builder/Mesh.inl>

} // Builder
} // Graphics
} // lug
<commit_msg>Replace primitive sets vector with list in Builder::Mesh<commit_after>#pragma once

#include <list>
#include <string>
#include <vector>

#include <lug/Graphics/Render/Mesh.hpp>
#include <lug/Graphics/Resource.hpp>

namespace lug {
namespace Graphics {

class Renderer;

namespace Builder {

class LUG_GRAPHICS_API Mesh {
public:
    class PrimitiveSet {
    public:
        PrimitiveSet() = default;

        PrimitiveSet(const PrimitiveSet&) = delete;
        PrimitiveSet(PrimitiveSet&&) = default;

        PrimitiveSet& operator=(const PrimitiveSet&) = delete;
        PrimitiveSet& operator=(PrimitiveSet&&) = delete;

        ~PrimitiveSet() = default;

        void setMode(Render::Mesh::PrimitiveSet::Mode mode);
        void setMaterial(Resource::SharedPtr<Render::Material> material);

        // TODO: Non raw mode

        // Raw mode
        void addAttributeBuffer(void* data, uint32_t size, Render::Mesh::PrimitiveSet::Attribute::Type type);

        Render::Mesh::PrimitiveSet::Mode getMode() const;
        Resource::SharedPtr<Render::Material> getMaterial() const;
        const std::vector<Render::Mesh::PrimitiveSet::Attribute>& getAttributes() const;

    private:
        Render::Mesh::PrimitiveSet::Mode _mode{Render::Mesh::PrimitiveSet::Mode::Triangles};
        Resource::SharedPtr<Render::Material> _material{nullptr};

        std::vector<Render::Mesh::PrimitiveSet::Attribute> _attributes;
    };

    friend class PrimitiveSet;

public:
    explicit Mesh(Renderer& renderer);

    Mesh(const Mesh&) = delete;
    Mesh(Mesh&&) = delete;

    Mesh& operator=(const Mesh&) = delete;
    Mesh& operator=(Mesh&&) = delete;

    virtual ~Mesh() = default;

    /**
     * @brief      Sets the name.
     * @param[in]  name  The name of the mesh.
     */
    void setName(const std::string& name);

    /**
     * @brief      Adds a primitive set to the builder and returns it.
     */
    PrimitiveSet* addPrimitiveSet();

    virtual Resource::SharedPtr<Render::Mesh> build() = 0;

protected:
    Renderer& _renderer;

    std::string _name;
    std::list<PrimitiveSet> _primitiveSets;
};

#include <lug/Graphics/Builder/Mesh.inl>

} // Builder
} // Graphics
} // lug
<|endoftext|>


<commit_before>/*-
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Copyright (c) 2020 NKI/AVL, Netherlands Cancer Institute
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdexcept>

#define BOOST_TEST_ALTERNATIVE_INIT_API
#include <boost/algorithm/string.hpp>
#include <boost/test/included/unit_test.hpp>

#include "DSSP.hpp"
#include "dssp_wrapper.hpp"

namespace ba = boost::algorithm;
namespace fs = std::filesystem;

// --------------------------------------------------------------------

cif::file operator""_cf(const char *text, size_t length)
{
	struct membuf : public std::streambuf
	{
		membuf(char *text, size_t length)
		{
			this->setg(text, text, text + length);
		}
	} buffer(const_cast<char *>(text), length);

	std::istream is(&buffer);
	return cif::file(is);
}

// --------------------------------------------------------------------

fs::path gTestDir = fs::current_path();

bool init_unit_test()
{
	cif::VERBOSE = 1;

	// not a test, just initialize test dir
	if (boost::unit_test::framework::master_test_suite().argc == 2)
	{
		gTestDir = boost::unit_test::framework::master_test_suite().argv[1];

		cif::add_data_directory(gTestDir / ".." / "rsrc");
	}

	// // do this now, avoids the need for installing
	// cif::add_file_resource("mmcif_pdbx.dic", gTestDir / ".." / "rsrc" / "mmcif_pdbx.dic");

	// // initialize CCD location
	// cif::add_file_resource("components.cif", gTestDir / ".." / "data" / "ccd-subset.cif");

	return true;
}

// --------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(ut_dssp)
{
	using namespace std::literals;

	cif::file f(gTestDir / "1cbs.cif.gz");
	BOOST_ASSERT(f.is_valid());

	dssp::DSSP dssp(f.front(), 1, 3, true);

	std::stringstream test;

	writeDSSP(dssp, test);

	std::ifstream reference(gTestDir / "1cbs.dssp");

	BOOST_CHECK(reference.is_open());

	std::string line_t, line_r;
	BOOST_CHECK(std::getline(test, line_t) and std::getline(reference, line_r));

	const char *kHeaderLineStart = "==== Secondary Structure Definition by the program DSSP, NKI version 4.0                           ====";
	BOOST_CHECK(line_t.compare(0, std::strlen(kHeaderLineStart), kHeaderLineStart) == 0);
	BOOST_CHECK(line_r.compare(0, std::strlen(kHeaderLineStart), kHeaderLineStart) == 0);

	for (int line_nr = 2;; ++line_nr)
	{
		bool done_t = not std::getline(test, line_t);
		bool done_r = not std::getline(reference, line_r);

		BOOST_CHECK_EQUAL(done_r, done_t);
		if (done_r)
			break;

		if (line_t != line_r)
			std::cerr << line_nr << std::endl
					  << line_t << std::endl
					  << line_r << std::endl;

		BOOST_CHECK(line_t == line_r);
	}

	BOOST_CHECK(test.eof());
	BOOST_CHECK(reference.eof());
}

BOOST_AUTO_TEST_CASE(ut_mmcif_2)
{
	using namespace std::literals;
	using namespace cif::literals;

	cif::file f(gTestDir / "1cbs.cif.gz");
	BOOST_ASSERT(f.is_valid());

	dssp::DSSP dssp(f.front(), 1, 3, true);

	std::stringstream test;

	annotateDSSP(f.front(), dssp, true, test);

	cif::file rf(gTestDir / "1cbs-dssp.cif");

	// structure.datablock()["software"].erase("name"_key == "dssp");
	// rs.datablock()["software"].erase("name"_key == "dssp");

	// generate some output on different files:
	cif::VERBOSE = 2;

	// BOOST_CHECK(f.front() == rf.front());
}

// --------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(dssp_1)
{
	cif::file f(gTestDir / "1cbs.cif");

	BOOST_ASSERT(f.is_valid());

	std::ifstream t(gTestDir / "1cbs-dssp-test.tsv");

	dssp::DSSP dssp(f.front(), 1, 3, true);

	for (auto residue : dssp)
	{
		std::string line;
		getline(t, line);

		std::cout << line << std::endl;

		auto f = cif::split(line, "\t");

		BOOST_CHECK_EQUAL(f.size(), 3);
		if (f.size() != 3)
			continue;

		int seqID;
		std::from_chars(f[0].begin(), f[0].end(), seqID);
		std::string asymID{ f[1] };
		std::string secstr{ f[2] };
		if (secstr == "_")
			secstr = " ";

		BOOST_CHECK_EQUAL(residue.asym_id(), asymID);
		BOOST_CHECK_EQUAL(residue.seq_id(), seqID);
		BOOST_CHECK_EQUAL((char)residue.type(), secstr.front());
	}
}<commit_msg>Fix unit-test<commit_after>/*-
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Copyright (c) 2020 NKI/AVL, Netherlands Cancer Institute
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdexcept>

#define BOOST_TEST_ALTERNATIVE_INIT_API
#include <boost/algorithm/string.hpp>
#include <boost/test/included/unit_test.hpp>

#include "DSSP.hpp"
#include "dssp_wrapper.hpp"

namespace ba = boost::algorithm;
namespace fs = std::filesystem;

// --------------------------------------------------------------------

cif::file operator""_cf(const char *text, size_t length)
{
	struct membuf : public std::streambuf
	{
		membuf(char *text, size_t length)
		{
			this->setg(text, text, text + length);
		}
	} buffer(const_cast<char *>(text), length);

	std::istream is(&buffer);
	return cif::file(is);
}

// --------------------------------------------------------------------

fs::path gTestDir = fs::current_path();

bool init_unit_test()
{
	cif::VERBOSE = 1;

	// not a test, just initialize test dir
	if (boost::unit_test::framework::master_test_suite().argc == 2)
	{
		gTestDir = boost::unit_test::framework::master_test_suite().argv[1];

		cif::add_data_directory(gTestDir / ".." / "rsrc");
	}

	// // do this now, avoids the need for installing
	// cif::add_file_resource("mmcif_pdbx.dic", gTestDir / ".." / "rsrc" / "mmcif_pdbx.dic");

	// // initialize CCD location
	// cif::add_file_resource("components.cif", gTestDir / ".." / "data" / "ccd-subset.cif");

	return true;
}

// --------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(ut_dssp)
{
	using namespace std::literals;

	cif::file f(gTestDir / "1cbs.cif.gz");
	BOOST_ASSERT(f.is_valid());

	dssp::DSSP dssp(f.front(), 1, 3, true);

	std::stringstream test;

	writeDSSP(dssp, test);

	std::ifstream reference(gTestDir / "1cbs.dssp");

	BOOST_CHECK(reference.is_open());

	std::string line_t, line_r;
	BOOST_CHECK(std::getline(test, line_t) and std::getline(reference, line_r));

	const char *kHeaderLineStart = "==== Secondary Structure Definition by the program DSSP, NKI version 4.0                           ====";
	BOOST_CHECK(line_t.compare(0, std::strlen(kHeaderLineStart), kHeaderLineStart) == 0);
	BOOST_CHECK(line_r.compare(0, std::strlen(kHeaderLineStart), kHeaderLineStart) == 0);

	for (int line_nr = 2;; ++line_nr)
	{
		bool done_t = not std::getline(test, line_t);
		bool done_r = not std::getline(reference, line_r);

		BOOST_CHECK_EQUAL(done_r, done_t);
		if (done_r)
			break;

		if (line_t != line_r)
			std::cerr << line_nr << std::endl
					  << line_t << std::endl
					  << line_r << std::endl;

		BOOST_CHECK(line_t == line_r);
	}

	BOOST_CHECK(test.eof());
	BOOST_CHECK(reference.eof());
}

BOOST_AUTO_TEST_CASE(ut_mmcif_2)
{
	using namespace std::literals;
	using namespace cif::literals;

	cif::file f(gTestDir / "1cbs.cif.gz");
	BOOST_ASSERT(f.is_valid());

	dssp::DSSP dssp(f.front(), 1, 3, true);

	std::stringstream test;

	annotateDSSP(f.front(), dssp, true, test);

	cif::file rf(gTestDir / "1cbs-dssp.cif");

	// structure.datablock()["software"].erase("name"_key == "dssp");
	// rs.datablock()["software"].erase("name"_key == "dssp");

	// generate some output on different files:
	cif::VERBOSE = 2;

	// BOOST_CHECK(f.front() == rf.front());
}

// --------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(dssp_1)
{
	cif::file f(gTestDir / "1cbs.cif.gz");

	BOOST_ASSERT(f.is_valid());

	std::ifstream t(gTestDir / "1cbs-dssp-test.tsv");

	dssp::DSSP dssp(f.front(), 1, 3, true);

	for (auto residue : dssp)
	{
		std::string line;
		getline(t, line);

		std::cout << line << std::endl;

		auto f = cif::split(line, "\t");

		BOOST_CHECK_EQUAL(f.size(), 3);
		if (f.size() != 3)
			continue;

		int seqID;
		std::from_chars(f[0].begin(), f[0].end(), seqID);
		std::string asymID{ f[1] };
		std::string secstr{ f[2] };
		if (secstr == "_")
			secstr = " ";

		BOOST_CHECK_EQUAL(residue.asym_id(), asymID);
		BOOST_CHECK_EQUAL(residue.seq_id(), seqID);
		BOOST_CHECK_EQUAL((char)residue.type(), secstr.front());
	}
}<|endoftext|>