void QSGDefaultRenderer::render()
{
#if defined (QML_RUNTIME_TESTING)
    static bool dumpTree = qApp->arguments().contains(QLatin1String("--dump-tree"));
    if (dumpTree) {
        printf("\n\n");
        QSGNodeDumper::dump(rootNode());
    }
#endif

#ifdef RENDERER_DEBUG
    debugTimer.invalidate();
    debugTimer.start();
    geometryNodesDrawn = 0;
    materialChanges = 0;
#endif

    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_BLEND);

    glFrontFace(isMirrored() ? GL_CW : GL_CCW);
    glDisable(GL_CULL_FACE);

    glEnable(GL_DEPTH_TEST);
    glDepthMask(true);
    glDepthFunc(GL_GREATER);
#if defined(QT_OPENGL_ES)
    glClearDepthf(0);
#else
    glClearDepth(0);
#endif

    glDisable(GL_SCISSOR_TEST);
    glClearColor(m_clear_color.redF(), m_clear_color.greenF(), m_clear_color.blueF(), m_clear_color.alphaF());

#ifdef RENDERER_DEBUG
    int debugtimeSetup = debugTimer.elapsed();
#endif

    bindable()->clear(clearMode());

#ifdef RENDERER_DEBUG
    int debugtimeClear = debugTimer.elapsed();
#endif

    QRect r = viewportRect();
    glViewport(r.x(), deviceRect().bottom() - r.bottom(), r.width(), r.height());
    m_current_projection_matrix = projectionMatrix();
    m_current_model_view_matrix.setToIdentity();

    m_currentClip = 0;
    glDisable(GL_STENCIL_TEST);

    m_currentMaterial = 0;
    m_currentProgram = 0;
    m_currentMatrix = 0;

    if (m_rebuild_lists) {
        m_opaqueNodes.reset();
        m_transparentNodes.reset();
        m_currentRenderOrder = 1;
        buildLists(rootNode());
        m_rebuild_lists = false;
    }

#ifdef RENDERER_DEBUG
    int debugtimeLists = debugTimer.elapsed();
#endif


    if (m_needs_sorting) {
        if (!m_opaqueNodes.isEmpty()) {
            qSort(&m_opaqueNodes.first(), &m_opaqueNodes.first() + m_opaqueNodes.size(),
                  m_sort_front_to_back
                  ? nodeLessThanWithRenderOrder
                  : nodeLessThan);
        }
        m_needs_sorting = false;
    }

#ifdef RENDERER_DEBUG
    int debugtimeSorting = debugTimer.elapsed();
#endif

    m_renderOrderMatrix.setToIdentity();
    m_renderOrderMatrix.scale(1, 1, qreal(1) / m_currentRenderOrder);

    glDisable(GL_BLEND);
    glDepthMask(true);
#ifdef QML_RUNTIME_TESTING
    if (m_render_opaque_nodes)
#endif
    {
#if defined (QML_RUNTIME_TESTING)
        if (dumpTree)
            qDebug() << "Opaque Nodes:";
#endif
        renderNodes(m_opaqueNodes);
    }

#ifdef RENDERER_DEBUG
    int debugtimeOpaque = debugTimer.elapsed();
    int opaqueNodes = geometryNodesDrawn;
    int opaqueMaterialChanges = materialChanges;
#endif

    glEnable(GL_BLEND);
    glDepthMask(false);
#ifdef QML_RUNTIME_TESTING
    if (m_render_alpha_nodes)
#endif
    {
#if defined (QML_RUNTIME_TESTING)
        if (dumpTree)
            qDebug() << "Alpha Nodes:";
#endif
        renderNodes(m_transparentNodes);
    }

#ifdef RENDERER_DEBUG
    int debugtimeAlpha = debugTimer.elapsed();
#endif


    if (m_currentProgram)
        m_currentProgram->deactivate();

#ifdef RENDERER_DEBUG
    if (debugTimer.elapsed() > DEBUG_THRESHOLD) {
        printf(" --- Renderer breakdown:\n"
               "     - setup=%d, clear=%d, building=%d, sorting=%d, opaque=%d, alpha=%d\n"
               "     - material changes: opaque=%d, alpha=%d, total=%d\n"
               "     - geometry ndoes: opaque=%d, alpha=%d, total=%d\n",
               debugtimeSetup,
               debugtimeClear - debugtimeSetup,
               debugtimeLists - debugtimeClear,
               debugtimeSorting - debugtimeLists,
               debugtimeOpaque - debugtimeSorting,
               debugtimeAlpha - debugtimeOpaque,
               opaqueMaterialChanges, materialChanges - opaqueMaterialChanges, materialChanges,
               opaqueNodes, geometryNodesDrawn - opaqueNodes, geometryNodesDrawn);
    }
