Example #1
0
bool SakbotWrapper::run(QStringList* originals)
{
    m_originals = originals;

    // create an initial background estimation
    m_sakbot.initBackground( originals );

    // only run if there is at least one frame
    cv::Mat currentFrame = cv::imread(originals->at(0).toStdString());
    if(currentFrame.empty())
        return false;

    // only run if parameters have been chosen by the user
    if( !findShadowParams() )
        return false;

    // run for every frame
    for(int i = 0; i < originals->length(); i++)
    {
        currentFrame = cv::imread(originals->at(i).toStdString());
        if(currentFrame.empty())
            continue;
        m_sakbot.setImage(currentFrame);
        m_sakbot.findSegmentation();
        saveResult(originals->at(i));
    }
    return true;
}
void TestWindow::next()
{
    if (done < 5){
        ui->progressBar->setValue(ui->progressBar->value() + 1);
        int answer = 0;
        if (ui->radioButton->isChecked()) answer = 1;
        else if (ui->radioButton_2->isChecked()) answer = 2;
        else if (ui->radioButton_3->isChecked()) answer = 3;
        else if (ui->radioButton_4->isChecked()) answer = 4;
        done++;
        if (answer == true_ans){
            num_of_trues++;
            ui->textBrowser->append("Правильно!");
        }
        ui->textBrowser->append("");
        std::ifstream input;
        QString path=QApplication::applicationDirPath()+"/Test.txt";
        input.open(path.toLocal8Bit().data());
        showQuest(input, qts);
        qts++;
        input.close();
    }
    if (done == 5) {
        showResult();
        saveResult();
        ui->widget_3->hide();
    }
}
Example #3
0
MainWindow::MainWindow(QWidget* parent, int, char* const*) :
    QMainWindow(parent),
    d(new Private(this)) {
    createActions();
    createMenus();
    createToolBars();

    connect(d->saveAct, SIGNAL(triggered()), d->result, SLOT(saveResult()));
    setCentralWidget(d->result);
    d->result->setFocusPolicy(Qt::ClickFocus);

    QDockWidget* settingsDock = new QDockWidget(tr("Settings"), this);
    settingsDock->setAllowedAreas(Qt::LeftDockWidgetArea);
    settingsDock->setWidget(d->settings);
    addDockWidget(Qt::LeftDockWidgetArea, settingsDock);
    d->result->setFocus();
    d->setSettings();

    connect(d->settings,
        SIGNAL(settingsChanged(int, int, int, int, int, int)),
        this,
        SLOT(getSettings(int, int, int, int, int, int)));

    // connect (result, SIGNAL (etching()), this, SLOT (etch()));
    connect(d->etchMenu, SIGNAL(startEtching(int, int, float*)), this,
        SLOT(etch(int, int, float*)));
}
/*
 * Шукаємо вертикальні слова
 */
