Skip to content

[ENH, MAINT] MNE Scan: Separating plugins and threads. #883

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
// QT INCLUDES
//=============================================================================================================

#include <QThread>
#include <QObject>
#include <QCoreApplication>
#include <QSharedPointer>
#include <QAction>
Expand All @@ -76,7 +76,7 @@ namespace SCSHAREDLIB
*
* @brief The AbstractPlugin class is the base interface class of all plugins.
*/
class SCSHAREDSHARED_EXPORT AbstractPlugin : public QThread
class SCSHAREDSHARED_EXPORT AbstractPlugin : public QObject
{
Q_OBJECT

Expand Down
94 changes: 94 additions & 0 deletions src/applications/mne_scan/libs/scShared/Plugins/threads.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
//=============================================================================================================
/**
* @file threads.h
* @author Gabriel Motta <[email protected]>
* @since 0.1.9
* @date January, 2022
*
* @section LICENSE
*
* Copyright (C) 2022, Gabriel Motta. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Contains threading classes.
*
*/

#ifndef MNESCAN_THREADS_H
#define MNESCAN_THREADS_H

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include <thread>
#include <atomic>
#include <chrono>

//=============================================================================================================
// DEFINE NAMESPACE SCSHAREDLIB
//=============================================================================================================

namespace SCSHAREDLIB
{

class Thread
{
public:
//=========================================================================================================
/**
* Constructs an "empty" object.
*/
Thread(): m_bIsRunning(false) {}


template<class Function, class... Args >
//=========================================================================================================
/**
* Constructs a thread object to run a function in a separate thread.
*
* @param[in] func function to be run in separate thread
* @param[in] args function arguments.
* (Note - member functions need to be passed usually-implicit 'this' pointer)
*/
Thread(Function&& func, Args&&... args): m_thread(func, args...), m_bIsRunning(true) {}

//=========================================================================================================
/**
* Returns whether the thread is running.
*/
bool isRunning() const {return m_bIsRunning;}

//=========================================================================================================
/**
* Runs a function as a thread. Thread is deleted once function is finished. Not bound by caller's scope.
*/
template<class Function, class... Args >
static void run(Function&& func, Args&&... args){Thread(func, args...).m_thread.detach();}

private:
std::thread m_thread; /**< The actual thread. */
std::atomic_bool m_bIsRunning; /**< Whether the thred is runing. */
};

}//namespace

#endif // MNESCAN_THREADS_H
17 changes: 11 additions & 6 deletions src/applications/mne_scan/plugins/averaging/averaging.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,15 @@ using namespace Eigen;

Averaging::Averaging()
: m_pCircularBuffer(CircularBuffer<FIFFLIB::FiffEvokedSet>::SPtr::create(40))
, m_bProcessOutput(false)
{
}

//=============================================================================================================

Averaging::~Averaging()
{
if(this->isRunning())
if(m_bProcessOutput)
stop();
}

Expand All @@ -106,7 +107,8 @@ void Averaging::unload()

bool Averaging::start()
{
QThread::start();
m_bProcessOutput = true;
m_OutputProcessingThread = std::thread(&Averaging::run, this);

return true;
}
Expand All @@ -115,8 +117,11 @@ bool Averaging::start()

bool Averaging::stop()
{
requestInterruption();
wait(500);
m_bProcessOutput = false;

if(m_OutputProcessingThread.joinable()){
m_OutputProcessingThread.join();
}

m_bPluginControlWidgetsInit = false;

Expand Down Expand Up @@ -406,7 +411,7 @@ void Averaging::onChangeBaselineActive(bool state)
void Averaging::onNewEvokedSet(const FIFFLIB::FiffEvokedSet& evokedSet,
const QStringList& lResponsibleTriggerTypes)
{
if(!this->isRunning()) {
if(!m_bProcessOutput) {
return;
}

Expand Down Expand Up @@ -439,7 +444,7 @@ void Averaging::run()
FIFFLIB::FiffEvokedSet evokedSet;
QStringList lResponsibleTriggerTypes;

while(!isInterruptionRequested()){
while(m_bProcessOutput){
if(m_pCircularBuffer->pop(evokedSet)) {
m_qMutex.lock();
lResponsibleTriggerTypes = m_lResponsibleTriggerTypes;
Expand Down
6 changes: 6 additions & 0 deletions src/applications/mne_scan/plugins/averaging/averaging.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@

#include <fiff/fiff_evoked_set.h>

#include <thread>
#include <atomic>

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
Expand Down Expand Up @@ -237,6 +240,9 @@ class AVERAGINGSHARED_EXPORT Averaging : public SCSHAREDLIB::AbstractAlgorithm

QMap<QString,int> m_mapStimChsIndexNames; /**< The currently available stim channels and their corresponding index in the data. */

std::thread m_OutputProcessingThread;
std::atomic_bool m_bProcessOutput;

signals:
void stimChannelsChanged(const QMap<QString,int>& mapStimChsIndexNames);
void fiffChInfoChanged(const QList<FIFFLIB::FiffChInfo>& fiffChInfoList);
Expand Down
19 changes: 12 additions & 7 deletions src/applications/mne_scan/plugins/babymeg/babymeg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ BabyMEG::BabyMEG()
, m_sFiffProjections(QCoreApplication::applicationDirPath() + "/../resources/mne_scan/plugins/babymeg/header.fif")
, m_sFiffCompensators(QCoreApplication::applicationDirPath() + "/../resources/mne_scan/plugins/babymeg/compensator.fif")
, m_sBadChannels(QCoreApplication::applicationDirPath() + "/../resources/mne_scan/plugins/babymeg/both.bad")
, m_bProcessOutput(false)
{
m_pActionSqdCtrl = new QAction(QIcon(":/images/sqdctrl.png"), tr("Squid Control"),this);
// m_pActionSetupProject->setShortcut(tr("F12"));
Expand All @@ -107,7 +108,7 @@ BabyMEG::BabyMEG()

BabyMEG::~BabyMEG()
{
if(this->isRunning()) {
if(m_bProcessOutput) {
stop();
}

Expand Down Expand Up @@ -208,7 +209,8 @@ bool BabyMEG::start()
initConnector();

// Start thread
QThread::start();
m_bProcessOutput = true;
m_OutputProcessingThread = std::thread(&BabyMEG::run, this);

return true;
}
Expand All @@ -217,8 +219,11 @@ bool BabyMEG::start()

bool BabyMEG::stop()
{
requestInterruption();
wait(2000);
m_bProcessOutput = false;

if(m_OutputProcessingThread.joinable()){
m_OutputProcessingThread.join();
}

// Clear all data in the buffer connected to displays and other plugins
m_pRTMSABabyMEG->measurementData()->clear();
Expand Down Expand Up @@ -260,13 +265,13 @@ void BabyMEG::run()
{
MatrixXf matValue;

while(!isInterruptionRequested()) {
while(m_bProcessOutput) {
//pop matrix
if(m_pCircularBuffer->pop(matValue)) {
//Create digital trigger information
createDigTrig(matValue);

if(!isInterruptionRequested()) {
if(m_bProcessOutput) {
m_pRTMSABabyMEG->measurementData()->setValue(this->calibrate(matValue));
}
}
Expand Down Expand Up @@ -352,7 +357,7 @@ void BabyMEG::setFiffData(QByteArray data)
IOUtils::swap_floatp(rawData.data()+i);
}

if(this->isRunning()) {
if(m_bProcessOutput) {
while(!m_pCircularBuffer->push(rawData)) {
//Do nothing until the circular buffer is ready to accept new data again
}
Expand Down
5 changes: 5 additions & 0 deletions src/applications/mne_scan/plugins/babymeg/babymeg.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@
#include <scShared/Plugins/abstractsensor.h>
#include <utils/generics/circularbuffer.h>

#include <thread>
#include <atomic>

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
Expand Down Expand Up @@ -319,6 +322,8 @@ class BABYMEGSHARED_EXPORT BabyMEG : public SCSHAREDLIB::AbstractSensor
QPointer<QAction> m_pActionSqdCtrl; /**< show squid control. */
QPointer<QAction> m_pActionUpdateFiffInfo; /**< Update Fiff Info action. */

std::thread m_OutputProcessingThread;
std::atomic_bool m_bProcessOutput;
signals:
//=========================================================================================================
/**
Expand Down
15 changes: 10 additions & 5 deletions src/applications/mne_scan/plugins/brainamp/brainamp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ BrainAMP::BrainAMP()
, m_sRPA("2RD")
, m_sNasion("0Z")
, m_pCircularBuffer(QSharedPointer<CircularBuffer_Matrix_double>(new CircularBuffer_Matrix_double(8)))
, m_bProcessOutput(false)
{
// Create record file option action bar item/button
m_pActionSetupProject = new QAction(QIcon(":/images/database.png"), tr("Setup project"), this);
Expand All @@ -99,7 +100,7 @@ BrainAMP::~BrainAMP()
//std::cout << "BrainAMP::~BrainAMP() " << std::endl;

//If the program is closed while the sampling is in process
if(this->isRunning()) {
if(m_bProcessOutput) {
this->stop();
}
}
Expand Down Expand Up @@ -278,7 +279,8 @@ bool BrainAMP::start()
m_iSamplingFreq);

if(m_pBrainAMPProducer->isRunning()) {
QThread::start();
m_bProcessOutput = true;
m_OutputProcessingThread = std::thread(&BrainAMP::run, this);
return true;
} else {
qWarning() << "BrainAMP::start() - BrainAMPProducer thread could not be started." << endl;
Expand All @@ -290,8 +292,11 @@ bool BrainAMP::start()

bool BrainAMP::stop()
{
requestInterruption();
wait(500);
m_bProcessOutput = false;

if(m_OutputProcessingThread.joinable()){
m_OutputProcessingThread.join();
}

//Stop the producer thread first
m_pBrainAMPProducer->stop();
Expand Down Expand Up @@ -372,7 +377,7 @@ void BrainAMP::run()
{
MatrixXd matData;

while(!isInterruptionRequested()) {
while(m_bProcessOutput) {
if(m_pBrainAMPProducer->isRunning()) {
//pop matrix
if(m_pCircularBuffer->pop(matData)) {
Expand Down
6 changes: 6 additions & 0 deletions src/applications/mne_scan/plugins/brainamp/brainamp.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@
#include <scShared/Plugins/abstractsensor.h>
#include <utils/generics/circularbuffer.h>

#include <thread>
#include <atomic>

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
Expand Down Expand Up @@ -232,6 +235,9 @@ protected slots:
QAction* m_pActionSetupStimulus; /**< starts stimulus feature. */

QMutex m_mutex;

std::thread m_OutputProcessingThread;
std::atomic_bool m_bProcessOutput;
};
} // NAMESPACE

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ BrainFlowBoard::BrainFlowBoard()
, m_sStreamerParams("")
, m_uiSamplesPerBlock(100)
, m_pFiffInfo(QSharedPointer<FiffInfo>::create())
, m_bProcessOutput(false)
{
m_pShowSettingsAction = new QAction(QIcon(":/images/options.png"), tr("Streaming Settings"),this);
m_pShowSettingsAction->setStatusTip(tr("Streaming Settings"));
Expand Down Expand Up @@ -244,7 +245,8 @@ bool BrainFlowBoard::start()
msgBox.exec();
return false;
}
QThread::start();
m_bProcessOutput = true;
m_OutputProcessingThread = std::thread(&BrainFlowBoard::run, this);
return true;
}

Expand All @@ -256,8 +258,11 @@ bool BrainFlowBoard::stop()
if(m_pBoardShim) {
m_pBoardShim->stop_stream();
}
requestInterruption();
wait(500);
m_bProcessOutput = false;

if(m_OutputProcessingThread.joinable()){
m_OutputProcessingThread.join();
}
m_pOutput->measurementData()->clear();
} catch (const BrainFlowException &err) {
BoardShim::log_message((int)LogLevels::LEVEL_ERROR, err.what());
Expand Down Expand Up @@ -388,12 +393,12 @@ void BrainFlowBoard::run()
BrainFlowArray<double, 2> data;
QList<Eigen::VectorXd> lSampleBlockBuffer;

while(!isInterruptionRequested()) {
usleep(lSamplingPeriod);
while(m_bProcessOutput) {
std::this_thread::sleep_for(std::chrono::microseconds(lSamplingPeriod));
iSampleIterator = 0;

//get samples from device until the complete matrix is filled, i.e. the samples per block size is met
while(iSampleIterator < m_uiSamplesPerBlock && !isInterruptionRequested()) {
while(iSampleIterator < m_uiSamplesPerBlock && m_bProcessOutput) {
//Get sample block from device
data = m_pBoardShim->get_board_data ();
if (data.get_size(1) == 0) {
Expand Down
Loading