#endif

}
Esempio n. 2
0
void EmuThread::run()
{
	running = true;
	setCurrentThreadName("EmuThread");

	host->UpdateUI();
	host->InitGL();

	glWindow->makeCurrent();

#ifndef USING_GLES2
	glewInit();
#endif
	NativeInitGraphics();

	INFO_LOG(BOOT, "Starting up hardware.");

	QElapsedTimer timer;

	while(running) {
		//UpdateGamepad(*input_state);
		timer.start();

		gameMutex.lock();
		bool gRun = gameRunning;
		gameMutex.unlock();

		if(gRun)
		{
			gameMutex.lock();

			glWindow->makeCurrent();
			if(needInitGame)
			{
				g_State.bEmuThreadStarted = true;

				CoreParameter coreParameter;
				coreParameter.fileToStart = fileToStart.toStdString();
				coreParameter.enableSound = true;
				coreParameter.gpuCore = GPU_GLES;
				coreParameter.cpuCore = (CPUCore)g_Config.iCpuCore;
				coreParameter.enableDebugging = true;
				coreParameter.printfEmuLog = false;
				coreParameter.headLess = false;
				coreParameter.renderWidth = 480 * g_Config.iWindowZoom;
				coreParameter.renderHeight = 272 * g_Config.iWindowZoom;
				coreParameter.outputWidth = dp_xres;
				coreParameter.outputHeight = dp_yres;
				coreParameter.pixelWidth = pixel_xres;
				coreParameter.pixelHeight = pixel_yres;
				coreParameter.startPaused = !g_Config.bAutoRun;

				std::string error_string;
				if (!PSP_Init(coreParameter, &error_string))
				{
					ERROR_LOG(BOOT, "Error loading: %s", error_string.c_str());
					FinalShutdown();
					return;
				}

				LayoutGamepad(dp_xres, dp_yres);

				_dbg_update_();

				host->UpdateDisassembly();
				Core_EnableStepping(coreParameter.startPaused ? TRUE : FALSE);

				g_State.bBooted = true;
			#ifdef _DEBUG
				host->UpdateMemView();
			#endif
				host->BootDone();
				needInitGame = false;
			}
			UpdateInputState(input_state);

			for (int i = 0; i < controllistCount; i++) {
				if (input_state->pad_buttons_down & controllist[i].emu_id) {
					__CtrlButtonDown(controllist[i].psp_id);
				}
				if (input_state->pad_buttons_up & controllist[i].emu_id) {
					__CtrlButtonUp(controllist[i].psp_id);
				}
			}
			__CtrlSetAnalog(input_state->pad_lstick_x, input_state->pad_lstick_y);

			EndInputState(input_state);

			glstate.Restore();
			glViewport(0, 0, pixel_xres, pixel_yres);
			Matrix4x4 ortho;
			ortho.setOrtho(0.0f, dp_xres, dp_yres, 0.0f, -1.0f, 1.0f);
			glsl_bind(UIShader_Get());
			glUniformMatrix4fv(UIShader_Get()->u_worldviewproj, 1, GL_FALSE, ortho.getReadPtr());


			ReapplyGfxState();

			Core_Run();

			// Hopefully coreState is now CORE_NEXTFRAME
			if (coreState == CORE_NEXTFRAME) {
				// set back to running for the next frame
				coreState = CORE_RUNNING;

				qint64 time = timer.elapsed();
				const int frameTime = (1.0f/60.0f) * 1000;
				gameMutex.unlock();
				if(time < frameTime)
				{
					glWindow->doneCurrent();
					msleep(frameTime-time);
					glWindow->makeCurrent();
				}
				gameMutex.lock();
				timer.start();
			}

			fbo_unbind();

			UIShader_Prepare();

			uiTexture->Bind(0);

			glViewport(0, 0, pixel_xres, pixel_yres);

			ui_draw2d.Begin(DBMODE_NORMAL);

			//if (g_Config.bShowTouchControls)
			//	DrawGamepad(ui_draw2d);

			glsl_bind(UIShader_Get());
			ui_draw2d.End();
			ui_draw2d.Flush(UIShader_Get());


			// Tiled renderers like PowerVR should benefit greatly from this. However - seems I can't call it?
#if defined(USING_GLES2)
			bool hasDiscard = false;  // TODO
			if (hasDiscard) {
				//glDiscardFramebuffer(GL_COLOR_EXT | GL_DEPTH_EXT | GL_STENCIL_EXT);
			}
#endif
			glWindow->swapBuffers();
			glWindow->doneCurrent();
			gameMutex.unlock();
		}
		else
		{
			gameMutex.lock();
			glWindow->makeCurrent();
			glClearColor(0, 0, 0, 0);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

			time_update();
			float t = (float)frames_ / 60.0f;
			frames_++;

			float alpha = t;
			if (t > 1.0f) alpha = 1.0f;
			float alphaText = alpha;
			//if (t > 2.0f) alphaText = 3.0f - t;

			glstate.Restore();
			glViewport(0, 0, pixel_xres, pixel_yres);
			Matrix4x4 ortho;
			ortho.setOrtho(0.0f, dp_xres, dp_yres, 0.0f, -1.0f, 1.0f);
			glsl_bind(UIShader_Get());
			glUniformMatrix4fv(UIShader_Get()->u_worldviewproj, 1, GL_FALSE, ortho.getReadPtr());


			ReapplyGfxState();

			UIShader_Prepare();
			UIBegin();
			DrawBackground(alpha);

			ui_draw2d.SetFontScale(1.5f, 1.5f);
			ui_draw2d.DrawText(UBUNTU48, "PPSSPP", dp_xres / 2, dp_yres / 2 - 30, colorAlpha(0xFFFFFFFF, alphaText), ALIGN_CENTER);
			ui_draw2d.SetFontScale(1.0f, 1.0f);
			ui_draw2d.DrawText(UBUNTU24, "Created by Henrik Rydgard", dp_xres / 2, dp_yres / 2 + 40, colorAlpha(0xFFFFFFFF, alphaText), ALIGN_CENTER);
			ui_draw2d.DrawText(UBUNTU24, "Free Software under GPL 2.0", dp_xres / 2, dp_yres / 2 + 70, colorAlpha(0xFFFFFFFF, alphaText), ALIGN_CENTER);
			ui_draw2d.DrawText(UBUNTU24, "www.ppsspp.org", dp_xres / 2, dp_yres / 2 + 130, colorAlpha(0xFFFFFFFF, alphaText), ALIGN_CENTER);

			UIEnd();

			glsl_bind(UIShader_Get());
			ui_draw2d.Flush(UIShader_Get());

			glWindow->swapBuffers();
			glWindow->doneCurrent();
			gameMutex.unlock();
			qint64 time = timer.elapsed();
			const int frameTime = (1.0f/60.0f) * 1000;
			if(time < frameTime)
			{
				msleep(frameTime-time);
			}
			timer.start();
		}

	}

	if(gameRunning)
	{
		stopGame();
	}

}
Esempio n. 3
0
void qAnimationDlg::preview()
{
	//we'll take the rendering time into account!
	QElapsedTimer timer;
	timer.start();

	setEnabled(false);

	size_t vp1 = previewFromSelectedCheckBox->isChecked() ? static_cast<size_t>(getCurrentStepIndex()) : 0;

	//count the total number of frames
	int frameCount = countFrames(loopCheckBox->isChecked() ? 0 : vp1);
	int fps = fpsSpinBox->value();

	//show progress dialog
	QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this);
	progressDialog.setWindowTitle("Preview");
	progressDialog.show();
	progressDialog.setModal(true);
	progressDialog.setAutoClose(false);
	QApplication::processEvents();

	assert(stepSelectionList->count() >= m_videoSteps.size());

	int frameIndex = 0;
	size_t vp2 = 0;
	while (getNextSegment(vp1, vp2))
	{
		Step& step1 = m_videoSteps[vp1];
		Step& step2 = m_videoSteps[vp2];

		//theoretical waiting time per frame
		qint64 delay_ms = static_cast<int>(1000 * step1.duration_sec / fps);
		int frameCount = static_cast<int>( fps * step1.duration_sec );

		ViewInterpolate interpolator(step1.viewport, step2.viewport);
		interpolator.setMaxStep(frameCount);
		cc2DViewportObject currentParams;
		while ( interpolator.nextView( currentParams ) )
		{
			timer.restart();
			applyViewport ( &currentParams );
			qint64 dt_ms = timer.elapsed();

			progressDialog.setValue(++frameIndex);
			QApplication::processEvents();
			if (progressDialog.wasCanceled())
			{
				break;
			}

			//remaining time
			if (dt_ms < delay_ms)
			{
				int wait_ms = static_cast<int>(delay_ms - dt_ms);
#if defined(CC_WINDOWS)
				::Sleep( wait_ms );
#else
				usleep( wait_ms * 1000 );
#endif
			}
		}
		if (progressDialog.wasCanceled())
		{
			break;
		}

		if (vp2 == 0)
		{
			assert(loopCheckBox->isChecked());
			frameIndex = 0;
		}
		vp1 = vp2;
	}

	//reset view
	onCurrentStepChanged(getCurrentStepIndex());

	setEnabled(true);
}
Esempio n. 4
0
bool QtLockedFile::lock(LockMode mode, bool block)
{
#ifdef ZOMBOID
    QElapsedTimer elapsed;
    elapsed.start();
#endif

    if (!isOpen()) {
        qWarning("QtLockedFile::lock(): file is not opened");
        return false;
    }

    if (mode == m_lock_mode)
        return true;

    if (m_lock_mode != 0)
        unlock();

    if (m_semaphore_hnd == 0) {
        QFileInfo fi(*this);
        QString sem_name = QString::fromLatin1(SEMAPHORE_PREFIX)
                           + fi.absoluteFilePath().toLower();

        m_semaphore_hnd = CreateSemaphoreW(0, SEMAPHORE_MAX, SEMAPHORE_MAX,
                                           (TCHAR*)sem_name.utf16());

        if (m_semaphore_hnd == 0) {
            qWarning("QtLockedFile::lock(): CreateSemaphore: %s",
                     errorCodeToString(GetLastError()).toLatin1().constData());
            return false;
        }
    }

    bool gotMutex = false;
    int decrement;
    if (mode == ReadLock) {
        decrement = 1;
    } else {
        decrement = SEMAPHORE_MAX;
        if (m_mutex_hnd == 0) {
            QFileInfo fi(*this);
            QString mut_name = QString::fromLatin1(MUTEX_PREFIX)
                               + fi.absoluteFilePath().toLower();

            m_mutex_hnd = CreateMutexW(NULL, FALSE, (TCHAR*)mut_name.utf16());

            if (m_mutex_hnd == 0) {
                qWarning("QtLockedFile::lock(): CreateMutex: %s",
                         errorCodeToString(GetLastError()).toLatin1().constData());
                return false;
            }
        }
        DWORD res = WaitForSingleObject(m_mutex_hnd, block ? INFINITE : 0);
        if (res == WAIT_TIMEOUT)
            return false;
        if (res == WAIT_FAILED) {
            qWarning("QtLockedFile::lock(): WaitForSingleObject (mutex): %s",
                     errorCodeToString(GetLastError()).toLatin1().constData());
            return false;
        }
        gotMutex = true;
    }

    for (int i = 0; i < decrement; ++i) {
        DWORD res = WaitForSingleObject(m_semaphore_hnd, block ? INFINITE : 0);
        if (res == WAIT_TIMEOUT) {
            if (i) {
                // A failed nonblocking rw locking. Undo changes to semaphore.
                if (ReleaseSemaphore(m_semaphore_hnd, i, NULL) == 0) {
                    qWarning("QtLockedFile::unlock(): ReleaseSemaphore: %s",
                             errorCodeToString(GetLastError()).toLatin1().constData());
                    // Fall through
                }
            }
            if (gotMutex)
                ReleaseMutex(m_mutex_hnd);
            return false;
	}
        if (res != WAIT_OBJECT_0) {
            if (gotMutex)
                ReleaseMutex(m_mutex_hnd);
            qWarning("QtLockedFile::lock(): WaitForSingleObject (semaphore): %s",
                        errorCodeToString(GetLastError()).toLatin1().constData());
            return false;
        }
    }

    m_lock_mode = mode;
    if (gotMutex)
        ReleaseMutex(m_mutex_hnd);
#ifdef ZOMBOID
    if (elapsed.elapsed() > 0)
        qDebug() << "QtLockedFile::lock took" << elapsed.elapsed() << "ms";
#endif
    return true;
}
Esempio n. 5
0
toolpath::toolpath(preprocess &p)
{
    QElapsedTimer timer;
    timer.start();

    int i,j;
    struct net tempPreprocessNetPath;

    //produce toolpath for every element
    //method:offset the shape with the radius of the bit
    //then link the breaking points
    for(j=0;j<p.netList.size();j++)
    {
        struct netPath tempToolPathNetPath;
        tempPreprocessNetPath=p.netList.at(j);
        Paths tempCPaths;
        for(i=0;i<tempPreprocessNetPath.elements.size();i++)
        {
            struct myPath tempPath;
            struct element e=tempPreprocessNetPath.elements.at(i);
            struct segment s;
            tempPath.element=e;
            if(e.elementType=='T')//track
            {
                struct myRect r=trackToMyRect(e.track,toolDiameter);

                s.point=r.p1;
                s.type='L';
                tempPath.segmentList.append(s);
                s.point=r.p2;
                s.type='C';
                tempPath.segmentList.append(s);
                s.point=r.p3;
                s.type='L';
                tempPath.segmentList.append(s);
                s.point=r.p4;
                s.type='C';
                tempPath.segmentList.append(s);

                IntPoint point;
                point.X=r.p1.x();point.Y=r.p1.y();
                tempPath.toolpath<<point;
                arcToSegments(r.p2,r.p3,tempPath.toolpath);
                point.X=r.p4.x();point.Y=r.p4.y();
                tempPath.toolpath<<point;
                arcToSegments(r.p4,r.p1,tempPath.toolpath);
            }
            else//pad
            {
                if(e.pad.shape=='C')
                {
                    QPoint point;
                    QPoint point1,point2;
                    point.setX(e.pad.point.x());
                    point.setY(e.pad.point.y()+e.pad.parameter[0]/2+toolDiameter/2);
                    point1=point;
                    s.point=point;
                    s.type='C';
                    tempPath.segmentList.append(s);

                    point.setY(e.pad.point.y()-e.pad.parameter[0]/2-toolDiameter/2);
                    point2=point;
                    s.point=point;
                    s.type='C';
                    tempPath.segmentList.append(s);

                    arcToSegments(point1,point2,tempPath.toolpath);
                    arcToSegments(point2,point1,tempPath.toolpath);
                }
                else if(e.pad.shape=='R')
                {
                    struct myRect r=rectToMyRect(e.pad,toolDiameter);
                    s.point=r.p1;
                    s.type='L';
                    tempPath.segmentList.append(s);
                    s.point=r.p2;
                    s.type='L';
                    tempPath.segmentList.append(s);
                    s.point=r.p3;
                    s.type='L';
                    tempPath.segmentList.append(s);
                    s.point=r.p4;
                    s.type='L';
                    tempPath.segmentList.append(s);

                    IntPoint point;
                    point.X=r.p1.x();point.Y=r.p1.y();
                    tempPath.toolpath<<point;
                    point.X=r.p2.x();point.Y=r.p2.y();
                    tempPath.toolpath<<point;
                    point.X=r.p3.x();point.Y=r.p3.y();
                    tempPath.toolpath<<point;
                    point.X=r.p4.x();point.Y=r.p4.y();
                    tempPath.toolpath<<point;
                }
                else if(e.pad.shape=='O')
                {
                    struct track t=obroundToTrack(e.pad);
                    struct myRect r=trackToMyRect(t,toolDiameter);
                    s.point=r.p1;
                    s.type='L';
                    tempPath.segmentList.append(s);
                    s.point=r.p2;
                    s.type='C';
                    tempPath.segmentList.append(s);
                    s.point=r.p3;
                    s.type='L';
                    tempPath.segmentList.append(s);
                    s.point=r.p4;
                    s.type='C';
                    tempPath.segmentList.append(s);

                    IntPoint point;
                    point.X=r.p1.x();point.Y=r.p1.y();
                    tempPath.toolpath<<point;
                    arcToSegments(r.p2,r.p3,tempPath.toolpath);
                    point.X=r.p4.x();point.Y=r.p4.y();
                    tempPath.toolpath<<point;
                    arcToSegments(r.p4,r.p1,tempPath.toolpath);
                }
            }
            tempCPaths.push_back(tempPath.toolpath);
            tempPath.boundingRect=expandBoundingRect(e.boundingRect,toolDiameter);
            tempToolPathNetPath.pathList.append(tempPath);

        }
        SimplifyPolygons(tempCPaths,tempToolPathNetPath.toolpath,pftNonZero);
        netPathList.append(tempToolPathNetPath);
    }
    cToolpathIntersects(netPathList,tpCollisionNum);
    int sum=0;
    for(int i=0;i<tpCollisionNum.size();i++)
    {
        collisionToolpath temp=tpCollisionNum.at(i);
        sum+=temp.pair.size();
        for(int j=0;j<temp.pair.size();j++)
        {
            net n=p.netList.at(temp.pair.at(j).p1);
            n.collisionFlag=true;
            p.netList.replace(temp.pair.at(j).p1,n);

            n=p.netList.at(temp.pair.at(j).p2);
            n.collisionFlag=true;
            p.netList.replace(temp.pair.at(j).p2,n);
        }
    }
    qDebug()<<"toolpath collision num="<<sum;
    collisionSum=sum;

    Paths tempPath;
    for(i=0;i<netPathList.size();i++)
        tempPath.push_back(netPathList.at(i).toolpath.at(0));

    SimplifyPolygons(tempPath,totalToolpath,pftNonZero);

    for(i=0;i<netPathList.size();i++)
        if(netPathList.at(i).toolpath.size()>1)
        {
            for(j=1;j<netPathList.at(i).toolpath.size();j++)
            totalToolpath.push_back(netPathList.at(i).toolpath.at(j));
        }

    time=timer.elapsed();

}
Esempio n. 6
0
void qCSF::doAction()
{
	//m_app should have already been initialized by CC when plugin is loaded!
	//(--> pure internal check)
	assert(m_app);
	if (!m_app)
		return;

	if ( !m_app->haveOneSelection() )
	{
		m_app->dispToConsole("Select only one cloud!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

	const ccHObject::Container& selectedEntities = m_app->getSelectedEntities();

	ccHObject* ent = selectedEntities[0];
	assert(ent);
	if (!ent || !ent->isA(CC_TYPES::POINT_CLOUD))
	{
		m_app->dispToConsole("Select a real point cloud!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

	//to get the point cloud from selected entity.
	ccPointCloud* pc = static_cast<ccPointCloud*>(ent);

	//Convert CC point cloud to CSF type
	unsigned count = pc->size();
	wl::PointCloud csfPC;
	try
	{
		csfPC.reserve(count);
	}
	catch (const std::bad_alloc&)
	{
		m_app->dispToConsole("Not enough memory!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}
	for (unsigned i = 0; i < count; i++)
	{
		const CCVector3* P = pc->getPoint(i);
		wl::Point tmpPoint;
		//tmpPoint.x = P->x;
		//tmpPoint.y = P->y;
		//tmpPoint.z = P->z;
		tmpPoint.x =  P->x;
		tmpPoint.y = -P->z;
		tmpPoint.z =  P->y;
		csfPC.push_back(tmpPoint);
	}

	//initial dialog parameters
	static bool csf_postprocessing = false;
	static double cloth_resolution = 2;
	static double class_threshold = 0.5;
	static int csf_rigidness = 2;
	static int MaxIteration = 500;
	static bool ExportClothMesh = false;

	// display the dialog
	{
		ccCSFDlg csfDlg(m_app->getMainWindow());
		csfDlg.postprocessingcheckbox->setChecked(csf_postprocessing);
		csfDlg.rig1->setChecked(csf_rigidness == 1);
		csfDlg.rig2->setChecked(csf_rigidness == 2);
		csfDlg.rig3->setChecked(csf_rigidness == 3);
		csfDlg.MaxIterationSpinBox->setValue(MaxIteration);
		csfDlg.cloth_resolutionSpinBox->setValue(cloth_resolution);
		csfDlg.class_thresholdSpinBox->setValue(class_threshold);
		csfDlg.exportClothMeshCheckBox->setChecked(ExportClothMesh);

		if (!csfDlg.exec())
		{
			return;
		}

		//save the parameters for next time
		csf_postprocessing = csfDlg.postprocessingcheckbox->isChecked();
		if (csfDlg.rig1->isChecked())
			csf_rigidness = 1;
		else if (csfDlg.rig2->isChecked())
			csf_rigidness = 2;
		else
			csf_rigidness = 3;
		MaxIteration = csfDlg.MaxIterationSpinBox->value();
		cloth_resolution = csfDlg.cloth_resolutionSpinBox->value();
		class_threshold = csfDlg.class_thresholdSpinBox->value();
		ExportClothMesh = csfDlg.exportClothMeshCheckBox->isChecked();
	}

	//display the progress dialog
	QProgressDialog pDlg;
	pDlg.setWindowTitle("CSF");
	pDlg.setLabelText("Computing....");
	pDlg.setCancelButton(0);
	pDlg.show();
	QApplication::processEvents();

	QElapsedTimer timer;
	timer.start();
	//instantiation a CSF class
	CSF csf(csfPC);

	// setup parameter
	csf.params.k_nearest_points = 1;
	csf.params.bSloopSmooth = csf_postprocessing;
	csf.params.time_step = 0.65;
	csf.params.class_threshold = class_threshold;
	csf.params.cloth_resolution = cloth_resolution;
	csf.params.rigidness = csf_rigidness;
	csf.params.iterations = MaxIteration;
	//to do filtering
	std::vector<int> groundIndexes, offGroundIndexes;
	ccMesh* clothMesh = 0;
	if (!csf.do_filtering(groundIndexes, offGroundIndexes, ExportClothMesh, clothMesh, m_app))
	{
		m_app->dispToConsole("Process failed", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

	m_app->dispToConsole(QString("[CSF] %1% of points classified as ground points").arg((groundIndexes.size() * 100.0) / count, 0, 'f', 2), ccMainAppInterface::STD_CONSOLE_MESSAGE);
	m_app->dispToConsole(QString("[CSF] Timing: %1 s.").arg(timer.elapsed() / 1000.0, 0, 'f', 1), ccMainAppInterface::STD_CONSOLE_MESSAGE);

	//extract ground subset
	ccPointCloud* groundpoint = 0;
	{
		CCLib::ReferenceCloud groundpc(pc);
		if (groundpc.reserve(static_cast<unsigned>(groundIndexes.size())))
		{
			for (unsigned j = 0; j < groundIndexes.size(); ++j)
			{
				groundpc.addPointIndex(groundIndexes[j]);
			}
			groundpoint = pc->partialClone(&groundpc);
		}
	}
	if (!groundpoint)
	{
		m_app->dispToConsole("Failed to extract the ground subset (not enough memory)", ccMainAppInterface::WRN_CONSOLE_MESSAGE);
	}

	//extract off-ground subset
	ccPointCloud* offgroundpoint = 0;
	{
		CCLib::ReferenceCloud offgroundpc(pc);
		if (offgroundpc.reserve(static_cast<unsigned>(offGroundIndexes.size())))
		{
			for (unsigned k = 0; k < offGroundIndexes.size(); ++k)
			{
				offgroundpc.addPointIndex(offGroundIndexes[k]);
			}
			offgroundpoint = pc->partialClone(&offgroundpc);
		}
	}
	if (!offgroundpoint)
	{
		m_app->dispToConsole("Failed to extract the off-ground subset (not enough memory)", ccMainAppInterface::WRN_CONSOLE_MESSAGE);
		if (!groundpoint)
		{
			//nothing to do!
			return;
		}
	}

	pDlg.hide();
	QApplication::processEvents();
	
	//hide the original cloud
	pc->setEnabled(false);

	//we add new group to DB/display
	ccHObject* cloudContainer = new ccHObject(pc->getName() + QString("_csf"));
	if (groundpoint)
	{
		groundpoint->setVisible(true);
		groundpoint->setName("ground points");
		cloudContainer->addChild(groundpoint);
	}

	if (offgroundpoint)
	{
		offgroundpoint->setVisible(true);
		offgroundpoint->setName("off-ground points");
		cloudContainer->addChild(offgroundpoint);
	}

	if (clothMesh)
	{
		clothMesh->computePerVertexNormals();
		clothMesh->showNormals(true);
		cloudContainer->addChild(clothMesh);
	}

	m_app->addToDB(cloudContainer);
	m_app->refreshAll();
}
Esempio n. 7
0
void CorrespondenceSearch::run()
{
	QElapsedTimer allTimer; allTimer.start();

    auto & paths = generator->computedAssignments;

	QVector<ParticleMesh*> input; input << sA << sB;
	QVector<Particles> inputParticles; inputParticles << sA->particles << sB->particles;
	auto boxA = sA->bbox();

	std::vector<double> pathScores( paths.size(), DBL_MAX );
  
	bool abort = false;

    // Evaluate correspondences
    #pragma omp parallel for
    for(int pi = 0; pi < (int)paths.size(); pi++)
    {
        #pragma omp flush (abort)
        if(!abort)
        {
            if(pd->wasCanceled()){
                abort = true;
                #pragma omp flush (abort)
            }

			double score = 0;
			auto & path = paths[pi];

			// Compute dense correspondence
			QVector<Particles> particles = inputParticles;
			for(auto & pairing : path) PartCorresponder::correspondSegments( pairing, input, particles );

			// Evaluate correspondence:
			{
				int numSamples = 4;
				int start = 1; // Skipping initial configuration

				for(int sample = start; sample < numSamples; sample++) 
				{
					double t = double(sample) / (numSamples-1);

					for(auto & p : particles[0])
					{
						// one-to-none
						if( p.correspondence > particles[1].size() ) 
						{
							score += (p.pos /*- boxA.center()*/).norm() * 100;
							continue;
						}

						auto blended = AlphaBlend(t, p.pos, particles[1][p.correspondence].pos);

						score += (blended - p.pos).norm();
					}
				}
			}

			pathScores[pi] = score;

			emit( pathComputed() );
        }
    }

	/// Assign best correspondence:
	{
		auto bestPath = std::min_element(pathScores.begin(), pathScores.end()) - pathScores.begin();
		bestCorrespondence = paths[bestPath];
	}

	// Timing
	property["allSearchTime"].setValue( (int)allTimer.elapsed() );

	emit( done() );
}
Esempio n. 8
0
unsigned long now()
{
    return timer.elapsed();
}
void PeerObject::readData()
{
// 	static int readCount	=	0;
// 	m_dbgLog.write("PeerObject::readData()");
// 	m_dbgLog.write(QString("(%1)\n").arg(++readCount).toLatin1());
// 	m_dbgLog.flush();

	static quint64	totalRead	=	0;

	while(m_socket->availableData()) {
		// Read size
		quint32	orgSize	=	0;
		quint32	size		=	0;

		if(m_socket->bytesAvailable() < sizeof(size)) {
			callSlotQueued(this, "checkReadData");
			return;
		}

		if(m_socket->read((char *)&orgSize, sizeof(orgSize)) < sizeof(orgSize))
			qFatal("Could not read size!");

		size	=	qFromBigEndian<quint32>(orgSize);
// 		if(m_socket->read((char*)&size, sizeof(size)) < sizeof(size))
// 			qFatal("Could not checksum!");
// 		size	=	qFromBigEndian<quint32>(size);

// 		qDebug("Peer: size to read: %u", size);

		if(size == 0) {
			qDebug("Peer: PeerObject::readData() - zero size data");

			m_peerSocket->write(QStringLiteral("fReceived zero size").toLatin1());
// 			m_peerSocket->flush();

			if(m_close)
				close(1);

			return;
		}

		// Read data with specified size
		QElapsedTimer	timer;
		QByteArray		data(size, (char)'\0');

// 		qDebug("PeerObject::readData() - size: %u", size);

		// m_dbgLog.write("Reading: ");
		// m_dbgLog.write(QStringLiteral("%1 bytes").arg(size).toLatin1());
		// m_dbgLog.write("\n");
		// m_dbgLog.flush();

		// Read max 30 seconds
		timer.start();
		qint64	tmp		=	0;
		qint64	read	=	0;
		bool		waiting	=	false;

		while(read < size && timer.elapsed() < 10000) {
			if(m_socket->bytesAvailable() < 1) {
				waiting	=	true;
// 				Logger::log("Read bytes (TestLocalSocket_Ext_PO)", totalRead + read, "bW", "Begin waiting for bytes");
				if(m_socket->waitForReadyRead(10000 - timer.elapsed()))
					timer.restart();
			}

			tmp	=	m_socket->read(data.data() + read, size - read);

			if(tmp < 0) {
				m_peerSocket->write(QStringLiteral("fCould not read data!").toLatin1());
// 				m_peerSocket->flush();

				close(1);
				return;
			}

// 			Logger::log("Read tmp bytes (TestLocalSocket_Ext_PO)", tmp);

			read	+=	tmp;
		}

// 		if(waiting)
// 			Logger::log("Read bytes (TestLocalSocket_Ext_PO)", totalRead + read, "eW", "End waiting for bytes");

		// m_dbgLog.write("Ok\n");
		// m_dbgLog.flush();

		// Check read data size
		if(read < size) {
			qDebug("Peer: PeerObject::readData() - not enough data");

			m_peerSocket->write(QStringLiteral("fDid not receive enough data. Expected: %1; Got: %2").arg(size).arg(data.size()).toLatin1());
// 			m_peerSocket->flush();

// 			m_dbgLog.write("Did not receive enough data");
// 			m_dbgLog.write("\n");
// 			m_dbgLog.flush();

			if(m_close)
				close(1);

			return;
		}

// 		printf("=== Data read (%lld/%d) ===\n", read, data.size());
// 		QByteArray	tmpData(QByteArray((const char*)&orgSize, sizeof(orgSize)) + data);
// 		for(int i = 0; i < tmpData.size(); i++)
// 			printf("%02X", tmpData.constData()[i]);
// 		printf("\n=================\n");

		// m_dbgLog.write("Locking: 170\n");// m_dbgLog.flush();
		QWriteLocker		writeLocker(&m_dataLock);
		// m_dbgLog.write("Ok: 170\n");// m_dbgLog.flush();

		// Store data
		m_data.append(data);

		static int totalReadCount	=	0;
		totalReadCount++;
		Logger::log("Handled data", totalReadCount);
	}

	callSlotQueued(this, "checkReadData");
}
Esempio n. 10
0
int main(int argc, char  *argv[])
{
    QCoreApplication application(argc, argv);

    QContactManager manager(QLatin1String("org.nemomobile.contacts.sqlite"));

    QContactFetchRequest request;
    request.setManager(&manager);

    qint64 elapsedTimeTotal = 0;

    QElapsedTimer asyncTotalTimer;
    asyncTotalTimer.start();

    // Fetch all, no optimization hints
    for (int i = 0; i < 3; ++i) {
        QElapsedTimer timer;
        timer.start();
        request.start();
        request.waitForFinished();

        qint64 elapsed = timer.elapsed();
        qDebug() << i << ": Fetch completed in" << elapsed << "ms";
        elapsedTimeTotal += elapsed;
    }

    // Skip relationships
    QContactFetchHint hint;
    hint.setOptimizationHints(QContactFetchHint::NoRelationships);
    request.setFetchHint(hint);

    for (int i = 0; i < 3; ++i) {
        QElapsedTimer timer;
        timer.start();
        request.start();
        request.waitForFinished();

        qint64 elapsed = timer.elapsed();
        qDebug() << i << ": No-relationships fetch completed in" << elapsed << "ms";
        elapsedTimeTotal += elapsed;
    }

    // Reduce data access
#ifdef USING_QTPIM
    hint.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactName::Type << QContactAddress::Type);
#else
    hint.setDetailDefinitionsHint(QStringList() << QContactName::DefinitionName << QContactAddress::DefinitionName);
#endif
    request.setFetchHint(hint);

    for (int i = 0; i < 3; ++i) {
        QElapsedTimer timer;
        timer.start();
        request.start();
        request.waitForFinished();

        qint64 elapsed = timer.elapsed();
        qDebug() << i << ": Reduced data fetch completed in" << elapsed << "ms";
        elapsedTimeTotal += elapsed;
    }

    // Reduce number of results
    hint.setMaxCountHint(request.contacts().count() / 8);
    request.setFetchHint(hint);

    for (int i = 0; i < 3; ++i) {
        QElapsedTimer timer;
        timer.start();
        request.start();
        request.waitForFinished();

        qint64 elapsed = timer.elapsed();
        qDebug() << i << ": Max count fetch completed in" << elapsed << "ms";
        elapsedTimeTotal += elapsed;
    }
    qint64 asyncTotalElapsed = asyncTotalTimer.elapsed();



    // Time some synchronous operations.  First, generate the test data.
    qsrand((int)asyncTotalElapsed);
    QList<int> nbrContacts;
    nbrContacts << 10 << 100 << 500 << 1000 << 2000;
    QList<QList<QContact> > testData;
    qDebug() << "\n\n\n\n\n";
    qDebug() << "Generating test data for timings...";
    for (int i = 0; i < nbrContacts.size(); ++i) {
        int howMany = nbrContacts.at(i);
        QList<QContact> newTestData;
        newTestData.reserve(howMany);

        for (int j = 0; j < howMany; ++j) {
            newTestData.append(generateContact());
        }

        testData.append(newTestData);
    }


    // Perform the timings - these all create new contacts and assume an "empty" initial database
    QElapsedTimer syncTimer;
    for (int i = 0; i < testData.size(); ++i) {
        QList<QContact> td = testData.at(i);
        qint64 ste = 0;
        qDebug() << "Performing tests for" << td.size() << "contacts:";

        syncTimer.start();
        manager.saveContacts(&td);
        ste = syncTimer.elapsed();
        qDebug() << "    saving took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        QContactFetchHint fh;
        syncTimer.start();
        QList<QContact> readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all (" << readContacts.size() << "), all details, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

#ifdef USING_QTPIM
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type
                << QContactName::Type << QContactAvatar::Type
                << QContactPhoneNumber::Type << QContactEmailAddress::Type);
#else
        fh.setDetailDefinitionsHint(QStringList() << QContactDisplayLabel::DefinitionName
                << QContactName::DefinitionName << QContactAvatar::DefinitionName
                << QContactPhoneNumber::DefinitionName << QContactEmailAddress::DefinitionName);
#endif
        syncTimer.start();
        readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all, common details, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        fh.setOptimizationHints(QContactFetchHint::NoRelationships);
#ifdef USING_QTPIM
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>());
#else
        fh.setDetailDefinitionsHint(QStringList());
#endif
        syncTimer.start();
        readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all, no relationships, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

#ifdef USING_QTPIM
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type
                << QContactName::Type << QContactAvatar::Type);
#else
        fh.setDetailDefinitionsHint(QStringList() << QContactDisplayLabel::DefinitionName
                << QContactName::DefinitionName << QContactAvatar::DefinitionName);
#endif
        syncTimer.start();
        readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        QContactDetailFilter firstNameStartsA;
#ifdef USING_QTPIM
        firstNameStartsA.setDetailType(QContactName::Type, QContactName::FieldFirstName);
#else
        firstNameStartsA.setDetailDefinitionName(QContactName::DefinitionName, QContactName::FieldFirstName);
#endif
        firstNameStartsA.setValue("A");
        firstNameStartsA.setMatchFlags(QContactDetailFilter::MatchStartsWith);
#ifdef USING_QTPIM
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>());
#else
        fh.setDetailDefinitionsHint(QStringList());
#endif
        syncTimer.start();
        readContacts = manager.contacts(firstNameStartsA, QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading filtered (" << readContacts.size() << "), no relationships, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

#ifdef USING_QTPIM
        QList<QContactId> idsToRemove;
        for (int j = 0; j < td.size(); ++j) {
            idsToRemove.append(td.at(j).id());
        }
#else
        QList<QContactLocalId> idsToRemove;
        for (int j = 0; j < td.size(); ++j) {
            idsToRemove.append(td.at(j).localId());
        }
#endif
        syncTimer.start();
        manager.removeContacts(idsToRemove);
        ste = syncTimer.elapsed();
        qDebug() << "    removing test data took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;
    }

    // these tests are slightly different to those above.  They operate on much smaller
    // batches, but occur after the database has already been prefilled with some data.
    QList<int> smallerNbrContacts;
    smallerNbrContacts << 1 << 2 << 5 << 10 << 20 << 50;
    QList<QList<QContact> > smallerTestData;
    qDebug() << "\n\nGenerating smaller test data for prefilled timings...";
    for (int i = 0; i < smallerNbrContacts.size(); ++i) {
        int howMany = smallerNbrContacts.at(i);
        QList<QContact> newTestData;
        newTestData.reserve(howMany);

        for (int j = 0; j < howMany; ++j) {
            newTestData.append(generateContact());
        }

        smallerTestData.append(newTestData);
    }

    // prefill the database
    QList<QContact> prefillData;
    for (int i = 0; i < testData.size() && testData.at(i).size() < 1001; ++i) {
        prefillData = testData.at(i);
    }
    qDebug() << "Prefilling database with" << prefillData.size() << "contacts... this will take a while...";
    manager.saveContacts(&prefillData);
    qDebug() << "Now performing timings (shouldn't get aggregated)...";
    for (int i = 0; i < smallerTestData.size(); ++i) {
        QList<QContact> td = smallerTestData.at(i);
        qint64 ste = 0;
        qDebug() << "Performing tests for" << td.size() << "contacts:";

        syncTimer.start();
        manager.saveContacts(&td);
        ste = syncTimer.elapsed();
        qDebug() << "    saving took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;

        QContactFetchHint fh;
        syncTimer.start();
        QList<QContact> readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all (" << readContacts.size() << "), all details, took" << ste << "milliseconds";
        elapsedTimeTotal += ste;

#ifdef USING_QTPIM
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type
                << QContactName::Type << QContactAvatar::Type
                << QContactPhoneNumber::Type << QContactEmailAddress::Type);
#else
        fh.setDetailDefinitionsHint(QStringList() << QContactDisplayLabel::DefinitionName
                << QContactName::DefinitionName << QContactAvatar::DefinitionName
                << QContactPhoneNumber::DefinitionName << QContactEmailAddress::DefinitionName);
#endif
        syncTimer.start();
        readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all, common details, took" << ste << "milliseconds";
        elapsedTimeTotal += ste;

        fh.setOptimizationHints(QContactFetchHint::NoRelationships);
#ifdef USING_QTPIM
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>());
#else
        fh.setDetailDefinitionsHint(QStringList());
#endif
        syncTimer.start();
        readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all, no relationships, took" << ste << "milliseconds";
        elapsedTimeTotal += ste;

#ifdef USING_QTPIM
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type
                << QContactName::Type << QContactAvatar::Type);
#else
        fh.setDetailDefinitionsHint(QStringList() << QContactDisplayLabel::DefinitionName
                << QContactName::DefinitionName << QContactAvatar::DefinitionName);
#endif
        syncTimer.start();
        readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading all, display details + no rels, took" << ste << "milliseconds";
        elapsedTimeTotal += ste;

        QContactDetailFilter firstNameStartsA;
#ifdef USING_QTPIM
        firstNameStartsA.setDetailType(QContactName::Type, QContactName::FieldFirstName);
#else
        firstNameStartsA.setDetailDefinitionName(QContactName::DefinitionName, QContactName::FieldFirstName);
#endif
        firstNameStartsA.setValue("A");
        firstNameStartsA.setMatchFlags(QContactDetailFilter::MatchStartsWith);
#ifdef USING_QTPIM
        fh.setDetailTypesHint(QList<QContactDetail::DetailType>());
#else
        fh.setDetailDefinitionsHint(QStringList());
#endif
        syncTimer.start();
        readContacts = manager.contacts(firstNameStartsA, QList<QContactSortOrder>(), fh);
        ste = syncTimer.elapsed();
        qDebug() << "    reading filtered (" << readContacts.size() << "), no relationships, took" << ste << "milliseconds";
        elapsedTimeTotal += ste;

#ifdef USING_QTPIM
        QList<QContactId> idsToRemove;
        for (int j = 0; j < td.size(); ++j) {
            idsToRemove.append(td.at(j).id());
        }
#else
        QList<QContactLocalId> idsToRemove;
        for (int j = 0; j < td.size(); ++j) {
            idsToRemove.append(td.at(j).localId());
        }
#endif
        syncTimer.start();
        manager.removeContacts(idsToRemove);
        ste = syncTimer.elapsed();
        qDebug() << "    removing test data took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )";
        elapsedTimeTotal += ste;
    }


    // The next test is about saving contacts which should get aggregated into others.
    // Aggregation is an expensive operation, so we expect these save operations to take longer.
    qDebug() << "\n\nPerforming aggregation tests";
    QList<QContact> contactsToAggregate;
    for (int i = 0; i < 100; ++i) {
        QContact existingContact = prefillData.at(prefillData.size() - 1 - i);
        QContact contactToAggregate;
        QContactSyncTarget newSyncTarget;
        newSyncTarget.setSyncTarget(QString(QLatin1String("fetchtimes-aggregation")));
        QContactName aggName = existingContact.detail<QContactName>(); // ensures it'll get aggregated
        QContactOnlineAccount newOnlineAcct; // new data, which should get promoted up etc.
        newOnlineAcct.setAccountUri(QString(QLatin1String("test-aggregation-%1@fetchtimes")).arg(i));
        contactToAggregate.saveDetail(&newSyncTarget);
        contactToAggregate.saveDetail(&aggName);
        contactToAggregate.saveDetail(&newOnlineAcct);
        contactsToAggregate.append(contactToAggregate);
    }

    syncTimer.start();
    manager.saveContacts(&contactsToAggregate);
    qint64 aggregationElapsed = syncTimer.elapsed();
    int totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "Average time for aggregation of" << contactsToAggregate.size() << "contacts (with" << totalAggregatesInDatabase << "existing in database):" << aggregationElapsed
             << "milliseconds (" << ((1.0 * aggregationElapsed) / (1.0 * contactsToAggregate.size())) << " msec per aggregated contact )";
    elapsedTimeTotal += aggregationElapsed;

    // Now perform the test again, this time with more aggregates, to test nonlinearity.
    contactsToAggregate.clear();
    for (int i = 200; i < 400; ++i) {
        QContact existingContact = prefillData.at(prefillData.size() - 1 - i);
        QContact contactToAggregate;
        QContactSyncTarget newSyncTarget;
        newSyncTarget.setSyncTarget(QString(QLatin1String("fetchtimes-aggregation")));
        QContactName aggName = existingContact.detail<QContactName>(); // ensures it'll get aggregated
        QContactOnlineAccount newOnlineAcct; // new data, which should get promoted up etc.
        newOnlineAcct.setAccountUri(QString(QLatin1String("test-aggregation-%1@fetchtimes")).arg(i));
        contactToAggregate.saveDetail(&newSyncTarget);
        contactToAggregate.saveDetail(&aggName);
        contactToAggregate.saveDetail(&newOnlineAcct);
        contactsToAggregate.append(contactToAggregate);
    }

    syncTimer.start();
    manager.saveContacts(&contactsToAggregate);
    aggregationElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "Average time for aggregation of" << contactsToAggregate.size() << "contacts (with" << totalAggregatesInDatabase << "existing in database):" << aggregationElapsed
             << "milliseconds (" << ((1.0 * aggregationElapsed) / (1.0 * contactsToAggregate.size())) << " msec per aggregated contact )";
    elapsedTimeTotal += aggregationElapsed;


    // The next test is about updating existing contacts, amongst a large set.
    // We're especially interested in presence updates, as these are common.
    qDebug() << "\n\nPerforming presence update tests:";

    // in the first presence update test, we update a small number of contacts.
    QStringList presenceAvatars = generateAvatarsList();
    QList<QContact> contactsToUpdate;
    for (int i = 0; i < 10; ++i) {
        contactsToUpdate.append(prefillData.at(prefillData.size() - 1 - i));
    }

    // modify the presence, nickname and avatar of the test data
    for (int j = 0; j < contactsToUpdate.size(); ++j) {
        QString genstr = QString::number(j);
        QContact curr = contactsToUpdate[j];
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(QDateTime::currentDateTime());
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>(qrand() % 4));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.replace(j, curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    qint64 presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // in the second presence update test, we update ALL of the contacts
    // This simulates having a large number of contacts from a single source (eg, a social network)
    // where (due to changed connectivity status) presence updates for the entire set become available.
    contactsToUpdate.clear();
    QDateTime timestamp = QDateTime::currentDateTime();
    for (int j = 0; j < prefillData.size(); ++j) {
        QContact curr = prefillData.at(j);
        QString genstr = QString::number(j) + "2";
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(timestamp);
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // the third presence update test is identical to the previous, but with 2000 prefilled contacts in database.
    qDebug() << "    Adding more prefill data, please wait...";
    QList<QContact> morePrefillData;
    for (int i = 0; i < 1000; ++i) {
        morePrefillData.append(generateContact());
    }
    manager.saveContacts(&morePrefillData);

    // now do the updates and save.
    contactsToUpdate.clear();
    timestamp = QDateTime::currentDateTime();
    for (int j = 0; j < prefillData.size(); ++j) {
        QContact curr = prefillData.at(j);
        QString genstr = QString::number(j) + "3";
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(timestamp);
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.append(curr);
    }
    for (int j = 0; j < morePrefillData.size(); ++j) {
        QContact curr = morePrefillData.at(j);
        QString genstr = QString::number(j) + "3";
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(timestamp);
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // clean up the "more prefill data"
    qDebug() << "    cleaning up extra prefill data, please wait...";
#ifdef USING_QTPIM
    QList<QContactId> morePrefillIds;
    for (int j = 0; j < morePrefillData.size(); ++j) {
        morePrefillIds.append(morePrefillData.at(j).id());
    }
#else
    QList<QContactLocalId> morePrefillIds;
    for (int j = 0; j < morePrefillData.size(); ++j) {
        morePrefillIds.append(morePrefillData.at(j).localId());
    }
#endif
    manager.removeContacts(morePrefillIds);

    // the fourth presence update test checks update time for non-overlapping sets of data.
    qDebug() << "    generating non-overlapping / aggregated prefill data, please wait...";
    morePrefillData.clear();
    for (int i = 0; i < 1000; ++i) {
        morePrefillData.append(generateContact("test-presence-4", false)); // false = don't aggregate.
    }
    manager.saveContacts(&morePrefillData);

    // now do the update
    contactsToUpdate.clear();
    timestamp = QDateTime::currentDateTime();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        QContact curr = morePrefillData.at(j);
        QString genstr = QString::number(j) + "4";
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(timestamp);
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, no overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // clean up the "more prefill data"
    qDebug() << "    cleaning up extra prefill data, please wait...";
#ifdef USING_QTPIM
    morePrefillIds.clear();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        morePrefillIds.append(morePrefillData.at(j).id());
    }
#else
    morePrefillIds.clear();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        morePrefillIds.append(morePrefillData.at(j).localId());
    }
#endif
    manager.removeContacts(morePrefillIds);

    // the fifth presence update test is similar to the above except that half of
    // the extra contacts have a (high) chance of being aggregated into an existing contact.
    // So, database should have 2000 constituents, 1000 from "local", 1000 from "test-presence-5"
    // with 1500 aggregates (about 500 of test-presence-5 contacts will share an aggregate with
    // a local contact).  TODO: check what happens if multiple aggregates for local contacts
    // could possibly match a given test-presence-5 contact (which is possible, since the backend
    // never aggregates two contacts from the same sync source...)
    qDebug() << "    generating partially-overlapping / aggregated prefill data, please wait...";
    morePrefillData.clear();
    for (int i = 0; i < 1000; ++i) {
        if (i < 500) {
            morePrefillData.append(generateContact("test-presence-5", false)); // false = don't aggregate.
        } else {
            morePrefillData.append(generateContact("test-presence-5", true));  // true = possibly aggregate.
        }
    }
    manager.saveContacts(&morePrefillData);

    // now do the update
    contactsToUpdate.clear();
    timestamp = QDateTime::currentDateTime();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        QContact curr = morePrefillData.at(j);
        QString genstr = QString::number(j) + "5";
        QContactPresence cp = curr.detail<QContactPresence>();
        QContactNickname nn = curr.detail<QContactNickname>();
        QContactAvatar av = curr.detail<QContactAvatar>();
        cp.setNickname(genstr);
        cp.setCustomMessage(genstr);
        cp.setTimestamp(timestamp);
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        nn.setNickname(nn.nickname() + genstr);
        av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size()));
        curr.saveDetail(&cp);
        curr.saveDetail(&nn);
        curr.saveDetail(&av);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, 500 overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // the sixth presence update test is identical to the fifth test, except that we ONLY
    // update the presence status (not nickname or avatar).
    morePrefillData = contactsToUpdate;
    contactsToUpdate.clear();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        QContact curr = morePrefillData.at(j);
        QContactPresence cp = curr.detail<QContactPresence>();
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        curr.saveDetail(&cp);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") presence only (with" << totalAggregatesInDatabase << "existing in database, 500 overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // the seventh presence update test is identical to the 6th test, except that
    // we also pass a "detail type mask" to the update.  This allows the backend
    // to perform optimisation based upon which details are modified.
    morePrefillData = contactsToUpdate;
    contactsToUpdate.clear();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        QContact curr = morePrefillData.at(j);
        QContactPresence cp = curr.detail<QContactPresence>();
        cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1));
        curr.saveDetail(&cp);
        contactsToUpdate.append(curr);
    }

    // perform a batch save.