void tableTemplateWidget::scanVertical(void)
{
  int wordLength, countOfIntersection;
  int resrow = 0, rescol = 0, reswl = 0;
  QTableWidgetItem *cell = NULL;
  int value = -1;

  for (int i = 0; i < numCol; i++)
    {
      wordLength = countOfIntersection = 0;

      for (int j = 0; j < numRow; j++)
        {
          cell = item(j, i);
          value = cell->data(Qt::UserRole).toInt();

          if (value)
            {
              if (wordLength == 0)
                {
                  resrow = j;
                  rescol = i;
                }

              int intersection = typeOfIntersection(j, i);
              if (intersection)
                {
                  updateCell(cell, intersection);
                  countOfIntersection++;
                }

              wordLength++;
            }
          else
            {
              reswl = wordLength;
              wordLength = 0;
              saveResult(resrow, rescol, reswl, vertical, countOfIntersection);
              countOfIntersection = 0;
            }
        }

      reswl = wordLength;
      saveResult(resrow, rescol, reswl, vertical, countOfIntersection);
    }
}
Example #5
0
bool dem_simulation::run(float et, float dt, unsigned int step)
{
	unsigned int part = 0;
	unsigned int cStep = 0;
	unsigned int eachStep = 0;
	unsigned int nStep = static_cast<unsigned int>((et / dt) + 1);
	float ct = dt * cStep;
	std::cout
		<< "-------------------------------------------------------------" << std::endl
		<< "| Num. Part | Sim. Time | I. Part | I. Total | Elapsed Time |" << std::endl
		<< "-------------------------------------------------------------" << std::endl;
	std::ios::right;
	std::setprecision(6);
	if (saveResult(ct, part)){
		std::cout << "| " << std::setw(9) << part << std::setw(12) << ct << std::setw(10) << eachStep << std::setw(11) << cStep << std::setw(15) << 0 << std::endl;
	}
	cStep++;	
	boost::timer::auto_cpu_timer t;
	while (cStep < nStep)
	{
		ct = dt * cStep;
		itor->updatePosition(dt);
		gb->detection();
		collision_dem(dt);
		itor->updateVelocity(dt);
		if (!((cStep) % step)){
			part++;
			if (saveResult(ct, part)){
				std::cout << "| " << std::setw(9) << part << std::setw(12) << ct << std::setw(10) << eachStep << std::setw(11) << cStep << std::setw(15) << 0 << std::endl;
			}
			eachStep = 0;
		}
		cStep++;
		eachStep++;
	}
	return true;
}
/** Initializes this widget. */
void CModuleResultView::initView() {
    // see also csearchresultview.cpp
    setToolTip(tr("Works chosen for the search and the number of the hits in each work"));
    setHeaderLabels( QStringList(tr("Work")) << tr("Hits") );

    setColumnWidth(0, util::tool::mWidth(this, 8));
    setColumnWidth(1, util::tool::mWidth(this, 4));
    QSize sz(util::tool::mWidth(this, 13), util::tool::mWidth(this, 5));
    //setMinimumSize(sz);
    m_size = sz;
    /// \todo sorting
    //setSorting(0, true);
    //setSorting(1, true);

    //setup the popup menu
    m_popup = new QMenu(this);

    m_actions.copyMenu = new QMenu(tr("Copy..."), m_popup);
    m_actions.copyMenu->setIcon(CResMgr::searchdialog::result::moduleList::copyMenu::icon());
    m_actions.copy.result = new QAction(tr("Reference only"), this);
    BT_CONNECT(m_actions.copy.result, SIGNAL(triggered()),
               this,                  SLOT(copyResult()));
    m_actions.copyMenu->addAction(m_actions.copy.result);
    m_actions.copy.resultWithText = new QAction(tr("Reference with text"), this);
    BT_CONNECT(m_actions.copy.resultWithText, SIGNAL(triggered()),
               this,                           SLOT(copyResultWithText()));
    m_actions.copyMenu->addAction(m_actions.copy.resultWithText);
    m_popup->addMenu(m_actions.copyMenu);

    m_actions.saveMenu = new QMenu(tr("Save..."), m_popup);
    m_actions.saveMenu->setIcon(CResMgr::searchdialog::result::moduleList::saveMenu::icon());
    m_actions.save.result = new QAction(tr("Reference only"), this);
    BT_CONNECT(m_actions.save.result, SIGNAL(triggered()),
               this,                  SLOT(saveResult()));
    m_actions.saveMenu->addAction(m_actions.save.result);
    m_actions.save.resultWithText = new QAction(tr("Reference with text"), this);
    BT_CONNECT(m_actions.save.resultWithText, SIGNAL(triggered()),
               this,                          SLOT(saveResultWithText()));
    m_actions.saveMenu->addAction(m_actions.save.resultWithText);
    m_popup->addMenu(m_actions.saveMenu);

    m_actions.printMenu = new QMenu(tr("Print..."), m_popup);
    m_actions.printMenu->setIcon(CResMgr::searchdialog::result::moduleList::printMenu::icon());
    m_actions.print.result = new QAction(tr("Reference with text"), this);
    BT_CONNECT(m_actions.print.result, SIGNAL(triggered()),
               this,                   SLOT(printResult()));
    m_actions.printMenu->addAction(m_actions.print.result);
    m_popup->addMenu(m_actions.printMenu);
}
int FrameCapture::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: finished(); break;
        case 1: printProgress((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 2: saveResult((*reinterpret_cast< bool(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 3;
    }
    return _id;
}
Example #8
0
App::App(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);

	centralWidget = new QWidget;
	centralLayout = new QVBoxLayout;

	contentWidget = new QWidget;
	contentLayout = new QGridLayout;

	elapsedTimeLabel = new QLabel("Elapsed time: 0 s");
	elapsedTimeLabel->setFixedSize(300, 15);

	sourceLabel = new QLabel;
	sourceLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	sourceLabel->setScaledContents(true);
	contentLayout->addWidget(sourceLabel, 0, 0);

	maskLabel = new QLabel;
	maskLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	maskLabel->setScaledContents(true);
	contentLayout->addWidget(maskLabel, 0, 1);

	v_disparityLabel = new QLabel;
	v_disparityLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	v_disparityLabel->setScaledContents(true);
	contentLayout->addWidget(v_disparityLabel, 0, 2);

	v_disparity_N_Label = new QLabel;
	v_disparity_N_Label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	v_disparity_N_Label->setScaledContents(true);
	contentLayout->addWidget(v_disparity_N_Label, 2, 2);

	u_disparityLabel = new QLabel;
	u_disparityLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	u_disparityLabel->setScaledContents(true);
	contentLayout->addWidget(u_disparityLabel, 2, 1);

	resultLabel = new QLabel;
	resultLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	resultLabel->setScaledContents(true);
	contentLayout->addWidget(resultLabel, 2, 0);

	contentWidget->setLayout(contentLayout);

	centralLayout->addWidget(elapsedTimeLabel);
	centralLayout->addWidget(contentWidget);
	centralWidget->setLayout(centralLayout);

	setCentralWidget(centralWidget);

	connect(ui.action_Load_default, SIGNAL(triggered()), this, SLOT(loadDefault()));
	connect(ui.action_Load_source, SIGNAL(triggered()), this, SLOT(loadSource()));
	connect(ui.action_Load_mask, SIGNAL(triggered()), this, SLOT(loadMask()));
	connect(ui.action_Remove_mask, SIGNAL(triggered()), this, SLOT(removeMask()));
	connect(ui.action_Save, SIGNAL(triggered()), this, SLOT(saveResult()));
	connect(ui.actionV_Disparity, SIGNAL(triggered()), this, SLOT(v_disparityCall()));
	connect(ui.actionU_Disparity, SIGNAL(triggered()), this, SLOT(u_disparityCall()));
	connect(ui.actionHoughLineV_Disp, SIGNAL(triggered()), this, SLOT(houghLinesV_DispCall()));
	connect(ui.actionPHoughLineV_Disp, SIGNAL(triggered()), this, SLOT(probabilisticHoughLinesV_DispCall()));
	connect(ui.actionCudaHoughLineV_Disp, SIGNAL(triggered()), this, SLOT(cudaHoughLinesV_DispCall()));
	connect(ui.actionCudaPHoughLineV_Disp, SIGNAL(triggered()), this, SLOT(cudaProbabilisticHoughLinesV_DispCall()));
}
Example #9
0
/*  Moving */
int go(int x, int y, int nodes)
{
    int i;
    if(x==END_X && y==END_Y)
    {
        maze[y][x] = 'E';  /* Mark the arriving */
        saveResult(maze, nodes);
        return 1;  /* Arrive */
    }

    int next[8] = {0};
    /* 0.right, 1.top-right, 2.top, 3.top-left, 4.left, 5.bottom-left, 6.bottom, 7.bottom-right; */
    /* scan */
    /* 0 */
    if(x!=MAP_WIDTH-1 && maze[y][x+1]=='1' && maze[y][x]=='1')
    {
        next[0] = 1;
    }
    /* 1 */
    if(x!=MAP_WIDTH-1 && y!=0)
    {
        if(maze[y][x]=='1' && maze[y-1][x+1]=='2')
            next[1] = 1;
        else if(maze[y][x]=='2' && maze[y-1][x+1]<'4' && maze[y-1][x+1]>'0')
            next[1] = 1;
    }
    /* 2 */
    if(y!=0 && maze[y-1][x]=='1' && maze[y][x]=='1')
    {
        next[2] = 1;
    }
    /* 3 */
    if(x!=0 && y!=0)
    {
        if(maze[y][x]=='1' && maze[y-1][x-1]=='3')
            next[3] = 1;
        else if(maze[y][x]=='3' && maze[y-1][x-1]<'4' && maze[y-1][x-1]>'0')
            next[3] = 1;
    }
    /* 4 */
    if(x!=0 && maze[y][x-1]=='1' && maze[y][x]=='1')
    {
        next[4] = 1;
    }
    /* 5 */
    if(x!=0 && y!=MAP_HEIGHT-1)
    {
        if(maze[y][x]=='1' && maze[y+1][x-1]=='2')
            next[5] = 1;
        else if(maze[y][x]=='2' && maze[y+1][x-1]<'4' && maze[y+1][x-1]>'0')
            next[5] = 1;
    }
    /* 6 */
    if(y!=MAP_HEIGHT-1 && maze[y+1][x]=='1' && maze[y][x]=='1')
    {
        next[6] = 1;
    }
    /* 7 */
    if(x!=MAP_WIDTH-1 && y!=MAP_HEIGHT-1)
    {
        if(maze[y][x]=='1'&& maze[y+1][x+1]=='3')
            next[7] = 1;
        else if(maze[y][x]=='3' && maze[y+1][x+1]<'4' && maze[y+1][x+1]>'0')
            next[7] = 1;
    }

    /* Make marks on the route */
    if(maze[y][x]!='0')
        maze[y][x] += 3;  /* 3 is only a magic number */
    else
        return -1;  /* Error: tring to walk on walls */

    int posibleWays = 0;
    for(i=0; i<8; i++)
        if(next[i]==1)
            posibleWays++;
    if(posibleWays==1)
    {
        for(i=0; next[i]!=1; i++);
        nextStep(i, x, y, nodes);
    }
    else if(posibleWays>1 && posibleWays<8)
    {
        nodes++;
        for(i=0; i<8; i++)
        {
            if(next[i]==1)
            {
                push(maze, x, y, nodes);
                nextStep(i, x, y, nodes);
                pop(maze, &x, &y, &nodes);
            }
        }
    }
    else
        return -2;  /* Error: no way to go */
}
////////////////////////////////////////////////////////////////////////////////
//! Run a simple test for CUDA
////////////////////////////////////////////////////////////////////////////////
void
runTest( int argc, char** argv)
{
	ocd_options opts = ocd_get_options();
	platform_id = opts.platform_id;
	n_device = opts.device_id;

	if ( argc != 8)
	{
		printf("Usage: GpuTemporalDataMining [<platform> <device> --] <file path> <temporal constraint path> <threads> <support> <(a)bsolute or (r)atio> <(s)tatic | (d)ynamic> <(m)ap and merge | (n)aive | (o)hybrid> \n");
		return;
	}

//    CUT_DEVICE_INIT();
    initGpu();

    getDeviceVariables(device_id);


	printf("Dataset, Support Threshold, PTPE or MapMerge, A1 or A1+A2, Level, Episodes (N), Episodes Culled (X), A1 Counting Time, A2 Counting Time, Generation Time, Total Counting Time\n");

    //CUT_SAFE_CALL( cutCreateTimer( &timer));
    //CUT_SAFE_CALL( cutCreateTimer( &generating_timer));
    //CUT_SAFE_CALL( cutCreateTimer( &a1_counting_timer));
    //CUT_SAFE_CALL( cutCreateTimer( &a2_counting_timer));
    //CUT_SAFE_CALL( cutCreateTimer( &total_timer));

    //CUT_SAFE_CALL( cutStartTimer( total_timer));
    //CUT_SAFE_CALL( cutStartTimer( timer));
    //CUT_SAFE_CALL( cutStartTimer( generating_timer));
    //CUT_SAFE_CALL( cutStartTimer( a1_counting_timer));
    //CUT_SAFE_CALL( cutStartTimer( a2_counting_timer));

    unsigned int num_threads = atoi(argv[3]);
    // allocate host memory
    //initEpisodeCandidates();
	if ( loadData( argv[1] ) != 0 )
		return;
	if ( loadTemporalConstraints(argv[2]) != 0 )
		return;

	// Check whether value supplied is absolute or ratio support
	supportType = *(argv[5]) == 'a' ? ABSOLUTE : RATIO;
	memoryModel = *(argv[6]) == 's' ? STATIC : DYNAMIC;

	switch (*(argv[7]))
	{
	case 'm':
		algorithmType = MAP_AND_MERGE;
		break;
	case 'n':
		algorithmType = NAIVE;
		break;
	case 'o':
		algorithmType = OPTIMAL;
		break;
	}

	support = atof(argv[4]);

	dumpFile = fopen( "episode.txt", "w" );

	//printf("Initializing GPU Data...\n");

	setupGpu();

	// setup execution parameters
    size_t grid[3];
    size_t threads[3];

	//printf("Event stream size: %i\n", eventSize);

	// BEGIN LOOP
	for ( int level = 1; level <= eventSize; level++ )
	{
		printf("Generating episode candidates for level %i...\n", level);
//		CUT_SAFE_CALL( cutResetTimer( total_timer));
//		CUT_SAFE_CALL( cutStartTimer( total_timer));

		//CUDA_SAFE_CALL( cudaUnbindTexture( candidateTex ) );
		if(level != 1){
			unbindTexture(&candidateTex, d_episodeCandidates, numCandidates * (level-1) * sizeof(UBYTE) );
		//CUDA_SAFE_CALL( cudaUnbindTexture( intervalTex ) );
		unbindTexture(&intervalTex, d_episodeIntervals, numCandidates * (level-2) * 2 * sizeof(float));
        }

//		CUT_SAFE_CALL( cutResetTimer( generating_timer));
//		CUT_SAFE_CALL( cutStartTimer( generating_timer));

//		int test1, test = numCandidates;
//		generateEpisodeCandidatesCPU( level );
//		test1 = numCandidates;
//		numCandidates = test;
        printf("Generating Episodes\n");
#ifdef CPU_EPISODE_GENERATION
		generateEpisodeCandidatesCPU( level );
#else
		generateEpisodeCandidatesGPU( level, num_threads );
#endif

//		CUT_SAFE_CALL( cutStopTimer( generating_timer));
		//printf( "\tGenerating time: %f (ms)\n", cutGetTimerValue( generating_timer));


		if ( numCandidates == 0 )
			break;
        printf("Writing to buffer\n");
		// Copy candidates to GPU
#ifdef CPU_EPISODE_GENERATION
		clEnqueueWriteBuffer(commands, d_episodeCandidates, CL_TRUE, 0, numCandidates * level * sizeof(UBYTE), h_episodeCandidates, 0, NULL, &ocdTempEvent);
                START_TIMER(ocdTempEvent, OCD_TIMER_H2D, "TDM Episode Copy", ocdTempTimer)
                END_TIMER(ocdTempTimer)
		clEnqueueWriteBuffer(commands, d_episodeIntervals, CL_TRUE, 0, numCandidates * (level-1) * 2 * sizeof(float), h_episodeIntervals, 0, NULL, &ocdTempEvent);
                clFinish(commands);
		START_TIMER(ocdTempEvent, OCD_TIMER_H2D, "TDM Episode Copy", ocdTempTimer)
                END_TIMER(ocdTempTimer)
#endif

        bindTexture( 0, &candidateTex, d_episodeCandidates, numCandidates * level * sizeof(UBYTE), CL_UNSIGNED_INT8);

		bindTexture( 0, &intervalTex, d_episodeIntervals, numCandidates * (level-1) * 2 * sizeof(float), CL_FLOAT );

		//printf("Executing kernel on %i candidates...\n", numCandidates, level);

		// execute the kernel
		calculateGrid(grid, num_threads, numCandidates);
		calculateBlock(threads, num_threads, numCandidates);

		int sections;
		unsigned int shared_mem_needed;
		//CUT_SAFE_CALL( cutStartTimer( counting_timer));

		int aType = algorithmType;
		if ( algorithmType == OPTIMAL )
			aType = chooseAlgorithmType( level, numCandidates, num_threads );

		if ( memoryModel == DYNAMIC )
		{
			if ( aType == NAIVE )
			{
				shared_mem_needed = MaxListSize*level*threads[0]*sizeof(float);
                printf("Shared memory needed %d\n", shared_mem_needed);
				//CUT_SAFE_CALL( cutResetTimer( a1_counting_timer));
				//CUT_SAFE_CALL( cutStartTimer( a1_counting_timer));
				countCandidates(grid, threads, d_episodeSupport, eventSize, level, supportType, numCandidates, candidateTex, intervalTex, eventTex, timeTex, shared_mem_needed );

			}
			else
			{
                printf("DYNAMIC MAP MERGE\n");
				calculateLevelParameters(level, threads, grid, sections);
				shared_mem_needed = 16000;
                printf("numCandidates=%d\n", numCandidates);
				//CUT_SAFE_CALL( cutResetTimer( a1_counting_timer));
				//CUT_SAFE_CALL( cutStartTimer( a1_counting_timer));
				countCandidatesMapMerge(grid, threads, d_episodeSupport, padEventSize, level, supportType, sections, padEventSize / sections, numCandidates,
                    candidateTex, intervalTex, eventTex, timeTex, shared_mem_needed );
				//countCandidatesMapMergeStatic<<< grid, threads, shared_mem_needed >>>( d_episodeSupport, padEventSize, level, supportType, sections, padEventSize / sections, numCandidates );
			}
		}
		else
		{
			if ( aType == NAIVE )
			{
				shared_mem_needed = level*threads[0]*sizeof(float);
			}
			else
			{
				calculateLevelParameters(level, threads, grid, sections);
				shared_mem_needed = 16000;
			}

				//CUT_SAFE_CALL( cutResetTimer( a2_counting_timer));
				//CUT_SAFE_CALL( cutStartTimer( a2_counting_timer));
			if ( aType == NAIVE )
                countCandidatesStatic(grid, threads, d_episodeSupport, eventSize, level, supportType, numCandidates, candidateTex, intervalTex, eventTex, timeTex, shared_mem_needed  );
			else
                countCandidatesMapMergeStatic(grid, threads, d_episodeSupport, padEventSize, level, supportType, sections, padEventSize / sections, numCandidates,
                    candidateTex, intervalTex, eventTex, timeTex, shared_mem_needed );
			clFinish(commands);

			//CUT_SAFE_CALL( cutStopTimer( a2_counting_timer));

            int err;
            err = clEnqueueReadBuffer(commands,d_episodeSupport, CL_TRUE, 0, numCandidates * sizeof(float), h_episodeSupport, 0, NULL, &ocdTempEvent);
            clFinish(commands);
            	START_TIMER(ocdTempEvent, OCD_TIMER_D2H, "TDM Episode Copy", ocdTempTimer)
            END_TIMER(ocdTempTimer)
		CHKERR(err, "Unable to read buffer from device.");

			unbindTexture(&candidateTex, d_episodeCandidates, numCandidates * level * sizeof(UBYTE) );
			unbindTexture(&intervalTex, d_episodeIntervals, numCandidates * (level-1) * 2 * sizeof(float));

			// Remove undersupported episodes
			cullCandidates( level );

			if ( numCandidates == 0 )
				break;
			unsigned int mmthreads = num_threads;
			if ( MaxListSize*level*num_threads*sizeof(float) > 16384 )
			{
				if ( MaxListSize*level*96*sizeof(float) < 16384 )
					mmthreads = 96;
				else if ( MaxListSize*level*64*sizeof(float) < 16384)
					mmthreads = 64;
				else if ( MaxListSize*level*32*sizeof(float) < 16384)
					mmthreads = 32;
				printf("More shared memory needed for %d threads. Changed to %d threads.\n", num_threads, mmthreads );
			}

#ifdef CPU_EPISODE_GENERATION
            err = clEnqueueWriteBuffer(commands, d_episodeCandidates, CL_TRUE, 0, numCandidates * level * sizeof(UBYTE), h_episodeCandidates, 0, NULL, &ocdTempEvent);
	START_TIMER(ocdTempEvent, OCD_TIMER_H2D, "TDM Episode Copy", ocdTempTimer)
            END_TIMER(ocdTempTimer)
            CHKERR(err, "Unable to write buffer 1.");
            if(numCandidates * (level - 1) * 2 * sizeof(float) != 0)
            err = clEnqueueWriteBuffer(commands, d_episodeIntervals, CL_TRUE, 0, numCandidates * (level-1) * 2 * sizeof(float), h_episodeIntervals, 0, NULL, &ocdTempEvent);
        clFinish(commands);
            START_TIMER(ocdTempEvent, OCD_TIMER_H2D, "TDM Episode Copy", ocdTempTimer)
        CHKERR(err, "Unable to write buffer 2.");
		END_TIMER(ocdTempTimer)
#endif
            bindTexture( 0, &candidateTex, d_episodeCandidates, numCandidates * level * sizeof(UBYTE), CL_UNSIGNED_INT8);
            bindTexture( 0, &intervalTex, d_episodeIntervals, numCandidates * (level-1) * 2 * sizeof(float), CL_FLOAT );

			if ( algorithmType == OPTIMAL )
				aType = chooseAlgorithmType( level, numCandidates, mmthreads );

			// Run (T1,T2] algorithm
			if ( aType == NAIVE )
			{
				shared_mem_needed = MaxListSize*level* mmthreads*sizeof(float);
				calculateGrid(grid, mmthreads, numCandidates );
				calculateBlock(threads, mmthreads, numCandidates );
			}
			else
			{
				calculateLevelParameters(level, threads, grid, sections);
				shared_mem_needed = 16000;
			}
			//CUT_SAFE_CALL( cutResetTimer( a1_counting_timer));
			//CUT_SAFE_CALL( cutStartTimer( a1_counting_timer));

			if ( aType == NAIVE )
                countCandidates(grid, threads, d_episodeSupport, eventSize, level, supportType, numCandidates,
                    candidateTex, intervalTex, eventTex, timeTex, shared_mem_needed );
			else
                countCandidatesMapMerge(grid, threads, d_episodeSupport, padEventSize, level, supportType, sections, padEventSize / sections, numCandidates,
                    candidateTex, intervalTex, eventTex, timeTex, shared_mem_needed );

		}
        printf("Finishing\n");
		clFinish(commands);
		//CUT_SAFE_CALL( cutStopTimer( a1_counting_timer));
		//printf( "\tCounting time: %f (ms)\n", cutGetTimerValue( counting_timer));

		// check if kernel execution generated an error
		//CUT_CHECK_ERROR("Kernel execution failed");

		//printf("Copying result back to host...\n\n");

        int err = clEnqueueReadBuffer(commands, d_episodeSupport, CL_TRUE, 0, numCandidates * sizeof(float), h_episodeSupport, 0, NULL, &ocdTempEvent);
        clFinish(commands);
		START_TIMER(ocdTempEvent, OCD_TIMER_D2H, "TDM Episode Copy", ocdTempTimer)
        END_TIMER(ocdTempTimer)
		CHKERR(err, "Unable to read memory 1.");
		err = clEnqueueReadBuffer(commands, d_episodeCandidates, CL_TRUE, 0, numCandidates * level * sizeof(UBYTE), h_episodeCandidates, 0, NULL, &ocdTempEvent);
                clFinish(commands);
                START_TIMER(ocdTempEvent, OCD_TIMER_D2H, "TDM Episode Copy", ocdTempTimer)
                END_TIMER(ocdTempTimer)
		CHKERR(err, "Unable to read memory 2.");
		//CUDA_SAFE_CALL( cudaMemcpy( h_mapRecords, d_mapRecords, 3 * numSections * maxLevel * maxCandidates * sizeof(float), cudaMemcpyDeviceToHost ));
		saveResult(level);
		fflush(dumpFile);
	// END LOOP

		//CUT_SAFE_CALL( cutStopTimer( total_timer));

		// Print Statistics for this run
		printf("%s, %f, %s, %s, %d, %d, %d\n",
			argv[1],											// Dataset
			support,											// Support Threshold
			algorithmType == NAIVE ? "PTPE" : algorithmType == MAP_AND_MERGE ? "MapMerge" : "Episode-Based",		// PTPE or MapMerge or Episode-Based
			memoryModel == STATIC ? "A1+A2" : "A1",				// A1 or A1+A2
			level,												// Level
			numCandidates+episodesCulled,						// Episodes counted
			episodesCulled  									// Episodes removed by A2
	//		cutGetTimerValue( a1_counting_timer),				// Time for A1
//			memoryModel == STATIC ? cutGetTimerValue( a2_counting_timer) : 0.0f,				// Time for A2
		//	cutGetTimerValue( generating_timer),				// Episode generation time
		//	cutGetTimerValue( total_timer) );					// Time for total loop
            );
	}
	printf("Done!\n");

    cleanup();

    //CUT_SAFE_CALL( cutStopTimer( timer));
    //printf( "Processing time: %f (ms)\n", cutGetTimerValue( timer));
    //CUT_SAFE_CALL( cutDeleteTimer( timer));
    //CUT_SAFE_CALL( cutDeleteTimer( generating_timer));
    //CUT_SAFE_CALL( cutDeleteTimer( a1_counting_timer));
    //CUT_SAFE_CALL( cutDeleteTimer( a2_counting_timer));
    //CUT_SAFE_CALL( cutDeleteTimer( total_timer));

}
    std::pair<int, size_t> dp(const int k, const size_t kidx, const std::vector<int>& a, const size_t ai, const std::vector<int>& b, const size_t bi) {
        std::ostringstream ostr;
        ostr << k << ":" << kidx << ":" << ai << ":" << bi << ":";
        if (dpMap.find(ostr.str()) != dpMap.end()) {
            return dpMap[ostr.str()];
        }

        if (ai >= a.size()) {
            saveResult(ostr.str(), std::make_pair(1, getNextIndex(false, k, kidx, b, bi, a.size(), ai)));
            return dpMap[ostr.str()];
        }
        
        if (bi >= b.size()) {
            saveResult(ostr.str(), std::make_pair(0, getNextIndex(true, k, kidx, a, ai, b.size(), bi)));
            return dpMap[ostr.str()];
        }
        
        if (ai >=a.size() && bi >=a.size()) {
            assert(0 == "should not reach here");
        }
        
        const size_t naidx = getNextIndex(true, k, kidx, a, ai, b.size(), bi);
        const size_t nbidx = getNextIndex(false, k, kidx, b, bi, a.size(), ai);
        
        if (a[naidx] > b[nbidx]) {
            saveResult(ostr.str(), std::make_pair(0, naidx));
            return dpMap[ostr.str()];
        } else if (a[naidx] < b[nbidx]) {
            saveResult(ostr.str(),std::make_pair(1, nbidx));
            return dpMap[ostr.str()];
        } else if (kidx == k-1) {
            saveResult(ostr.str(),std::make_pair(0, naidx));
            return dpMap[ostr.str()];
        } else {
            std::vector<std::vector<int> const*> nums;
            nums.reserve(2);
            nums.push_back(&a);
            nums.push_back(&b);
            std::pair<int, size_t> adp;
            std::pair<int, size_t> bdp;
            
            size_t tnaidx = naidx+1;
            size_t tnbidx = nbidx+1;
            size_t depth = 1;
            do {
                adp = dp(k, kidx+depth, a, tnaidx, b, bi);
                bdp = dp(k, kidx+depth, a, ai, b, tnbidx);
                ++tnaidx;
                ++tnbidx;
                ++depth;
            } while ((*nums[adp.first])[adp.second] == (*nums[bdp.first])[bdp.second] &&
                     nums[adp.first]->size()-1 <= adp.second &&
                     nums[bdp.first]->size()-1 <= bdp.second &&
                     depth < k-kidx);
            if ((*nums[adp.first])[adp.second] > (*nums[bdp.first])[bdp.second]) {
                saveResult(ostr.str(),std::make_pair(0, naidx));
                return dpMap[ostr.str()];
            } else if ((*nums[adp.first])[adp.second] < (*nums[bdp.first])[bdp.second]) {
                saveResult(ostr.str(),std::make_pair(1, nbidx));
                return dpMap[ostr.str()];
            } else if (nums[adp.first]->size()-1 > adp.second) {
                saveResult(ostr.str(), std::make_pair(0, naidx));
                return dpMap[ostr.str()];
            } else if (nums[bdp.first]->size()-1 > bdp.second) {
                saveResult(ostr.str(),std::make_pair(1, nbidx));
                return dpMap[ostr.str()];
            }
        }
        assert(0 == "Should never reach here");
    }