#ifdef USING_QTPIM
    QList<QContactDetail::DetailType> typeMask;
    typeMask << QContactDetail::TypePresence;
#else
    QStringList typeMask;
    typeMask << QString(QLatin1String(QContactPresence::DefinitionName));
#endif
    syncTimer.start();
    manager.saveContacts(&contactsToUpdate, typeMask);
    presenceElapsed = syncTimer.elapsed();
    totalAggregatesInDatabase = manager.contactIds().count();
    qDebug() << "    update ( batch of" << contactsToUpdate.size() << ") masked presence only (with" << totalAggregatesInDatabase << "existing in database, 500 overlap):" << presenceElapsed
             << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )";
    elapsedTimeTotal += presenceElapsed;

    // clean up the "more prefill data"
    qDebug() << "    cleaning up extra prefill data, please wait...";
#ifdef USING_QTPIM
    morePrefillIds.clear();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        morePrefillIds.append(morePrefillData.at(j).id());
    }
#else
    morePrefillIds.clear();
    for (int j = 0; j < morePrefillData.size(); ++j) {
        morePrefillIds.append(morePrefillData.at(j).localId());
    }
#endif
    manager.removeContacts(morePrefillIds);

    qDebug() << "\n\nCumulative elapsed time:" << elapsedTimeTotal << "milliseconds";
    return 0;
}
Esempio n. 11
0
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // Command Line Parser
    QCommandLineParser parser;
    parser.setApplicationDescription("Clustered Inverse Powell Rap Music Raw Example");
    parser.addHelpOption();

    QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
    QCommandLineOption eventsFileOption("eve", "Path to the event <file>.", "file", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/sample_audvis_raw-eve.fif");
    QCommandLineOption fwdOption("fwd", "Path to forwad solution <file>.", "file", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif");
    QCommandLineOption surfOption("surfType", "Surface type <type>.", "type", "orig");
    QCommandLineOption annotOption("annotType", "Annotation type <type>.", "type", "aparc.a2009s");
    QCommandLineOption subjectOption("subject", "Selected subject <subject>.", "subject", "sample");
    QCommandLineOption subjectPathOption("subjectPath", "Selected subject path <subjectPath>.", "subjectPath", QCoreApplication::applicationDirPath() + "/MNE-sample-data/subjects");
    QCommandLineOption stcFileOption("stcOut", "Path to stc <file>, which is to be written.", "file", "");
    QCommandLineOption numDipolePairsOption("numDip", "<number> of dipole pairs to localize.", "number", "7");
    QCommandLineOption evokedIdxOption("aveIdx", "The average <index> to choose from the average file.", "index", "1");
    QCommandLineOption hemiOption("hemi", "Selected hemisphere <hemi>.", "hemi", "2");
    QCommandLineOption doMovieOption("doMovie", "Create overlapping movie.", "doMovie", "false");
    QCommandLineOption keepCompOption("keepComp", "Keep compensators.", "keepComp", "false");
    QCommandLineOption pickAllOption("pickAll", "Pick all channels.", "pickAll", "true");
    QCommandLineOption destCompsOption("destComps", "<Destination> of the compensator which is to be calculated.", "destination", "0");

    parser.addOption(inputOption);
    parser.addOption(eventsFileOption);
    parser.addOption(fwdOption);
    parser.addOption(surfOption);
    parser.addOption(annotOption);
    parser.addOption(subjectOption);
    parser.addOption(subjectPathOption);
    parser.addOption(stcFileOption);
    parser.addOption(numDipolePairsOption);
    parser.addOption(evokedIdxOption);
    parser.addOption(hemiOption);
    parser.addOption(doMovieOption);
    parser.addOption(keepCompOption);
    parser.addOption(pickAllOption);
    parser.addOption(destCompsOption);

    parser.process(a);

    //Load data
    QFile t_fileRaw(parser.value(inputOption));
    QString t_sEventName = parser.value(eventsFileOption);
    QFile t_fileFwd(parser.value(fwdOption));

    SurfaceSet t_surfSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(surfOption), parser.value(subjectPathOption));
    AnnotationSet t_annotationSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(annotOption), parser.value(subjectPathOption));

    QString t_sFileNameStc(parser.value(stcFileOption));

    qint32 numDipolePairs = parser.value(numDipolePairsOption).toInt();

    //Choose average
    qint32 event = parser.value(evokedIdxOption).toInt();

    float tmin = 0.1f;
    float tmax = 0.2f;

    bool keep_comp = false;
    if(parser.value(keepCompOption) == "false" || parser.value(keepCompOption) == "0") {
        keep_comp = false;
    } else if(parser.value(keepCompOption) == "true" || parser.value(keepCompOption) == "1") {
        keep_comp = true;
    }

    fiff_int_t dest_comp = parser.value(destCompsOption).toInt();

    bool pick_all = false;
    if(parser.value(pickAllOption) == "false" || parser.value(pickAllOption) == "0") {
        pick_all = false;
    } else if(parser.value(pickAllOption) == "true" || parser.value(pickAllOption) == "1") {
        pick_all = true;
    }

    qint32 k, p;

    bool doMovie = false;
    if(parser.value(doMovieOption) == "false" || parser.value(doMovieOption) == "0") {
        pick_all = false;
    } else if(parser.value(doMovieOption) == "true" || parser.value(doMovieOption) == "1") {
        pick_all = true;
    }

    //
    // Load data
    //
    MNEForwardSolution t_Fwd(t_fileFwd);
    if(t_Fwd.isEmpty())
        return 1;

    //
    //   Setup for reading the raw data
    //
    FiffRawData raw(t_fileRaw);

    RowVectorXi picks;
    if (pick_all)
    {
        //
        // Pick all
        //
        picks.resize(raw.info.nchan);

        for(k = 0; k < raw.info.nchan; ++k)
            picks(k) = k;
        //
    }
    else
    {
        QStringList include;
        include << "STI 014";
        bool want_meg   = true;
        bool want_eeg   = false;
        bool want_stim  = false;

        picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);//prefer member function
    }

    QStringList ch_names;
    for(k = 0; k < picks.cols(); ++k)
        ch_names << raw.info.ch_names[picks(0,k)];

    //
    //   Set up projection
    //
    if (raw.info.projs.size() == 0)
        printf("No projector specified for these data\n");
    else
    {
        //
        //   Activate the projection items
        //
        for (k = 0; k < raw.info.projs.size(); ++k)
            raw.info.projs[k].active = true;

        printf("%d projection items activated\n",raw.info.projs.size());
        //
        //   Create the projector
        //
//        fiff_int_t nproj = MNE::make_projector_info(raw.info, raw.proj); Using the member function instead
        fiff_int_t nproj = raw.info.make_projector(raw.proj);

        if (nproj == 0)
        {
            printf("The projection vectors do not apply to these channels\n");
        }
        else
        {
            printf("Created an SSP operator (subspace dimension = %d)\n",nproj);
        }
    }

    //
    //   Set up the CTF compensator
    //
    qint32 current_comp = raw.info.get_current_comp();
    if (current_comp > 0)
        printf("Current compensation grade : %d\n",current_comp);

    if (keep_comp)
        dest_comp = current_comp;

    if (current_comp != dest_comp)
    {
        qDebug() << "This part needs to be debugged";
        if(MNE::make_compensator(raw.info, current_comp, dest_comp, raw.comp))
        {
            raw.info.set_current_comp(dest_comp);
            printf("Appropriate compensator added to change to grade %d.\n",dest_comp);
        }
        else
        {
            printf("Could not make the compensator\n");
            return 0;
        }
    }
    //
    //  Read the events
    //
    QFile t_EventFile;
    MatrixXi events;
    if (t_sEventName.size() == 0)
    {
        p = t_fileRaw.fileName().indexOf(".fif");
        if (p > 0)
        {
            t_sEventName = t_fileRaw.fileName().replace(p, 4, "-eve.fif");
        }
        else
        {
            printf("Raw file name does not end properly\n");
            return 0;
        }
//        events = mne_read_events(t_sEventName);

        t_EventFile.setFileName(t_sEventName);
        MNE::read_events(t_EventFile, events);
        printf("Events read from %s\n",t_sEventName.toUtf8().constData());
    }
    else
    {
        //
        //   Binary file
        //
        p = t_fileRaw.fileName().indexOf(".fif");
        if (p > 0)
        {
            t_EventFile.setFileName(t_sEventName);
            if(!MNE::read_events(t_EventFile, events))
            {
                printf("Error while read events.\n");
                return 0;
            }
            printf("Binary event file %s read\n",t_sEventName.toUtf8().constData());
        }
        else
        {
            //
            //   Text file
            //
            printf("Text file %s is not supported jet.\n",t_sEventName.toUtf8().constData());
//            try
//                events = load(eventname);
//            catch
//                error(me,mne_omit_first_line(lasterr));
//            end
//            if size(events,1) < 1
//                error(me,'No data in the event file');
//            end
//            //
//            //   Convert time to samples if sample number is negative
//            //
//            for p = 1:size(events,1)
//                if events(p,1) < 0
//                    events(p,1) = events(p,2)*raw.info.sfreq;
//                end
//            end
//            //
//            //    Select the columns of interest (convert to integers)
//            //
//            events = int32(events(:,[1 3 4]));
//            //
//            //    New format?
//            //
//            if events(1,2) == 0 && events(1,3) == 0
//                fprintf(1,'The text event file %s is in the new format\n',eventname);
//                if events(1,1) ~= raw.first_samp
//                    error(me,'This new format event file is not compatible with the raw data');
//                end
//            else
//                fprintf(1,'The text event file %s is in the old format\n',eventname);
//                //
//                //   Offset with first sample
//                //
//                events(:,1) = events(:,1) + raw.first_samp;
//            end
        }
    }

    //
    //    Select the desired events
    //
    qint32 count = 0;
    MatrixXi selected = MatrixXi::Zero(1, events.rows());
    for (p = 0; p < events.rows(); ++p)
    {
        if (events(p,1) == 0 && events(p,2) == event)
        {
            selected(0,count) = p;
            ++count;
        }
    }
    selected.conservativeResize(1, count);
    if (count > 0)
        printf("%d matching events found\n",count);
    else
    {
        printf("No desired events found.\n");
        return 0;
    }


    fiff_int_t event_samp, from, to;
    MatrixXd timesDummy;

    MNEEpochDataList data;

    MNEEpochData* epoch = NULL;

    MatrixXd times;

    for (p = 0; p < count; ++p)
    {
        //
        //       Read a data segment
        //
        event_samp = events(selected(p),0);
        from = event_samp + tmin*raw.info.sfreq;
        to   = event_samp + floor(tmax*raw.info.sfreq + 0.5);

        epoch = new MNEEpochData();

        if(raw.read_raw_segment(epoch->epoch, timesDummy, from, to, picks))
        {
            if (p == 0)
            {
                times.resize(1, to-from+1);
                for (qint32 i = 0; i < times.cols(); ++i)
                    times(0, i) = ((float)(from-event_samp+i)) / raw.info.sfreq;
            }

            epoch->event = event;
            epoch->tmin = ((float)(from)-(float)(raw.first_samp))/raw.info.sfreq;
            epoch->tmax = ((float)(to)-(float)(raw.first_samp))/raw.info.sfreq;

            data.append(MNEEpochData::SPtr(epoch));//List takes ownwership of the pointer - no delete need
        }
        else
        {
            printf("Can't read the event data segments");
            return 0;
        }
    }

    if(data.size() > 0)
    {
        printf("Read %d epochs, %d samples each.\n",data.size(),(qint32)data[0]->epoch.cols());

//        //DEBUG
//        std::cout << data[0]->epoch.block(0,0,10,10) << std::endl;
//        qDebug() << data[0]->epoch.rows() << " x " << data[0]->epoch.cols();

//        std::cout << times.block(0,0,1,10) << std::endl;
//        qDebug() << times.rows() << " x " << times.cols();
    }


    // Calculate the average
    // Option 1 - Random selection
    VectorXi vecSel(2);    
    srand (time(NULL)); // initialize random seed

    for(qint32 i = 0; i < vecSel.size(); ++i)
    {
        qint32 val = rand() % count;
        vecSel(i) = val;
    }

//    //Option 3 - Take all epochs
//    VectorXi vecSel(data.size());

//    for(qint32 i = 0; i < vecSel.size(); ++i)
//    {
//        vecSel(i) = i;
//    }

//    //Option 3 - Manual selection
//    VectorXi vecSel(20);

//    vecSel << 76, 74, 13, 61, 97, 94, 75, 71, 60, 56, 26, 57, 56, 0, 52, 72, 33, 86, 96, 67;


    std::cout << "Select following epochs to average:\n" << vecSel << std::endl;

    FiffEvoked evoked = data.average(raw.info, tmin*raw.info.sfreq, floor(tmax*raw.info.sfreq + 0.5), vecSel);

    QStringList ch_sel_names = t_Fwd.info.ch_names;
    FiffEvoked pickedEvoked = evoked.pick_channels(ch_sel_names);

    //########################################################################################
    // RAP MUSIC Source Estimate

    //
    // Cluster forward solution;
    //
    MNEForwardSolution t_clusteredFwd = t_Fwd.cluster_forward_solution(t_annotationSet, 20);//40);

    //
    // Compute inverse solution
    //
    PwlRapMusic t_pwlRapMusic(t_clusteredFwd, false, numDipolePairs);

#ifdef BENCHMARK
    MNESourceEstimate sourceEstimate;
    QList<qint64> qVecElapsedTime;
    for(qint32 i = 0; i < 100; ++i)
    {
        //Benchmark time
        QElapsedTimer timer;
        timer.start();
        sourceEstimate = t_pwlRapMusic.calculateInverse(pickedEvoked);
        qVecElapsedTime.append(timer.elapsed());
    }

    double meanTime = 0.0;
    qint32 offset = 19;
    qint32 c = 0;
    for(qint32 i = offset; i < qVecElapsedTime.size(); ++i)
    {
        meanTime += qVecElapsedTime[i];
        ++c;
    }

    meanTime /= (double)c;

    double varTime = 0;
    for(qint32 i = offset; i < qVecElapsedTime.size(); ++i)
        varTime += pow(qVecElapsedTime[i] - meanTime,2);

    varTime /= (double)c - 1.0f;
    varTime = sqrt(varTime);

    qDebug() << "RAP-MUSIC calculation took" << meanTime << "+-" << varTime << "ms in average";

#else
    int iWinSize = 200;
    if(doMovie) {
        t_pwlRapMusic.setStcAttr(iWinSize, 0.6f);
    }

    MNESourceEstimate sourceEstimate = t_pwlRapMusic.calculateInverse(pickedEvoked);

    if(doMovie) {
        //Select only the activations once
        MatrixXd dataPicked(sourceEstimate.data.rows(), int(std::floor(sourceEstimate.data.cols()/iWinSize)));

        for(int i = 0; i < dataPicked.cols(); ++i) {
            dataPicked.col(i) = sourceEstimate.data.col(i*iWinSize);
        }

        sourceEstimate.data = dataPicked;
    }

    if(sourceEstimate.isEmpty()) {
        return 1;
    }

#endif

    if(sourceEstimate.isEmpty())
        return 1;

//    // View activation time-series
//    std::cout << "\nsourceEstimate:\n" << sourceEstimate.data.block(0,0,10,10) << std::endl;
//    std::cout << "time\n" << sourceEstimate.times.block(0,0,1,10) << std::endl;
//    std::cout << "timeMin\n" << sourceEstimate.times[0] << std::endl;
//    std::cout << "timeMax\n" << sourceEstimate.times[sourceEstimate.times.size()-1] << std::endl;
//    std::cout << "time step\n" << sourceEstimate.tstep << std::endl;

    //Source Estimate end
    //########################################################################################

//    //only one time point - P100
//    qint32 sample = 0;
//    for(qint32 i = 0; i < sourceEstimate.times.size(); ++i)
//    {
//        if(sourceEstimate.times(i) >= 0)
//        {
//            sample = i;
//            break;
//        }
//    }
//    sample += (qint32)ceil(0.106/sourceEstimate.tstep); //100ms
//    sourceEstimate = sourceEstimate.reduce(sample, 1);

    AbstractView::SPtr p3DAbstractView = AbstractView::SPtr(new AbstractView());
    Data3DTreeModel::SPtr p3DDataModel = p3DAbstractView->getTreeModel();

    p3DDataModel->addSurfaceSet(parser.value(subjectOption), evoked.comment, t_surfSet, t_annotationSet);

    //Add rt source loc data and init some visualization values
    if(MneEstimateTreeItem* pRTDataItem = p3DDataModel->addSourceData(parser.value(subjectOption),
                                                                      evoked.comment,
                                                                      sourceEstimate,
                                                                      t_clusteredFwd,
                                                                      t_surfSet,
                                                                      t_annotationSet)) {
        pRTDataItem->setLoopState(true);
        pRTDataItem->setTimeInterval(17);
        pRTDataItem->setNumberAverages(1);
        pRTDataItem->setStreamingState(true);
        pRTDataItem->setThresholds(QVector3D(0.01f,0.5f,1.0f));
        pRTDataItem->setVisualizationType("Annotation based");
        pRTDataItem->setColormapType("Hot");
    }

    p3DAbstractView->show();

    QList<Label> t_qListLabels;
    QList<RowVector4i> t_qListRGBAs;

    //ToDo overload toLabels using instead of t_surfSet rr of MNESourceSpace
    t_annotationSet.toLabels(t_surfSet, t_qListLabels, t_qListRGBAs);

    if(!t_sFileNameStc.isEmpty())
    {
        QFile t_fileClusteredStc(t_sFileNameStc);
        sourceEstimate.write(t_fileClusteredStc);
    }

    return a.exec();//1;//a.exec();
}
Esempio n. 12
0
/// @brief ctor
/// @param _pos the position of the emitter
/// @param _numParticles the number of particles to create
Emitter::Emitter(ngl::Vec3 _pos, unsigned int _numParticles, ngl::Vec3 *_wind )
{
  m_wind=_wind;
  Particle p;
  GLParticle g;
  ngl::Random *rand=ngl::Random::instance();
  ngl::NGLMessage::addMessage("Starting emitter ctor\n");
  QElapsedTimer timer;
  timer.start();
  m_pos=_pos;
  m_particles.reset(  new Particle[_numParticles]);
  m_glparticles.reset( new GLParticle[_numParticles]);
  m_vao= ngl::VAOFactory::createVAO(ngl::simpleVAO,GL_POINTS);

  float pointOnCircleX= cosf(ngl::radians(m_time))*4.0f;
  float pointOnCircleZ= sinf(ngl::radians(m_time))*4.0f;
  ngl::Vec3 end(pointOnCircleX,2.0,pointOnCircleZ);
  end=end-m_pos;

#pragma omp parallel for ordered schedule(dynamic)
  for (unsigned int i=0; i< _numParticles; ++i)
  {
    g.px=p.m_px=m_pos.m_x;
    g.py=p.m_py=m_pos.m_y;
    g.pz=p.m_pz=m_pos.m_z;
    ngl::Vec3 c=rand->getRandomColour3();
    p.m_r=g.pr=c.m_r;
    p.m_g=g.pg=c.m_g;
    p.m_b=g.pb=c.m_b;

    p.m_dx=end.m_x+rand->randomNumber(2)+0.5f;
    p.m_dy=end.m_y+rand->randomPositiveNumber(10)+0.5f;
    p.m_dz=end.m_z+rand->randomNumber(2)+0.5f;
    p.m_gravity=-9.0f;
    p.m_currentLife=0.0f;
    m_particles[i]=p;
    m_glparticles[i]=g;
  }
  m_numParticles=_numParticles;
  // create the VAO and stuff data

  m_vao->bind();
  // now copy the data
  m_vao->setData(ngl::SimpleVAO::VertexData(m_numParticles*sizeof(GLParticle),m_glparticles[0].px));
  m_vao->setVertexAttributePointer(0,3,GL_FLOAT,sizeof(GLParticle),0);
  m_vao->setVertexAttributePointer(1,3,GL_FLOAT,sizeof(GLParticle),3);
  m_vao->setNumIndices(m_numParticles);
  m_vao->unbind();

  ngl::NGLMessage::addMessage(fmt::format("Finished filling array took %d milliseconds\n",timer.elapsed()));
  /// @note this demo is based on alembic/lib/Alembic/AbcGeom/Tests/PointsTest.cpp

  // create an alembic Geometry output archive called particlesOut.abc
  Alembic::AbcCoreAbstract::MetaData md;
//  CreateArchiveWithInfo(
//                  Alembic::AbcCoreOgawa::WriteArchive(), "archiveInfo.abc",
//                  appWriter, userStr, md );
//  m_archive.reset(new  AbcG::OArchive(Alembic::AbcCoreOgawa::WriteArchive(),"particlesOut.abc",md) );
  namespace Abc = Alembic::Abc;
  using namespace Abc;
  OArchive archive;
  std::string appWriter = "ngl Alembic Export";
  std::string userStr = "Simple Demo of exporting points with alembic";

//  m_archive.reset( CreateArchiveWithInfo(
//                    Alembic::AbcCoreOgawa::WriteArchive(), "archiveInfo.abc",
//                    appWriter, userStr, md )) ;
//
   m_archive=CreateArchiveWithInfo(
                             Alembic::AbcCoreOgawa::WriteArchive(), "particlesOut.abc",
                             appWriter, userStr, md );
  // create time sampling of 24 fps at frame 0 to start
  AbcG::TimeSampling ts(1.0f/24.0f, 0.0f);
  // get the archive top
  //AbcG::OObject topObj( *m_archive.get(), AbcG::kTop );
  AbcG::OObject topObj( m_archive, AbcG::kTop );

  // then add in our time sampling.
  Alembic::Util::uint32_t tsidx = topObj.getArchive().addTimeSampling(ts);
  // this is our particle outputs to write to each frame
  m_partsOut.reset( new AbcG::OPoints(topObj, "simpleParticles", tsidx) );
  // now add a colour property to the alembic file for out points
  AbcG::MetaData mdata;

  AbcG::SetGeometryScope( mdata, AbcG::kVaryingScope );
  AbcG::OPointsSchema &pSchema = m_partsOut->getSchema();
  std::cout<<"Schema "<<pSchema.getNumSamples()<<" "<<pSchema.valid()<<"\n";
  m_rgbOut.reset(new AbcG::OC3fArrayProperty( pSchema, "Cd", tsidx ));
}
Esempio n. 13
0
/// @brief a method to update each of the particles contained in the system
void Emitter::update()
{
  QElapsedTimer timer;
  timer.start();
  ngl::NGLMessage::addMessage("Starting emitter update\n");

  m_vao->bind();
  ngl::Real *glPtr=m_vao->mapBuffer();

  unsigned int glIndex=0;
  static int rot=0;
  static float time=0.0f;
  float pointOnCircleX= cosf(ngl::radians(time))*4.0f;
  float pointOnCircleZ= sinf(ngl::radians(time))*4.0f;
  ngl::Vec3 end(pointOnCircleX,2.0f,pointOnCircleZ);
  end=end-m_pos;
  //end.normalize();
  time+=m_time;

  #pragma omp parallel for
  for(unsigned int i=0; i<m_numParticles; ++i)
  {
    m_particles[i].m_currentLife+=0.002f;
    // use projectile motion equation to calculate the new position
    // x(t)=Ix+Vxt
    // y(t)=Iy+Vxt-1/2gt^2
    // z(t)=Iz+Vzt

    m_particles[i].m_px=m_pos.m_x+(m_wind->m_x*m_particles[i].m_dx*m_particles[i].m_currentLife);
    m_particles[i].m_py= m_pos.m_y+(m_wind->m_y*m_particles[i].m_dy*m_particles[i].m_currentLife)+m_particles[i].m_gravity*(m_particles[i].m_currentLife*m_particles[i].m_currentLife);
    m_particles[i].m_pz=m_pos.m_z+(m_wind->m_z*m_particles[i].m_dz*m_particles[i].m_currentLife);
    glPtr[glIndex]=m_particles[i].m_px;
    glPtr[glIndex+1]=m_particles[i].m_py;
    glPtr[glIndex+2]=m_particles[i].m_pz;
    // if we go below the origin re-set
    if(m_particles[i].m_py <= m_pos.m_y-0.01f)
    {
      ++rot;
      m_particles[i].m_px=m_pos.m_x;
      m_particles[i].m_pz=m_pos.m_y;
      m_particles[i].m_px=m_pos.m_z;

      m_particles[i].m_currentLife=0.0;
      ngl::Random *rand=ngl::Random::instance();
      m_particles[i].m_dx=end.m_x+rand->randomNumber(2)+0.5f;
      m_particles[i].m_dy=end.m_y+rand->randomPositiveNumber(10)+0.5f;
      m_particles[i].m_dz=end.m_z+rand->randomNumber(2)+0.5f;

      glPtr[glIndex]=m_particles[i].m_px;
      glPtr[glIndex+1]=m_particles[i].m_py;
      glPtr[glIndex+2]=m_particles[i].m_pz;
      ngl::Vec3 c=rand->getRandomColour3();
      glPtr[glIndex+3]=c.m_r;
      glPtr[glIndex+4]=c.m_g;
      glPtr[glIndex+5]=c.m_b;
      m_particles[i].m_r=c.m_r;
      m_particles[i].m_g=c.m_g;
      m_particles[i].m_b=c.m_b;

    }
    #pragma omp atomic
    glIndex+=6;

  }
  m_vao->unmapBuffer();

  m_vao->unbind();

 ngl::NGLMessage::addMessage(fmt::format("Finished update array took %d milliseconds\n",timer.elapsed()));
}
Esempio n. 14
0
void qFacets::extractFacets(CellsFusionDlg::Algorithm algo)
{
	//disclaimer accepted?
	if (!ShowDisclaimer(m_app))
		return;

	assert(m_app);
	if (!m_app)
		return;

	//we expect a unique cloud as input
	const ccHObject::Container& selectedEntities = m_app->getSelectedEntities();
	ccPointCloud* pc = (selectedEntities.size() == 1 ? ccHObjectCaster::ToPointCloud(selectedEntities.back()) : 0);
	if (!pc)
	{
		m_app->dispToConsole("Select one and only one point cloud!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

	if (algo != CellsFusionDlg::ALGO_FAST_MARCHING && algo != CellsFusionDlg::ALGO_KD_TREE)
	{
		m_app->dispToConsole("Internal error: invalid algorithm type!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

	//first time: we compute the max edge length automatically
	if (s_lastCloud != pc)
	{
		s_maxEdgeLength = static_cast<double>(pc->getOwnBB().getMinBoxDim())/50;
		s_minPointsPerFacet = std::max<unsigned>(pc->size() / 100000, 10);
		s_lastCloud = pc;
	}

	CellsFusionDlg fusionDlg(algo,m_app->getMainWindow());
	if (algo == CellsFusionDlg::ALGO_FAST_MARCHING)
		fusionDlg.octreeLevelSpinBox->setCloud(pc);

	fusionDlg.octreeLevelSpinBox->setValue(s_octreeLevel);
	fusionDlg.useRetroProjectionCheckBox->setChecked(s_fmUseRetroProjectionError);
	fusionDlg.minPointsPerFacetSpinBox->setValue(s_minPointsPerFacet);
	fusionDlg.errorMeasureComboBox->setCurrentIndex(s_errorMeasureType);
	fusionDlg.maxRMSDoubleSpinBox->setValue(s_errorMaxPerFacet);
	fusionDlg.maxAngleDoubleSpinBox->setValue(s_kdTreeFusionMaxAngle_deg);
	fusionDlg.maxRelativeDistDoubleSpinBox->setValue(s_kdTreeFusionMaxRelativeDistance);
	fusionDlg.maxEdgeLengthDoubleSpinBox->setValue(s_maxEdgeLength);
	//"no normal" warning
	fusionDlg.noNormalWarningLabel->setVisible(!pc->hasNormals());

	if (!fusionDlg.exec())
		return;

	s_octreeLevel						= fusionDlg.octreeLevelSpinBox->value();
	s_fmUseRetroProjectionError			= fusionDlg.useRetroProjectionCheckBox->isChecked();
	s_minPointsPerFacet					= fusionDlg.minPointsPerFacetSpinBox->value();
	s_errorMeasureType					= fusionDlg.errorMeasureComboBox->currentIndex();
	s_errorMaxPerFacet					= fusionDlg.maxRMSDoubleSpinBox->value();
	s_kdTreeFusionMaxAngle_deg			= fusionDlg.maxAngleDoubleSpinBox->value();
	s_kdTreeFusionMaxRelativeDistance	= fusionDlg.maxRelativeDistDoubleSpinBox->value();
	s_maxEdgeLength						= fusionDlg.maxEdgeLengthDoubleSpinBox->value();

	//convert 'errorMeasureComboBox' index to enum
	CCLib::DistanceComputationTools::ERROR_MEASURES errorMeasure = CCLib::DistanceComputationTools::RMS;
	switch (s_errorMeasureType)
	{
	case 0:
		errorMeasure = CCLib::DistanceComputationTools::RMS;
		break;
	case 1:
		errorMeasure = CCLib::DistanceComputationTools::MAX_DIST_68_PERCENT;
		break;
	case 2:
		errorMeasure = CCLib::DistanceComputationTools::MAX_DIST_95_PERCENT;
		break;
	case 3:
		errorMeasure = CCLib::DistanceComputationTools::MAX_DIST_99_PERCENT;
		break;
	case 4:
		errorMeasure = CCLib::DistanceComputationTools::MAX_DIST;
		break;
	default:
		assert(false);
		break;
	}
	
	//create scalar field to host the fusion result
	const char c_defaultSFName[] = "facet indexes";
	int sfIdx = pc->getScalarFieldIndexByName(c_defaultSFName);
	if (sfIdx < 0)
		sfIdx = pc->addScalarField(c_defaultSFName);
	if (sfIdx < 0)
	{
		m_app->dispToConsole("Couldn't allocate a new scalar field for computing fusion labels! Try to free some memory ...",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}
	pc->setCurrentScalarField(sfIdx);
	
	//computation
	QElapsedTimer eTimer;
	eTimer.start();
	ccProgressDialog pDlg(true,m_app->getMainWindow());

	bool success = true;
	if (algo == CellsFusionDlg::ALGO_KD_TREE)
	{
		//we need a kd-tree
		QElapsedTimer eTimer;
		eTimer.start();
		ccKdTree kdtree(pc);

		if (kdtree.build(s_errorMaxPerFacet/2,errorMeasure,s_minPointsPerFacet,1000,&pDlg))
		{
			qint64 elapsedTime_ms = eTimer.elapsed();
			m_app->dispToConsole(QString("[qFacets] Kd-tree construction timing: %1 s").arg(static_cast<double>(elapsedTime_ms)/1.0e3,0,'f',3),ccMainAppInterface::STD_CONSOLE_MESSAGE);
		
			success = ccKdTreeForFacetExtraction::FuseCells(
				&kdtree,
				s_errorMaxPerFacet,
				errorMeasure,
				s_kdTreeFusionMaxAngle_deg,
				static_cast<PointCoordinateType>(s_kdTreeFusionMaxRelativeDistance),
				true,
				&pDlg);
		}
		else
		{
			m_app->dispToConsole("Failed to build Kd-tree! (not enough memory?)",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
			success = false;
		}
	}
	else if (algo == CellsFusionDlg::ALGO_FAST_MARCHING)
	{
		int result = FastMarchingForFacetExtraction::ExtractPlanarFacets(
			pc,
			static_cast<unsigned char>(s_octreeLevel),
			static_cast<ScalarType>(s_errorMaxPerFacet),
			errorMeasure,
			s_fmUseRetroProjectionError,
			&pDlg,
			pc->getOctree());

		success = (result >= 0);
	}

	if (success)
	{
		pc->setCurrentScalarField(sfIdx); //for AutoSegmentationTools::extractConnectedComponents
		
		CCLib::ReferenceCloudContainer components;
		if (!CCLib::AutoSegmentationTools::extractConnectedComponents(pc,components))
		{
			m_app->dispToConsole("Failed to extract fused components! (not enough memory?)",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		}
		else
		{
			//we remove the temporary scalar field (otherwise it will be copied to the sub-clouds!)
			ccScalarField* indexSF = static_cast<ccScalarField*>(pc->getScalarField(sfIdx));
			indexSF->link(); //to prevent deletion below
			pc->deleteScalarField(sfIdx);
			sfIdx = -1;

			bool error = false;
			ccHObject* group = createFacets(pc,components,s_minPointsPerFacet,s_maxEdgeLength,false,error);

			if (group)
			{
				switch(algo)
				{
				case CellsFusionDlg::ALGO_KD_TREE:
					group->setName(group->getName() + QString(" [Kd-tree][error < %1][angle < %2 deg.]").arg(s_errorMaxPerFacet).arg(s_kdTreeFusionMaxAngle_deg));
					break;
				case CellsFusionDlg::ALGO_FAST_MARCHING:
					group->setName(group->getName() + QString(" [FM][level %2][error < %1]").arg(s_octreeLevel).arg(s_errorMaxPerFacet));
					break;
				default:
					break;
				}

				unsigned count = group->getChildrenNumber();
				m_app->dispToConsole(QString("[qFacets] %1 facet(s) where created from cloud '%2'").arg(count).arg(pc->getName()));

				if (error)
				{
					m_app->dispToConsole("Error(s) occurred during the generation of facets! Result may be incomplete",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
				}
				else
				{
					//we but back the scalar field
					if (indexSF)
						sfIdx = pc->addScalarField(indexSF);
				}

				//pc->setEnabled(false);
				m_app->addToDB(group);
				group->prepareDisplayForRefresh();
			}
			else if (error)
			{
				m_app->dispToConsole("An error occurred during the generation of facets!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
			}
			else
			{
				m_app->dispToConsole("No facet remains! Check the parameters (min size, etc.)",ccMainAppInterface::WRN_CONSOLE_MESSAGE);
			}
		}
	}
	else
	{
		m_app->dispToConsole("An error occurred during the fusion process!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
	}

	if (sfIdx >= 0)
	{
		pc->getScalarField(sfIdx)->computeMinAndMax();
#ifdef _DEBUG
		pc->setCurrentDisplayedScalarField(sfIdx);
		pc->showSF(true);
#endif
	}

	//currently selected entities appearance may have changed!
	m_app->redrawAll();
}
Esempio n. 15
0
    MongoShellExecResult ScriptEngine::exec(const std::string &originalScript, const std::string &dbName)
    {
        QMutexLocker lock(&_mutex);

        if (!_scope) {
            _failedScope = true;
            return MongoShellExecResult(true, "Connection error. Uninitialized mongo scope.");
        }

        /*
         * Replace all commands ('show dbs', 'use db' etc.) with call
         * to shellHelper('show', 'dbs') and so on.
         */
        std::string stdstr(originalScript);

        pcrecpp::RE re("^(show|use|set) (\\w+)$",
            pcrecpp::RE_Options(PCRE_CASELESS|PCRE_MULTILINE|PCRE_NEWLINE_ANYCRLF));

        re.GlobalReplace("shellHelper('\\1', '\\2');", &stdstr);

        /*
         * Statementize (i.e. extract all JavaScript statements from script) and
         * execute each statement one by one
         */
        std::vector<std::string> statements;
        std::string error;
        bool result = statementize(stdstr, statements, error);

        if (!result && statements.size() == 0) {
            statements.push_back("print(__robomongoResult.error)");
        }

        std::vector<MongoShellResult> results;

        use(dbName);

        for (std::vector<std::string>::const_iterator it = statements.begin(); it != statements.end(); ++it)
        {
            std::string statement = *it;
            // clear global objects
            __objects.clear();
            __type = "";
            __finished = false;
            __logs.str("");

            if (true /* ! wascmd */) {
                try {
                    bool failed = false;
                    QElapsedTimer timer;
                    timer.start();
                    if ( _scope->exec( statement , "(shell)" , false , true , false, _timeoutSec * 1000) ) {
                         _scope->exec( "__robomongoLastRes = __lastres__; shellPrintHelper( __lastres__ );", 
                                      "(shell2)" , true , true , false, _timeoutSec * 1000);
                    }
                    else {  // failed to run script 
                        failed = true;                        
                    }

                    qint64 elapsed = timer.elapsed();

                    std::string logs = __logs.str();
                    std::string answer = logs.c_str();
                    std::string type = __type.c_str();

                    if (failed)
                        return MongoShellExecResult(true, answer);

                    std::vector<MongoDocumentPtr> docs = MongoDocument::fromBsonObj(__objects);

                    if (!answer.empty() || docs.size() > 0)
                        results.push_back(prepareResult(type, answer, docs, elapsed));
                }
                catch (const std::exception &e) {
                    std::cout << "error:" << e.what() << std::endl;
                }
            }
        }

        return prepareExecResult(results);
    }
Esempio n. 16
0
void Folder::bubbleUpSyncResult()
{
    // count new, removed and updated items
    int newItems = 0;
    int removedItems = 0;
    int updatedItems = 0;
    int ignoredItems = 0;
    int renamedItems = 0;

    SyncFileItem firstItemNew;
    SyncFileItem firstItemDeleted;
    SyncFileItem firstItemUpdated;
    SyncFileItem firstItemRenamed;
    Logger *logger = Logger::instance();

    SyncRunFileLog syncFileLog;

    syncFileLog.start(path(),  _engine->stopWatch() );

    QElapsedTimer timer;
    timer.start();

    foreach (const SyncFileItem &item, _syncResult.syncFileItemVector() ) {
        // Log the item
        syncFileLog.logItem( item );

        // and process the item to the gui
        if( item._status == SyncFileItem::FatalError || item._status == SyncFileItem::NormalError ) {
            slotSyncError( tr("%1: %2").arg(item._file, item._errorString) );
            logger->postOptionalGuiLog(item._file, item._errorString);
        } else {
            // add new directories or remove gone away dirs to the watcher
            if (item._isDirectory && item._instruction == CSYNC_INSTRUCTION_NEW ) {
                FolderMan::instance()->addMonitorPath( alias(), path()+item._file );
            }
            if (item._isDirectory && item._instruction == CSYNC_INSTRUCTION_REMOVE ) {
                FolderMan::instance()->removeMonitorPath( alias(), path()+item._file );
            }

            if (item._direction == SyncFileItem::Down) {
                switch (item._instruction) {
                case CSYNC_INSTRUCTION_NEW:
                    newItems++;
                    if (firstItemNew.isEmpty())
                        firstItemNew = item;
                    break;
                case CSYNC_INSTRUCTION_REMOVE:
                    removedItems++;
                    if (firstItemDeleted.isEmpty())
                        firstItemDeleted = item;
                    break;
                case CSYNC_INSTRUCTION_CONFLICT:
                case CSYNC_INSTRUCTION_SYNC:
                    updatedItems++;
                    if (firstItemUpdated.isEmpty())
                        firstItemUpdated = item;
                    break;
                case CSYNC_INSTRUCTION_ERROR:
                    qDebug() << "Got Instruction ERROR. " << _syncResult.errorString();
                    break;
                case CSYNC_INSTRUCTION_RENAME:
                    if (firstItemRenamed.isEmpty()) {
                        firstItemRenamed = item;
                    }
                    renamedItems++;
                    break;
                default:
                    // nothing.
                    break;
                }
            } else if( item._direction == SyncFileItem::None ) { // ignored files counting.
                if( item._instruction == CSYNC_INSTRUCTION_IGNORE ) {
                    ignoredItems++;
                }
            }
        }
    }
    syncFileLog.close();

    qDebug() << "Processing result list and logging took " << timer.elapsed() << " Milliseconds.";
    _syncResult.setWarnCount(ignoredItems);

    createGuiLog( firstItemNew._file,     FILE_STATUS_NEW, newItems );
    createGuiLog( firstItemDeleted._file, FILE_STATUS_REMOVE, removedItems );
    createGuiLog( firstItemUpdated._file, FILE_STATUS_UPDATED, updatedItems );

    if( !firstItemRenamed.isEmpty() ) {
        SyncFileStatus status = FILE_STATUS_RENAME;
        // if the path changes it's rather a move
        QDir renTarget = QFileInfo(firstItemRenamed._renameTarget).dir();
        QDir renSource = QFileInfo(firstItemRenamed._file).dir();
        if(renTarget != renSource) {
            status = FILE_STATUS_MOVE;
        }
        createGuiLog( firstItemRenamed._file, status, renamedItems, firstItemRenamed._renameTarget );
    }

    qDebug() << "OO folder slotSyncFinished: result: " << int(_syncResult.status());
}
Esempio n. 17
0
bool AssignmentThread::traditionalTaskPrepare()
{
    compileState = NoValidSourceFile;
    QDir contestantDir = QDir(Settings::sourcePath() + contestantName);
    QList<Compiler*> compilerList = settings->getCompilerList();
    
    for (int i = 0; i < compilerList.size(); i ++) {
        if (task->getCompilerConfiguration(compilerList[i]->getCompilerName()) == "disable") continue;
        QStringList filters = compilerList[i]->getSourceExtensions();
        for (int j = 0; j < filters.size(); j ++) {
            filters[j] = task->getSourceFileName() + "." + filters[j];
        }
        QStringList files = contestantDir.entryList(filters, QDir::Files);
        sourceFile = "";
        for (int j = 0; j < files.size(); j ++) {
            qint64 fileSize = QFileInfo(Settings::sourcePath() + contestantName + QDir::separator() + files[j]).size();
            if (fileSize <= settings->getFileSizeLimit() * 1024) {
                sourceFile = files[j];
                break;
            }
        }
        
        if (! sourceFile.isEmpty()) {
            QDir(Settings::temporaryPath()).mkdir(contestantName);
            QFile::copy(Settings::sourcePath() + contestantName + QDir::separator() + sourceFile,
                        Settings::temporaryPath() + contestantName + QDir::separator() + sourceFile);
            QStringList configurationNames = compilerList[i]->getConfigurationNames();
            QStringList compilerArguments = compilerList[i]->getCompilerArguments();
            QStringList interpreterArguments = compilerList[i]->getInterpreterArguments();
            QString currentConfiguration = task->getCompilerConfiguration(compilerList[i]->getCompilerName());
            for (int j = 0; j < configurationNames.size(); j ++) {
                if (configurationNames[j] == currentConfiguration) {
                    timeLimitRatio = compilerList[i]->getTimeLimitRatio();
                    memoryLimitRatio = compilerList[i]->getMemoryLimitRatio();
                    disableMemoryLimitCheck = compilerList[i]->getDisableMemoryLimitCheck();
                    environment = compilerList[i]->getEnvironment();
                    QStringList values = environment.toStringList();
                    for (int k = 0; k < values.size(); k ++) {
                        int tmp = values[k].indexOf("=");
                        QString variable = values[k].mid(0, tmp);
                        environment.insert(variable, 
                                           environment.value(variable) + ";"
                                           + QProcessEnvironment::systemEnvironment().value(variable));
                    }
                    
                    if (compilerList[i]->getCompilerType() == Compiler::Typical) {
#ifdef Q_OS_WIN32
                                executableFile = task->getSourceFileName() + ".exe";
#endif
#ifdef Q_OS_LINUX
                                executableFile = task->getSourceFileName();
#endif
                                interpreterFlag = false;
                    } else {
                        executableFile = compilerList[i]->getInterpreterLocation();
                        arguments = interpreterArguments[j];
                        arguments.replace("%s.*", sourceFile);
                        arguments.replace("%s", task->getSourceFileName());
                        interpreterFlag = true;
                    }
                    
                    if (compilerList[i]->getCompilerType() != Compiler::InterpretiveWithoutByteCode) {
                        QString arguments = compilerArguments[j];
                        arguments.replace("%s.*", sourceFile);
                        arguments.replace("%s", task->getSourceFileName());
                        QProcess *compiler = new QProcess(this);
                        compiler->setProcessChannelMode(QProcess::MergedChannels);
                        compiler->setProcessEnvironment(environment);
                        compiler->setWorkingDirectory(Settings::temporaryPath() + contestantName);
                        compiler->start(QString("\"") + compilerList[i]->getCompilerLocation() + "\" " + arguments);
                        if (! compiler->waitForStarted(-1)) {
                            compileState = InvalidCompiler;
                            delete compiler;
                            break;
                        }
                        QElapsedTimer timer;
                        timer.start();
                        bool flag = false;
                        while (timer.elapsed() < settings->getCompileTimeLimit()) {
                            if (compiler->state() != QProcess::Running) {
                                flag = true;
                                break;
                            }
                            QCoreApplication::processEvents();
                            if (stopJudging) {
                                compiler->kill();
                                delete compiler;
                                return false;
                            }
                            msleep(10);
                        }
                        if (! flag) {
                            compiler->kill();
                            compileState = CompileTimeLimitExceeded;
                        } else
                            if (compiler->exitCode() != 0) {
                                compileState = CompileError;
                                compileMessage = QString::fromLocal8Bit(compiler->readAllStandardOutput().data());
                            } else {
                                if (compilerList[i]->getCompilerType() == Compiler::Typical) {
                                    if (! QDir(Settings::temporaryPath() + contestantName).exists(executableFile)) {
                                        compileState = InvalidCompiler;
                                    } else {
                                        compileState = CompileSuccessfully;
                                    }
                                } else {
                                    QStringList filters = compilerList[i]->getBytecodeExtensions();
                                    for (int k = 0; k < filters.size(); k ++) {
                                        filters[k] = QString("*.") + filters[k];
                                    }
                                    if (QDir(Settings::temporaryPath() + contestantName)
                                            .entryList(filters, QDir::Files).size() == 0) {
                                        compileState = InvalidCompiler;
                                    } else {
                                        compileState = CompileSuccessfully;
                                    }
                                }
                            }
                        delete compiler;
                    }
                    
                    if (compilerList[i]->getCompilerType() == Compiler::InterpretiveWithoutByteCode)
                        compileState = CompileSuccessfully;
                    
                    break;
                }
            }
            break;
        }
    }
    
    if (compileState != CompileSuccessfully) {
        emit compileError(task->getTotalTimeLimit(), (int)compileState);
        return false;
    }
    
    return true;
}
Esempio n. 18
0
bool MSqlQuery::exec()
{
    if (!m_db)
    {
        // Database structure's been deleted
        return false;
    }

    if (m_last_prepared_query.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR,
            "MSqlQuery::exec(void) called without a prepared query.");
        return false;
    }

#if DEBUG_RECONNECT
    if (random() < RAND_MAX / 50)
    {
        LOG(VB_GENERAL, LOG_INFO,
            "MSqlQuery disconnecting DB to test reconnection logic");
        m_db->m_db.close();
    }
#endif

    // Database connection down.  Try to restart it, give up if it's still
    // down
    if (!m_db->isOpen() && !Reconnect())
    {
        LOG(VB_GENERAL, LOG_INFO, "MySQL server disconnected");
        return false;
    }

    QElapsedTimer timer;
    timer.start();

    bool result = QSqlQuery::exec();
    qint64 elapsed = timer.elapsed();

    // if the query failed with "MySQL server has gone away"
    // Close and reopen the database connection and retry the query if it
    // connects again
    if (!result && QSqlQuery::lastError().number() == 2006 && Reconnect())
        result = QSqlQuery::exec();

    if (!result)
    {
        QString err = MythDB::GetError("MSqlQuery", *this);
        MSqlBindings tmp = QSqlQuery::boundValues();
        bool has_null_strings = false;
        for (MSqlBindings::iterator it = tmp.begin(); it != tmp.end(); ++it)
        {
            if (it->type() != QVariant::String)
                continue;
            if (it->isNull() || it->toString().isNull())
            {
                has_null_strings = true;
                *it = QVariant(QString(""));
            }
        }
        if (has_null_strings)
        {
            bindValues(tmp);
            timer.restart();
            result = QSqlQuery::exec();
            elapsed = timer.elapsed();
        }
        if (result)
        {
            LOG(VB_GENERAL, LOG_ERR,
                QString("Original query failed, but resend with empty "
                        "strings in place of NULL strings worked. ") +
                "\n" + err);
        }
    }

    if (VERBOSE_LEVEL_CHECK(VB_DATABASE, LOG_INFO))
    {
        QString str = lastQuery();

        // Database logging will cause an infinite loop here if not filtered
        // out
        if (!str.startsWith("INSERT INTO logging "))
        {
            // Sadly, neither executedQuery() nor lastQuery() display
            // the values in bound queries against a MySQL5 database.
            // So, replace the named placeholders with their values.

            QMapIterator<QString, QVariant> b = boundValues();
            while (b.hasNext())
            {
                b.next();
                str.replace(b.key(), '\'' + b.value().toString() + '\'');
            }

            LOG(VB_DATABASE, LOG_INFO,
                QString("MSqlQuery::exec(%1) %2%3%4")
                        .arg(m_db->MSqlDatabase::GetConnectionName()).arg(str)
                        .arg(QString(" <<<< Took %1ms").arg(QString::number(elapsed)))
                        .arg(isSelect() ? QString(", Returned %1 row(s)")
                                              .arg(size()) : QString()));
        }
    }

    return result;
}
Esempio n. 19
0
void LVL_ModeFill::attemptFlood(LvlScene *scene)
{
    typedef QPair<qreal, qreal> CoorPair;

    //Stack overflow protection
    QElapsedTimer timer;
    timer.start();
    qint64 timeout=3000;

    LevelData historyBuffer;

    QPointF backUpPos;

    backUpPos = scene->cursor->scenePos();

    switch(scene->placingItem)
    {
    case LvlScene::PLC_Block:
        {
            QList<CoorPair> blackList; //items which don't pass the test anymore
            QList<CoorPair> nextList; //items to be checked next
            nextList << qMakePair<qreal, qreal>(scene->cursor->x(),scene->cursor->y());
            while(true)
            {
                QList<CoorPair> newList; //items to be checked next in the next loop
                foreach (CoorPair coor, nextList)
                {
                    if(blackList.contains(coor)) //don't check block in blacklist
                        continue;

                    scene->cursor->setPos(coor.first, coor.second);

                    if(!scene->itemCollidesWith(scene->cursor))
                    {
                        //place block if collision test
                        LvlPlacingItems::blockSet.x = coor.first;
                        LvlPlacingItems::blockSet.y = coor.second;
                        scene->LvlData->blocks_array_id++;

                        LvlPlacingItems::blockSet.array_id = scene->LvlData->blocks_array_id;
                        scene->LvlData->blocks.push_back(LvlPlacingItems::blockSet);

                        scene->placeBlock(LvlPlacingItems::blockSet, true);
                        historyBuffer.blocks.push_back(LvlPlacingItems::blockSet);
                        //expand on all sides
                        newList << qMakePair<qreal, qreal>(coor.first - LvlPlacingItems::blockSet.w,coor.second);
                        newList << qMakePair<qreal, qreal>(coor.first,coor.second - LvlPlacingItems::blockSet.h);
                        newList << qMakePair<qreal, qreal>(coor.first,coor.second + LvlPlacingItems::blockSet.h);
                        newList << qMakePair<qreal, qreal>(coor.first + LvlPlacingItems::blockSet.w,coor.second);
                    }
                    blackList << coor; //add current item to black list as it passed the test.
                }

                if(timer.elapsed() > timeout) break; //abort loop on time out

                if(newList.empty()) //if no blocks to add then break;
                    break;

                nextList = newList; //update next list
            }
        }
        break;
    case LvlScene::PLC_BGO:
        {
            QList<CoorPair> blackList; //items which don't pass the test anymore
            QList<CoorPair> nextList; //items to be checked next
            nextList << qMakePair<qreal, qreal>(scene->cursor->x(),scene->cursor->y());
            while(true)
            {
                QList<CoorPair> newList; //items to be checked next in the next loop
                foreach (CoorPair coor, nextList)
                {
                    if(blackList.contains(coor)) //don't check block in blacklist
                        continue;

                    scene->cursor->setPos(coor.first, coor.second);

                    if(!scene->itemCollidesWith(scene->cursor))
                    {
                        //place BGO if collision test
                        LvlPlacingItems::bgoSet.x = coor.first;
                        LvlPlacingItems::bgoSet.y = coor.second;
                        scene->LvlData->bgo_array_id++;

                        LvlPlacingItems::bgoSet.array_id = scene->LvlData->bgo_array_id;
                        scene->LvlData->bgo.push_back(LvlPlacingItems::bgoSet);

                        scene->placeBGO(LvlPlacingItems::bgoSet);
                        historyBuffer.bgo.push_back(LvlPlacingItems::bgoSet);
                        //expand on all sides
                        newList << qMakePair<qreal, qreal>(coor.first - LvlPlacingItems::itemW,coor.second);
                        newList << qMakePair<qreal, qreal>(coor.first,coor.second - LvlPlacingItems::itemH);
                        newList << qMakePair<qreal, qreal>(coor.first,coor.second + LvlPlacingItems::itemH);
                        newList << qMakePair<qreal, qreal>(coor.first + LvlPlacingItems::itemW,coor.second);
                    }
                    blackList << coor; //add current item to black list as it passed the test.
                }

                if(timer.elapsed() > timeout) break; //abort loop on time out

                if(newList.empty()) //if no blocks to add then break;
                    break;

                nextList = newList; //update next list
            }
        }
        break;
    default:
        break;
    }

    scene->cursor->setPos(backUpPos);

    if(
       historyBuffer.blocks.size()>0||
       historyBuffer.bgo.size()>0
            )

        scene->addPlaceHistory(historyBuffer);

}
void KItemListViewLayouter::doLayout()
{
    if (m_dirty) {
#ifdef KITEMLISTVIEWLAYOUTER_DEBUG
        QElapsedTimer timer;
        timer.start();
#endif
        m_visibleIndexesDirty = true;

        QSizeF itemSize = m_itemSize;
        QSizeF itemMargin = m_itemMargin;
        QSizeF size = m_size;

        const bool grouped = createGroupHeaders();

        const bool horizontalScrolling = (m_scrollOrientation == Qt::Horizontal);
        if (horizontalScrolling) {
            // Flip everything so that the layout logically can work like having
            // a vertical scrolling
            itemSize.transpose();
            itemMargin.transpose();
            size.transpose();

            if (grouped) {
                // In the horizontal scrolling case all groups are aligned
                // at the top, which decreases the available height. For the
                // flipped data this means that the width must be decreased.
                size.rwidth() -= m_groupHeaderHeight;
            }
        }

        m_columnWidth = itemSize.width() + itemMargin.width();
        const qreal widthForColumns = size.width() - itemMargin.width();
        m_columnCount = qMax(1, int(widthForColumns / m_columnWidth));
        m_xPosInc = itemMargin.width();

        const int itemCount = m_model->count();
        if (itemCount > m_columnCount && m_columnWidth >= 32) {
            // Apply the unused width equally to each column
            const qreal unusedWidth = widthForColumns - m_columnCount * m_columnWidth;
            if (unusedWidth > 0) {
                const qreal columnInc = unusedWidth / (m_columnCount + 1);
                m_columnWidth += columnInc;
                m_xPosInc += columnInc;
            }
        }

        int rowCount = itemCount / m_columnCount;
        if (itemCount % m_columnCount != 0) {
            ++rowCount;
        }

        m_itemInfos.resize(itemCount);

        qreal y = m_headerHeight + itemMargin.height();
        int row = 0;

        int index = 0;
        while (index < itemCount) {
            qreal x = m_xPosInc;
            qreal maxItemHeight = itemSize.height();

            if (grouped) {
                if (horizontalScrolling) {
                    // All group headers will always be aligned on the top and not
                    // flipped like the other properties
                    x += m_groupHeaderHeight;
                }

                if (m_groupItemIndexes.contains(index)) {
                    // The item is the first item of a group.
                    // Increase the y-position to provide space
                    // for the group header.
                    if (index > 0) {
                        // Only add a margin if there has been added another
                        // group already before
                        y += m_groupHeaderMargin;
                    } else if (!horizontalScrolling) {
                        // The first group header should be aligned on top
                        y -= itemMargin.height();
                    }

                    if (!horizontalScrolling) {
                        y += m_groupHeaderHeight;
                    }
                }
            }

            int column = 0;
            while (index < itemCount && column < m_columnCount) {
                qreal requiredItemHeight = itemSize.height();
                if (m_sizeHintResolver) {
                    const QSizeF sizeHint = m_sizeHintResolver->sizeHint(index);
                    const qreal sizeHintHeight = horizontalScrolling ? sizeHint.width() : sizeHint.height();
                    if (sizeHintHeight > requiredItemHeight) {
                        requiredItemHeight = sizeHintHeight;
                    }
                }

                ItemInfo& itemInfo = m_itemInfos[index];
                itemInfo.rect = QRectF(x, y, itemSize.width(), requiredItemHeight);
                itemInfo.column = column;
                itemInfo.row = row;

                if (grouped && horizontalScrolling) {
                    // When grouping is enabled in the horizontal mode, the header alignment
                    // looks like this:
                    //   Header-1 Header-2 Header-3
                    //   Item 1   Item 4   Item 7
                    //   Item 2   Item 5   Item 8
                    //   Item 3   Item 6   Item 9
                    // In this case 'requiredItemHeight' represents the column-width. We don't
                    // check the content of the header in the layouter to determine the required
                    // width, hence assure that at least a minimal width of 15 characters is given
                    // (in average a character requires the halve width of the font height).
                    //
                    // TODO: Let the group headers provide a minimum width and respect this width here
                    const qreal headerWidth = minimumGroupHeaderWidth();
                    if (requiredItemHeight < headerWidth) {
                        requiredItemHeight = headerWidth;
                    }
                }

                maxItemHeight = qMax(maxItemHeight, requiredItemHeight);
                x += m_columnWidth;
                ++index;
                ++column;

                if (grouped && m_groupItemIndexes.contains(index)) {
                    // The item represents the first index of a group
                    // and must aligned in the first column
                    break;
                }
            }

            y += maxItemHeight + itemMargin.height();
            ++row;
        }

        if (itemCount > 0) {
            // Calculate the maximum y-range of the last row for m_maximumScrollOffset
            m_maximumScrollOffset = m_itemInfos.last().rect.bottom();
            const qreal rowY = m_itemInfos.last().rect.y();

            int index = m_itemInfos.count() - 2;
            while (index >= 0 && m_itemInfos[index].rect.bottom() >= rowY) {
                m_maximumScrollOffset = qMax(m_maximumScrollOffset, m_itemInfos[index].rect.bottom());
                --index;
            }

            m_maximumScrollOffset += itemMargin.height();

            m_maximumItemOffset = m_columnCount * m_columnWidth;
        } else {
            m_maximumScrollOffset = 0;
            m_maximumItemOffset = 0;
        }

#ifdef KITEMLISTVIEWLAYOUTER_DEBUG
        kDebug() << "[TIME] doLayout() for " << m_model->count() << "items:" << timer.elapsed();
#endif
        m_dirty = false;
    }

    updateVisibleIndexes();
}
Esempio n. 21
0
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // Command Line Parser
    QCommandLineParser parser;
    parser.setApplicationDescription("Clustered Inverse Raw Example");
    parser.addHelpOption();

    QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", "./MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
    QCommandLineOption surfOption("surfType", "Surface type <type>.", "type", "inflated");
    QCommandLineOption annotOption("annotType", "Annotation type <type>.", "type", "aparc.a2009s");
    QCommandLineOption subjectOption("subject", "Selected subject <subject>.", "subject", "sample");
    QCommandLineOption subjectPathOption("subjectPath", "Selected subject path <subjectPath>.", "subjectPath", "./MNE-sample-data/subjects");
    QCommandLineOption fwdOption("fwd", "Path to forwad solution <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif");
    QCommandLineOption covFileOption("cov", "Path to the covariance <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-cov.fif");
    QCommandLineOption evokedIndexOption("aveIdx", "The average <index> to choose from the average file.", "index", "1");
    QCommandLineOption eventsFileOption("eve", "Path to the event <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis_raw-eve.fif");
    QCommandLineOption hemiOption("hemi", "Selected hemisphere <hemi>.", "hemi", "2");
    QCommandLineOption methodOption("method", "Inverse estimation <method>, i.e., 'MNE', 'dSPM' or 'sLORETA'.", "method", "dSPM");//"MNE" | "dSPM" | "sLORETA"
    QCommandLineOption snrOption("snr", "The SNR value used for computation <snr>.", "snr", "1.0");//3.0;//0.1;//3.0;
    QCommandLineOption invFileOutOption("invOut", "Path to inverse <file>, which is to be written.", "file", "");
    QCommandLineOption stcFileOutOption("stcOut", "Path to stc <file>, which is to be written.", "file", "");
    QCommandLineOption keepCompOption("keepComp", "Keep compensators.", "keepComp", "false");
    QCommandLineOption pickAllOption("pickAll", "Pick all channels.", "pickAll", "true");
    QCommandLineOption destCompsOption("destComps", "<Destination> of the compensator which is to be calculated.", "destination", "0");

    parser.addOption(inputOption);
    parser.addOption(surfOption);
    parser.addOption(annotOption);
    parser.addOption(subjectOption);
    parser.addOption(subjectPathOption);
    parser.addOption(fwdOption);
    parser.addOption(covFileOption);
    parser.addOption(evokedIndexOption);
    parser.addOption(eventsFileOption);
    parser.addOption(hemiOption);
    parser.addOption(methodOption);
    parser.addOption(snrOption);
    parser.addOption(invFileOutOption);
    parser.addOption(stcFileOutOption);
    parser.addOption(keepCompOption);
    parser.addOption(pickAllOption);
    parser.addOption(destCompsOption);

    parser.process(a);

    // Load files
    QFile t_fileFwd(parser.value(fwdOption));
    QFile t_fileCov(parser.value(covFileOption));
    QFile t_fileRaw(parser.value(inputOption));
    QString t_sEventName = parser.value(eventsFileOption);

    SurfaceSet t_surfSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(surfOption), parser.value(subjectPathOption));
    AnnotationSet t_annotationSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(annotOption), parser.value(subjectPathOption));

    qint32 event = parser.value(evokedIndexOption).toInt();

    float tmin = -0.2f;
    float tmax = 0.4f;

    bool keep_comp = false;
    if(parser.value(keepCompOption) == "false" || parser.value(keepCompOption) == "0") {
        keep_comp = false;
    } else if(parser.value(keepCompOption) == "true" || parser.value(keepCompOption) == "1") {
        keep_comp = true;
    }

    fiff_int_t dest_comp = parser.value(destCompsOption).toInt();

    bool pick_all = false;
    if(parser.value(pickAllOption) == "false" || parser.value(pickAllOption) == "0") {
        pick_all = false;
    } else if(parser.value(pickAllOption) == "true" || parser.value(pickAllOption) == "1") {
        pick_all = true;
    }

    qint32 k, p;

    //
    //   Setup for reading the raw data
    //
    FiffRawData raw(t_fileRaw);

    RowVectorXi picks;
    if (pick_all)
    {
        //
        // Pick all
        //
        picks.resize(raw.info.nchan);

        for(k = 0; k < raw.info.nchan; ++k)
            picks(k) = k;
        //
    }
    else
    {
        QStringList include;
        include << "STI 014";
        bool want_meg   = true;
        bool want_eeg   = false;
        bool want_stim  = false;

//        picks = Fiff::pick_types(raw.info, want_meg, want_eeg, want_stim, include, raw.info.bads);
        picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);//prefer member function
    }

    QStringList ch_names;
    for(k = 0; k < picks.cols(); ++k)
        ch_names << raw.info.ch_names[picks(0,k)];

    //
    //   Set up projection
    //
    if (raw.info.projs.size() == 0)
        printf("No projector specified for these data\n");
    else
    {
        //
        //   Activate the projection items
        //
        for (k = 0; k < raw.info.projs.size(); ++k)
            raw.info.projs[k].active = true;

        printf("%d projection items activated\n",raw.info.projs.size());
        //
        //   Create the projector
        //
//        fiff_int_t nproj = MNE::make_projector_info(raw.info, raw.proj); Using the member function instead
        fiff_int_t nproj = raw.info.make_projector(raw.proj);

        if (nproj == 0)
        {
            printf("The projection vectors do not apply to these channels\n");
        }
        else
        {
            printf("Created an SSP operator (subspace dimension = %d)\n",nproj);
        }
    }

    //
    //   Set up the CTF compensator
    //
//    qint32 current_comp = MNE::get_current_comp(raw.info);
    qint32 current_comp = raw.info.get_current_comp();
    if (current_comp > 0)
        printf("Current compensation grade : %d\n",current_comp);

    if (keep_comp)
        dest_comp = current_comp;

    if (current_comp != dest_comp)
    {
        qDebug() << "This part needs to be debugged";
        if(MNE::make_compensator(raw.info, current_comp, dest_comp, raw.comp))
        {
//            raw.info.chs = MNE::set_current_comp(raw.info.chs,dest_comp);
            raw.info.set_current_comp(dest_comp);
            printf("Appropriate compensator added to change to grade %d.\n",dest_comp);
        }
        else
        {
            printf("Could not make the compensator\n");
            return 0;
        }
    }
    //
    //  Read the events
    //
    QFile t_EventFile;
    MatrixXi events;
    if (t_sEventName.size() == 0)
    {
        p = t_fileRaw.fileName().indexOf(".fif");
        if (p > 0)
        {
            t_sEventName = t_fileRaw.fileName().replace(p, 4, "-eve.fif");
        }
        else
        {
            printf("Raw file name does not end properly\n");
            return 0;
        }
//        events = mne_read_events(t_sEventName);

        t_EventFile.setFileName(t_sEventName);
        MNE::read_events(t_EventFile, events);
        printf("Events read from %s\n",t_sEventName.toUtf8().constData());
    }
    else
    {
        //
        //   Binary file
        //
        p = t_fileRaw.fileName().indexOf(".fif");
        if (p > 0)
        {
            t_EventFile.setFileName(t_sEventName);
            if(!MNE::read_events(t_EventFile, events))
            {
                printf("Error while read events.\n");
                return 0;
            }
            printf("Binary event file %s read\n",t_sEventName.toUtf8().constData());
        }
        else
        {
            //
            //   Text file
            //
            printf("Text file %s is not supported jet.\n",t_sEventName.toUtf8().constData());
//            try
//                events = load(eventname);
//            catch
//                error(me,mne_omit_first_line(lasterr));
//            end
//            if size(events,1) < 1
//                error(me,'No data in the event file');
//            end
//            //
//            //   Convert time to samples if sample number is negative
//            //
//            for p = 1:size(events,1)
//                if events(p,1) < 0
//                    events(p,1) = events(p,2)*raw.info.sfreq;
//                end
//            end
//            //
//            //    Select the columns of interest (convert to integers)
//            //
//            events = int32(events(:,[1 3 4]));
//            //
//            //    New format?
//            //
//            if events(1,2) == 0 && events(1,3) == 0
//                fprintf(1,'The text event file %s is in the new format\n',eventname);
//                if events(1,1) ~= raw.first_samp
//                    error(me,'This new format event file is not compatible with the raw data');
//                end
//            else
//                fprintf(1,'The text event file %s is in the old format\n',eventname);
//                //
//                //   Offset with first sample
//                //
//                events(:,1) = events(:,1) + raw.first_samp;
//            end
        }
    }

    //
    //    Select the desired events
    //
    qint32 count = 0;
    MatrixXi selected = MatrixXi::Zero(1, events.rows());
    for (p = 0; p < events.rows(); ++p)
    {
        if (events(p,1) == 0 && events(p,2) == event)
        {
            selected(0,count) = p;
            ++count;
        }
    }
    selected.conservativeResize(1, count);
    if (count > 0)
        printf("%d matching events found\n",count);
    else
    {
        printf("No desired events found.\n");
        return 0;
    }


    fiff_int_t event_samp, from, to;
    MatrixXd timesDummy;

    MNEEpochDataList data;

    MNEEpochData* epoch = NULL;

    MatrixXd times;

    for (p = 0; p < count; ++p)
    {
        //
        //       Read a data segment
        //
        event_samp = events(selected(p),0);
        from = event_samp + tmin*raw.info.sfreq;
        to   = event_samp + floor(tmax*raw.info.sfreq + 0.5);

        epoch = new MNEEpochData();

        if(raw.read_raw_segment(epoch->epoch, timesDummy, from, to, picks))
        {
            if (p == 0)
            {
                times.resize(1, to-from+1);
                for (qint32 i = 0; i < times.cols(); ++i)
                    times(0, i) = ((float)(from-event_samp+i)) / raw.info.sfreq;
            }

            epoch->event = event;
            epoch->tmin = ((float)(from)-(float)(raw.first_samp))/raw.info.sfreq;
            epoch->tmax = ((float)(to)-(float)(raw.first_samp))/raw.info.sfreq;

            data.append(MNEEpochData::SPtr(epoch));//List takes ownwership of the pointer - no delete need
        }
        else
        {
            printf("Can't read the event data segments");
            return 0;
        }
    }

    if(data.size() > 0)
    {
        printf("Read %d epochs, %d samples each.\n",data.size(),(qint32)data[0]->epoch.cols());

        //DEBUG
        std::cout << data[0]->epoch.block(0,0,10,10) << std::endl;
        qDebug() << data[0]->epoch.rows() << " x " << data[0]->epoch.cols();

        std::cout << times.block(0,0,1,10) << std::endl;
        qDebug() << times.rows() << " x " << times.cols();
    }

    // Calculate the average
    // Option 1 - Random selection
    VectorXi vecSel(50);
    srand (time(NULL)); // initialize random seed

    for(qint32 i = 0; i < vecSel.size(); ++i)
    {
        qint32 val = rand() % count;
        vecSel(i) = val;
    }

//    //Option 3 - Take all epochs
//    VectorXi vecSel(data.size());

//    for(qint32 i = 0; i < vecSel.size(); ++i)
//    {
//        vecSel(i) = i;
//    }

//    //Option 3 - Manual selection
//    VectorXi vecSel(20);

//    vecSel << 76, 74, 13, 61, 97, 94, 75, 71, 60, 56, 26, 57, 56, 0, 52, 72, 33, 86, 96, 67;

    std::cout << "Select following epochs to average:\n" << vecSel << std::endl;

    FiffEvoked evoked = data.average(raw.info, tmin*raw.info.sfreq, floor(tmax*raw.info.sfreq + 0.5), vecSel);

    //########################################################################################
    // Source Estimate

    //
    // Settings
    //
    double snr = parser.value(snrOption).toDouble();
    QString method(parser.value(methodOption));

    QString t_sFileNameClusteredInv(parser.value(invFileOutOption));
    QString t_sFileNameStc(parser.value(stcFileOutOption));

    double lambda2 = 1.0 / pow(snr, 2);
    qDebug() << "Start calculation with: SNR" << snr << "; Lambda" << lambda2 << "; Method" << method << "; stc:" << t_sFileNameStc;

    //
    // Load data
    //
    MNEForwardSolution t_Fwd(t_fileFwd);
    if(t_Fwd.isEmpty())
        return 1;

    FiffCov noise_cov(t_fileCov);

    //
    // regularize noise covariance
    //
    noise_cov = noise_cov.regularize(evoked.info, 0.05, 0.05, 0.1, true);

    //
    // Cluster forward solution;
    //
    MatrixXd D;
    MNEForwardSolution t_clusteredFwd = t_Fwd.cluster_forward_solution(t_annotationSet, 20, D, noise_cov, evoked.info);

    //
    // make an inverse operators
    //
    FiffInfo info = evoked.info;

    MNEInverseOperator inverse_operator(info, t_clusteredFwd, noise_cov, 0.2f, 0.8f);

    //
    // save clustered inverse
    //
    if(!t_sFileNameClusteredInv.isEmpty())
    {
        QFile t_fileClusteredInverse(t_sFileNameClusteredInv);
        inverse_operator.write(t_fileClusteredInverse);
    }

    //
    // Compute inverse solution
    //
    MinimumNorm minimumNorm(inverse_operator, lambda2, method);

#ifdef BENCHMARK
    //
    //   Set up the inverse according to the parameters
    //
    minimumNorm.doInverseSetup(vecSel.size(),false);

    MNESourceEstimate sourceEstimate;
    QList<qint64> qVecElapsedTime;
    for(qint32 i = 0; i < 100; ++i)
    {
        //Benchmark time
        QElapsedTimer timer;
        timer.start();
        sourceEstimate = minimumNorm.calculateInverse(evoked.data, evoked.times(0), evoked.times(1)-evoked.times(0));
        qVecElapsedTime.append(timer.elapsed());
    }

    double meanTime = 0.0;
    qint32 offset = 19;
    qint32 c = 0;
    for(qint32 i = offset; i < qVecElapsedTime.size(); ++i)
    {
        meanTime += qVecElapsedTime[i];
        ++c;
    }

    meanTime /= (double)c;

    double varTime = 0;
    for(qint32 i = offset; i < qVecElapsedTime.size(); ++i)
        varTime += pow(qVecElapsedTime[i] - meanTime,2);

    varTime /= (double)c - 1.0f;
    varTime = sqrt(varTime);

    qDebug() << "MNE calculation took" << meanTime << "+-" << varTime << "ms in average";

#else
    MNESourceEstimate sourceEstimate = minimumNorm.calculateInverse(evoked);
#endif

    if(sourceEstimate.isEmpty())
        return 1;

    // View activation time-series
    std::cout << "\nsourceEstimate:\n" << sourceEstimate.data.block(0,0,10,10) << std::endl;
    std::cout << "time\n" << sourceEstimate.times.block(0,0,1,10) << std::endl;
    std::cout << "timeMin\n" << sourceEstimate.times[0] << std::endl;
    std::cout << "timeMax\n" << sourceEstimate.times[sourceEstimate.times.size()-1] << std::endl;
    std::cout << "time step\n" << sourceEstimate.tstep << std::endl;

    //Condition Numbers
//    MatrixXd mags(102, t_Fwd.sol->data.cols());
//    qint32 count = 0;
//    for(qint32 i = 2; i < 306; i += 3)
//    {
//        mags.row(count) = t_Fwd.sol->data.row(i);
//        ++count;
//    }
//    MatrixXd magsClustered(102, t_clusteredFwd.sol->data.cols());
//    count = 0;
//    for(qint32 i = 2; i < 306; i += 3)
//    {
//        magsClustered.row(count) = t_clusteredFwd.sol->data.row(i);
//        ++count;
//    }

//    MatrixXd grads(204, t_Fwd.sol->data.cols());
//    count = 0;
//    for(qint32 i = 0; i < 306; i += 3)
//    {
//        grads.row(count) = t_Fwd.sol->data.row(i);
//        ++count;
//        grads.row(count) = t_Fwd.sol->data.row(i+1);
//        ++count;
//    }
//    MatrixXd gradsClustered(204, t_clusteredFwd.sol->data.cols());
//    count = 0;
//    for(qint32 i = 0; i < 306; i += 3)
//    {
//        gradsClustered.row(count) = t_clusteredFwd.sol->data.row(i);
//        ++count;
//        gradsClustered.row(count) = t_clusteredFwd.sol->data.row(i+1);
//        ++count;
//    }

    VectorXd s;

    double t_dConditionNumber = MNEMath::getConditionNumber(t_Fwd.sol->data, s);
    double t_dConditionNumberClustered = MNEMath::getConditionNumber(t_clusteredFwd.sol->data, s);

    std::cout << "Condition Number:\n" << t_dConditionNumber << std::endl;
    std::cout << "Clustered Condition Number:\n" << t_dConditionNumberClustered << std::endl;

    std::cout << "ForwardSolution" << t_Fwd.sol->data.block(0,0,10,10) << std::endl;

    std::cout << "Clustered ForwardSolution" << t_clusteredFwd.sol->data.block(0,0,10,10) << std::endl;


//    double t_dConditionNumberMags = MNEMath::getConditionNumber(mags, s);
//    double t_dConditionNumberMagsClustered = MNEMath::getConditionNumber(magsClustered, s);

//    std::cout << "Condition Number Magnetometers:\n" << t_dConditionNumberMags << std::endl;
//    std::cout << "Clustered Condition Number Magnetometers:\n" << t_dConditionNumberMagsClustered << std::endl;

//    double t_dConditionNumberGrads = MNEMath::getConditionNumber(grads, s);
//    double t_dConditionNumberGradsClustered = MNEMath::getConditionNumber(gradsClustered, s);

//    std::cout << "Condition Number Gradiometers:\n" << t_dConditionNumberGrads << std::endl;
//    std::cout << "Clustered Condition Number Gradiometers:\n" << t_dConditionNumberGradsClustered << std::endl;


    //Source Estimate end
    //########################################################################################

//    //only one time point - P100
//    qint32 sample = 0;
//    for(qint32 i = 0; i < sourceEstimate.times.size(); ++i)
//    {
//        if(sourceEstimate.times(i) >= 0)
//        {
//            sample = i;
//            break;
//        }
//    }
//    sample += (qint32)ceil(0.106/sourceEstimate.tstep); //100ms
//    sourceEstimate = sourceEstimate.reduce(sample, 1);

    View3D::SPtr testWindow = View3D::SPtr(new View3D());
    Data3DTreeModel::SPtr p3DDataModel = Data3DTreeModel::SPtr(new Data3DTreeModel());
    testWindow->setModel(p3DDataModel);

    p3DDataModel->addSurfaceSet(parser.value(subjectOption), "MRI", t_surfSet, t_annotationSet);

    if(MneEstimateTreeItem* pRTDataItem = p3DDataModel->addSourceData(parser.value(subjectOption), evoked.comment, sourceEstimate, t_clusteredFwd)) {
        pRTDataItem->setLoopState(true);
        pRTDataItem->setTimeInterval(17);
        pRTDataItem->setNumberAverages(1);
        pRTDataItem->setStreamingActive(true);
        pRTDataItem->setNormalization(QVector3D(0.0,0.5,20.0));
        pRTDataItem->setVisualizationType("Smoothing based");
        pRTDataItem->setColortable("Hot");
    }

    testWindow->show();

    Control3DWidget::SPtr control3DWidget = Control3DWidget::SPtr(new Control3DWidget());
    control3DWidget->init(p3DDataModel, testWindow);
    control3DWidget->show();

    if(!t_sFileNameStc.isEmpty())
    {
        QFile t_fileClusteredStc(t_sFileNameStc);
        sourceEstimate.write(t_fileClusteredStc);
    }

    return a.exec();
}
Esempio n. 22
0
void SkpTcpSocketProtocol::skp_on_simple_recv()
{
    do {
        QByteArray arr = readAll();
        array.append(arr);
        if(!SkpCheckHead(array.data(), array.size())) {
            //qDebug() << "SkpCheckHead return";
            return;
        }

        SkpProtocalHead *ask = (SkpProtocalHead *)array.data();
        m_tlvRecv->reset();
        m_tlvRecv->copy(array.data(), ask->dataSize, ask->headSize);
        int dataSize = m_tlvRecv->seek(_Tag_System_Test);
        //qDebug() << "_Tag_System_Test" << dataSize;
        char *data = m_tlvRecv->seek_value();

        //qDebug() << "recv++++++++++++++++++++++++++++";
        //qDebug() << ask->send << ask->recv << ask->dataSize << ask->headSize;
        array.remove(0, ask->headSize + ask->dataSize);
        QByteArray arryData(data, dataSize);

        //qDebug() << arryData.size() << arryData.data();
        int i;
        bool isBreak = false;
        for(i = 0; i < gList.size(); i++) {
            QByteArray arryDataSend = gList.at(i);
            //qDebug() << arryDataSend.size() << arryDataSend.data();
            if(arryData == arryDataSend) {
                gList.removeAt(i);
                isBreak = true;
                break;
            }
        }

        if(!isBreak) {
            qDebug() << "error";
            QApplication::exit(1);
            return;
        }


//        if((dataSize = m_tlvRecv->seek(_Tag_Data)))
//        {
//            do
//            {
//                m_tlvRecvInfo->reset_TLV();
//                m_tlvRecvInfo->copy(m_tlvRecv->seek_value(), dataSize, 0);
//                int userID = m_tlvRecvInfo->seek_int(_Tag_UserID);
//                int serverID = m_tlvRecvInfo->seek_int(_Tag_ServerID);
//                int password = m_tlvRecvInfo->seek(_Tag_Password);
//                char *value = m_tlvRecvInfo->seek_value();
//                //QByteArray arryData(value, password);
//                //qDebug() << userID << serverID << arryData.data() << password;
//                //qDebug() << "_Tag_Data" << dataSize;
//            } while(m_tlvRecv->next());
//        }


        //            QByteArray arryDataSend = gList.takeFirst();
        //            if(arryData != arryDataSend) {
        //                qDebug() << "arryData != arryDataSend";
        //                qDebug() << arryDataSend.size() << arryDataSend.data();
        //                QApplication::exit(1);
        //                return;
        //            }


        sendNumber--;
        recvNumber++;
        allRecvNumber++;
        if(allRecvNumber % 1000 == 0)
        {
            qDebug() << "sendNumber = " << sendNumber << "connNumber = " << connNumber << "closeNumber = " << clostNumber << (uint)this << "recvNumber" << recvNumber << "allRecvNumber" << allRecvNumber;
            qint64 time = timer.elapsed();
            time = time / 1000;
            if(time == 0)
                time = 1;
            qDebug() << "allRecvNumber " << allRecvNumber << "time" << time << "sec" << allRecvNumber / time;
        }
    }while(array.size() > 0);

    if(sendNumber == 0) {
        if(SIGNAL_SEND)
            skp_on_simple_send();
    }

    if(sendNumber < 0){
        qDebug() << "send number error";
        QApplication::exit(1);
        return;
    }

}
///
/// \brief returns milliseconds elapsed from last call to timer_start
/// \return
///
inline long timer_elapsed_ms(){
    return (long)timer.elapsed();
}
Esempio n. 24
0
// Launch a simulation given the method, creates a log file and an info window at the end
void MainWindow::Simu(int method){
    first_simu = true;
    double errgomne=0;
    int cpt=0,cpt2=0;
    cantlocalize=0;
    nboutlier = 0;
    errpos.clear();
    par->box.clear();
    par->box.push_back(IntervalVector(3,Interval(-25,25)));
    ui->checkBox->setChecked(false);
    for(int i=0;i<par->nb_beacon;i++){
        par->x[i]= 1*(25 - rand() % 50);
        par->y[i]= 1*(25 - rand() % 50);
        par->z[i]= 5-i%4;
        par->theta_sonar[i] = rand() % 360;
        if((rand() % 100) <= probsensorfalse){
            if (rand() % 1 ==1)
                par->outliers[i]=1;
            else par->outliers[i]=-1;
            nboutlier++;
        }
        else{par->outliers[i]=0;}
    }
    ui->nbOutlierlcd->display(nboutlier);
    par->nb_beacon = ui->BeaconSpinBox->value();
    //Log
    ofstream myfile;
    myfile.open ("log_simu.txt");
    remove("log_simu.txt");
    myfile.close();
    myfile.open ("log_simu.txt");
    QString vt = "";
    QElapsedTimer tsimu;
    int gomnecpt=0;
    tsimu.start();
    step=ui->step_SpinBox->value();
    for(double i=0;i<6500;i=i+step) cpt2++;
    par->ratio_area.clear();
    par->areain=0;
    par->areap=0;
    for(double i=0;i<6500;i=i+step){
        //cout<<"entry box :"<<par->box.back()<<endl;
        QElapsedTimer tcur;
        QString vtcur = "";
        tcur.start();
        t=i;
        par->iteration=t;
        if(method==1)   on_ButtonFindSol_clicked();
        if (method==2)  on_ButtonGOMNE_clicked();
        if(method==3) {
            int qtmp=par->q;
            on_ButtonGOMNE_clicked();
            SLAM(step);
            if (par->q==qtmp) gomnecpt++;
            //if (gomnecpt>4) method=4;
        }
        if(method==4) GOMNE_fixed_q();
        errgomne += fabs(double(par->q-(double(par->nb_beacon) -  double(nboutlier))) / (double(par->nb_beacon) -  double(nboutlier))*100);
        ui->TSlider->setValue(t);
        Zoom(step);
        delay();
        vtcur = QString::number(tcur.elapsed());
        vt.append(vtcur);vt.append("ms ; ");
        myfile << vtcur.toUtf8().constData();myfile << "\n";
        if(ui->StopSimu->isDown())  break;
        cpt++;
    }
    double errpercoutliergomne = double(errgomne)/double(cpt);
    myfile.close();
    QString mess = "Execution time : ";
    double exec = tsimu.elapsed();
    mess.append(QString::number(exec));mess.append(" ms\n");
    mess.append(vt);mess.append(" ms\n");
    double cerpos=0;
    double i=0;
    vector<double> vcerpos;
    while (!errpos.empty()){
        cerpos+=errpos.back();
        i++;
        vcerpos.push_back(cerpos);
        errpos.pop_back();
    }
    double mean= cerpos/i;
    cerpos = 0;
    while(!vcerpos.empty()){
        cerpos+=pow(vcerpos.back()-mean,2);
        vcerpos.pop_back();
    }
    cerpos/=i;
    double area=0;
    for (size_t ii = 0; ii < par->ratio_area.size(); ii++){  area += par->ratio_area[ii];
    //cout<<par->ratio_area[ii]<<endl;
    }
    area/=par->ratio_area.size();
    cantlocalize/=cpt;cantlocalize*=100;

    mess.append(QString::number(cerpos));mess.append("\n");//mess.append(" variance (pixel)");
    mess.append(QString::number(mean));mess.append("\n");//mess.append(" average error (pixel)\n");
    mess.append(QString::number(exec));mess.append("\n");
    mess.append(QString::number(errpercoutliergomne));mess.append("\n");
    mess.append(QString::number(area));mess.append("\n");
    mess.append(QString::number(cantlocalize));mess.append("\n");
    QMessageBox::information(this,"End of Simulation",mess);
}
Esempio n. 25
0
bool QHttpSocketEngine::waitForWrite(int msecs, bool *timedOut)
{
    Q_D(const QHttpSocketEngine);

    // If we're connected, just forward the call.
    if (d->state == Connected) {
        if (d->socket->bytesToWrite()) {
            if (!d->socket->waitForBytesWritten(msecs)) {
                if (d->socket->error() == QAbstractSocket::SocketTimeoutError && timedOut)
                    *timedOut = true;
                return false;
            }
        }
        return true;
    }

    QElapsedTimer stopWatch;
    stopWatch.start();

    // If we're not connected yet, wait until we are, and until bytes have
    // been received (i.e., the socket has connected, we have sent the
    // greeting, and then received the response).
    while (d->state != Connected && d->socket->waitForReadyRead(qt_timeout_value(msecs, stopWatch.elapsed()))) {
        // Loop while the protocol handshake is taking place.
    }

    // Report any error that may occur.
    if (d->state != Connected) {
//        setError(d->socket->error(), d->socket->errorString());
        if (timedOut && d->socket->error() == QAbstractSocket::SocketTimeoutError)
            *timedOut = true;
    }

    return true;
}
Esempio n. 26
0
// Call simulation 'Soft Constraints'
void MainWindow::on_ButtonFindSol_clicked()
{
    if (first_simu == false){
        QMessageBox::warning(this,"Abort process",
        "To run the alogrithm at a given time, first you need to run a simulation.\nYou can stop it before the end by holding the STOP button.\nYour current simulation will end.");
        Simu(1);
    }
    QElapsedTimer timer;
    timer.start();
    RobotTraj();
    Init();
    ui->EpsilonSpinBox->setValue(0.5);
    if(ui->BeaconSpinBox->value()!=5)
        QMessageBox::warning(this,"Attention","This method only works with 5 beacons. Now running simulation with 5 beacons.\n Press Ok to continue...");
    ui->BeaconSpinBox->setValue(5);
    ui->InterSpinBox->setValue(par->nb_beacon);

    for (uint i=0;i<(sizeof(par->err)/sizeof(*par->err));i++){
       par->err[i] = 0.00;
    }
    Sivia sivia(*R,par);
    uint i=0;
    //double startstep=0.05+floor(10*par->epsilon_sivia)/10-floor(10*par->epsilon_sivia)/20;
    double startstep=1;
    double pas = 0.5*(1+par->erroutlier/10);
    int nstep = 2;
    int stepctr=0;

    while(pas>0.05){
        int forw=0;
        int back=0;

        while(par->isinside==1){
            for (uint j=0;j<par->nb_beacon;j++){
                par->err[j]=startstep;
                if(i==j) par->err[j]=startstep-((stepctr+1))*pas;
            }

            Sivia sivia(*R,par);
            stepctr=(stepctr+1)%nstep;
            if (stepctr==0){
                i++;
                i = i % par->nb_beacon;
                if(i==0)    startstep=startstep-pas;
            }
            back++;
        }
       // qDebug()<<"err back: "<<"is "<<par->err[0]<<";"<<par->err[1]<<";"<<par->err[2]<<";"<<par->err[3]<<";"<<par->err[4]<<endl;

        while(par->isinside==0){

            for (uint j=0;j<par->nb_beacon;j++){
                par->err[j]=startstep;
                if(i==j) par->err[j]=startstep+((stepctr+1))*pas;
            }

            Sivia sivia(*R,par);
            stepctr=(stepctr+1)%nstep;
            if (stepctr==0){
                i++;
                i = i % par->nb_beacon;
                if(i==0)    startstep=startstep+pas;
            }
            forw++;
        }
        //qDebug()<<"par->err for: "<<"is "<<par->err[0]<<";"<<par->err[1]<<";"<<par->err[2]<<";"<<par->err[3]<<";"<<par->err[4]<<endl;
        if(back>forw)
            startstep/=0.5;
        else
            startstep*=0.5;
        //cout<<"pas "<<pas<<endl;
        pas/=2;

    }
    ui->ErrSpinBox_1->setValue(par->err[0]);
    ui->ErrSpinBox_2->setValue(par->err[1]);
    ui->ErrSpinBox_3->setValue(par->err[2]);
    ui->ErrSpinBox_4->setValue(par->err[3]);
    ui->ErrSpinBox_5->setValue(par->err[4]);
    repaint();

    if (timeinfo){
        QString mess = "Execution time : ";
        mess.append(QString::number(timer.elapsed()));mess.append(" ms");
        QMessageBox::information(this,"Info",mess);
    }
}
void ScriptJob::run()
{
    m_mutex->lock();
    if ( !loadScript(&m_data.program) ) {
        kDebug() << "Script could not be loaded correctly";
        m_mutex->unlock();
        return;
    }

    QScriptEngine *engine = m_engine;
    ScriptObjects objects = m_objects;
    m_mutex->unlock();

    // Store start time of the script
    QElapsedTimer timer;
    timer.start();

    // Add call to the appropriate function
    QString functionName;
    QScriptValueList arguments = QScriptValueList() << request()->toScriptValue( engine );
    switch ( request()->parseMode() ) {
    case ParseForDepartures:
    case ParseForArrivals:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETTIMETABLE;
        break;
    case ParseForJourneysByDepartureTime:
    case ParseForJourneysByArrivalTime:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETJOURNEYS;
        break;
    case ParseForStopSuggestions:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETSTOPSUGGESTIONS;
        break;
    case ParseForAdditionalData:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETADDITIONALDATA;
        break;
    default:
        kDebug() << "Parse mode unsupported:" << request()->parseMode();
        break;
    }

    if ( functionName.isEmpty() ) {
        // This should never happen, therefore no i18n
        handleError( "Unknown parse mode" );
        return;
    }

    // Check if the script function is implemented
    QScriptValue function = engine->globalObject().property( functionName );
    if ( !function.isFunction() ) {
        handleError( i18nc("@info/plain", "Function <icode>%1</icode> not implemented by "
                           "the script", functionName) );
        return;
    }

    // Call script function
    QScriptValue result = function.call( QScriptValue(), arguments );
    if ( engine->hasUncaughtException() ) {
        // TODO Get filename where the exception occured, maybe use ScriptAgent for that
        handleError( i18nc("@info/plain", "Error in script function <icode>%1</icode>, "
                           "line %2: <message>%3</message>.",
                           functionName, engine->uncaughtExceptionLineNumber(),
                           engine->uncaughtException().toString()) );
        return;
    }

    GlobalTimetableInfo globalInfo;
    globalInfo.requestDate = QDate::currentDate();
    globalInfo.delayInfoAvailable = !objects.result->isHintGiven( ResultObject::NoDelaysForStop );

    // The called function returned, but asynchronous network requests may have been started.
    // Wait for all network requests to finish, because slots in the script may get called
    if ( !waitFor(objects.network.data(), SIGNAL(allRequestsFinished()), WaitForNetwork) ) {
        return;
    }

    // Wait for script execution to finish
    ScriptAgent agent( engine );
    if ( !waitFor(&agent, SIGNAL(scriptFinished()), WaitForScriptFinish) ) {
        return;
    }

    // Update last download URL
    QMutexLocker locker( m_mutex );
    m_lastUrl = objects.network->lastUrl(); // TODO Store all URLs
    m_lastUserUrl = objects.network->lastUserUrl();

    // Inform about script run time
    DEBUG_ENGINE_JOBS( "Script finished in" << (timer.elapsed() / 1000.0)
            << "seconds: " << m_data.provider.scriptFileName() << request()->parseMode() );

    // If data for the current job has already been published, do not emit
    // xxxReady() with an empty resultset
    if ( m_published == 0 || m_objects.result->count() > m_published ) {
        const bool couldNeedForcedUpdate = m_published > 0;
        const MoreItemsRequest *moreItemsRequest =
                dynamic_cast< const MoreItemsRequest* >( request() );
        const AbstractRequest *_request =
                moreItemsRequest ? moreItemsRequest->request().data() : request();
        switch ( _request->parseMode() ) {
        case ParseForDepartures:
            emit departuresReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const DepartureRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        case ParseForArrivals: {
            emit arrivalsReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast< const ArrivalRequest* >(_request),
                    couldNeedForcedUpdate );
            break;
        }
        case ParseForJourneysByDepartureTime:
        case ParseForJourneysByArrivalTime:
            emit journeysReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const JourneyRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        case ParseForStopSuggestions:
            emit stopSuggestionsReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const StopSuggestionRequest*>(_request),
                    couldNeedForcedUpdate );
            break;

        case ParseForAdditionalData: {
            const QList< TimetableData > data = m_objects.result->data();
            if ( data.isEmpty() ) {
                handleError( i18nc("@info/plain", "Did not find any additional data.") );
                return;
            } else if ( data.count() > 1 ) {
                kWarning() << "The script added more than one result set, only the first gets used";
            }
            emit additionalDataReady( data.first(), m_objects.result->features(),
                    m_objects.result->hints(), m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const AdditionalDataRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        }

        default:
            kDebug() << "Parse mode unsupported:" << _request->parseMode();
            break;
        }
    }

    // Check for exceptions
    if ( m_engine->hasUncaughtException() ) {
        // TODO Get filename where the exception occured, maybe use ScriptAgent for that
        handleError( i18nc("@info/plain", "Error in script function <icode>%1</icode>, "
                            "line %2: <message>%3</message>.",
                            functionName, m_engine->uncaughtExceptionLineNumber(),
                            m_engine->uncaughtException().toString()) );
        return;
    }

    // Cleanup
    m_engine->deleteLater();
    m_engine = 0;
    m_objects.storage->checkLifetime();
    m_objects.clear();
}
bool LocalSocketPrivate::waitForReadyRead(QElapsedTimer& timer, int timeout)
{
	bool	readyRead		=	false;
	bool	readyWrite	=	false;
	
  // Don't disable and reenable the socket notifiers as it seems unneeded, costs a lot of cpu time and blocks at some time (with lots of sockets)
// 	disableReadNotifier();
// 	disableWriteNotifier();
// 	disableExceptionNotifier();
	
	QReadLocker		controlLock(&m_controlLock);
	
	while(m_isOpen && (timeout > 0 ? timer.elapsed() < timeout : !readyWrite))
	{
		controlLock.unlock();
    QReadLocker   readLocker(&m_readBufferLock);
    // We need to read
    readyRead		=	m_readBuffer.isEmpty();
		readLocker.unlock();
    
    if(!readyRead)
      return true;
    
    QReadLocker   writeLocker(&m_writeBufferLock);
    // Do we need to write?
    readyWrite  = (!m_currentWriteData.isEmpty() || !m_writeBuffer.isEmpty());
    writeLocker.unlock();
		
		bool	ret	=	waitForReadOrWrite(readyRead, readyWrite, (timeout > 0 ? timeout - timer.elapsed() : 0));
		
		// Failed to wait
		if(!ret)
		{
			controlLock.relock();
			if(m_isOpen)
			{
        // Don't disable and reenable the socket notifiers as it seems unneeded, costs a lot of cpu time and blocks at some time (with lots of sockets)
// 				enableReadNotifier();
// 				enableWriteNotifier();
// 				enableExceptionNotifier();
			}
			
			return false;
		}
		
		// Read and write data if we can
		if(readyWrite)
			writeData();
		if(readyRead)
			readData();
		
		if(readyRead)
			break;
		
		readyRead		=	false;
		readyWrite	=	false;
	}
	controlLock.unlock();
	
  // Don't disable and reenable the socket notifiers as it seems unneeded, costs a lot of cpu time and blocks at some time (with lots of sockets)
// 	enableReadNotifier();
// 	enableWriteNotifier();
// 	enableExceptionNotifier();
  
	return readyRead;
}
Esempio n. 29
0
void global::global_init(QApplication *p)
{
    QElapsedTimer t;

    QSplashScreenPlus splash(":/images/images/Logo.png");

    //loading version and setting basic infomations
    t.start();
    splash.showMessage("loading basic infomations",Qt::AlignRight,QColor(Qt::white));
    qApp->processEvents();

    QFile version(":/text/version.txt");

    Q_ASSERT(version.open(QIODevice::ReadOnly|QIODevice::Text));
    QCoreApplication::setApplicationVersion(QString(version.readAll()));

    QCoreApplication::setOrganizationName("Lucky OIer Team");
    QCoreApplication::setApplicationName("Lucky OIer");

    p->setWindowIcon(QIcon(":/images/images/Logo.png"));

    while(t.elapsed()<1000)
        qApp->processEvents();

    //loading plugins
    t.restart();
    splash.showMessage("loading plugins",Qt::AlignRight,QColor(Qt::white));
    qApp->processEvents();

    QSettings settings;

    settings.beginGroup("plugins");
    QStringList plugins_name(settings.value("list_of_name").toStringList());
    pluginStruct tmp;
    for(QStringList::iterator i=plugins_name.begin();i!=plugins_name.end();i++)
    {
        tmp.p_plder=new QPluginLoader(*i);
        if(tmp.p_plder->load())
        {
            tmp.p_plugin=tmp.p_plder->instance();
            plugins[settings.value(*i+"/type").toInt()].push_back(tmp);
        }
        else
            delete tmp.p_plder;
    }
    settings.endGroup();

    while(t.elapsed()<1000)
        qApp->processEvents();

    //loading gui styles
    t.restart();
    splash.showMessage("loading gui styles",Qt::AlignRight,QColor(Qt::white));
    qApp->processEvents();

    settings.beginGroup("guiStyle");
    p->setStyle(settings.value("styleName").toString());
    settings.endGroup();

    while(t.elapsed()<1000)
        qApp->processEvents();

    splash.close();
}
Esempio n. 30
0
void tst_QSemaphore::tryAcquireWithTimeout()
{
    QFETCH(int, timeout);

    // timers are not guaranteed to be accurate down to the last millisecond,
    // so we permit the elapsed times to be up to this far from the expected value.
    int fuzz = 50 + (timeout / 20);

    QSemaphore semaphore;
    QElapsedTimer time;

#define FUZZYCOMPARE(a,e) \
    do { \
        int a1 = a; \
        int e1 = e; \
        QVERIFY2(qAbs(a1-e1) < fuzz, \
            qPrintable(QString("(%1=%2) is more than %3 milliseconds different from (%4=%5)") \
                        .arg(#a).arg(a1).arg(fuzz).arg(#e).arg(e1))); \
    } while (0)

    QCOMPARE(semaphore.available(), 0);

    semaphore.release();
    QCOMPARE(semaphore.available(), 1);
    time.start();
    QVERIFY(!semaphore.tryAcquire(2, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 1);

    semaphore.release();
    QCOMPARE(semaphore.available(), 2);
    time.start();
    QVERIFY(!semaphore.tryAcquire(3, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 2);

    semaphore.release(10);
    QCOMPARE(semaphore.available(), 12);
    time.start();
    QVERIFY(!semaphore.tryAcquire(100, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 12);

    semaphore.release(10);
    QCOMPARE(semaphore.available(), 22);
    time.start();
    QVERIFY(!semaphore.tryAcquire(100, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 22);

    time.start();
    QVERIFY(semaphore.tryAcquire(1, timeout));
    FUZZYCOMPARE(time.elapsed(), 0);
    QCOMPARE(semaphore.available(), 21);

    time.start();
    QVERIFY(semaphore.tryAcquire(1, timeout));
    FUZZYCOMPARE(time.elapsed(), 0);
    QCOMPARE(semaphore.available(), 20);

    time.start();
    QVERIFY(semaphore.tryAcquire(10, timeout));
    FUZZYCOMPARE(time.elapsed(), 0);
    QCOMPARE(semaphore.available(), 10);

    time.start();
    QVERIFY(semaphore.tryAcquire(10, timeout));
    FUZZYCOMPARE(time.elapsed(), 0);
    QCOMPARE(semaphore.available(), 0);

    // should not be able to acquire more
    time.start();
    QVERIFY(!semaphore.tryAcquire(1, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 0);

    time.start();
    QVERIFY(!semaphore.tryAcquire(1, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 0);

    time.start();
    QVERIFY(!semaphore.tryAcquire(10, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 0);

    time.start();
    QVERIFY(!semaphore.tryAcquire(10, timeout));
    FUZZYCOMPARE(time.elapsed(), timeout);
    QCOMPARE(semaphore.available(), 0);

#undef FUZZYCOMPARE
}