MNE-CPP  0.1.9
A Framework for Electrophysiology
unbiasedsquaredphaselagindex.cpp
Go to the documentation of this file.
1 //=============================================================================================================
39 //=============================================================================================================
40 // INCLUDES
41 //=============================================================================================================
42 
44 #include "../network/networknode.h"
45 #include "../network/networkedge.h"
46 #include "../network/network.h"
47 
48 #include <utils/spectral.h>
49 
50 //=============================================================================================================
51 // QT INCLUDES
52 //=============================================================================================================
53 
54 #include <QDebug>
55 #include <QtConcurrent>
56 
57 //=============================================================================================================
58 // EIGEN INCLUDES
59 //=============================================================================================================
60 
61 #include <unsupported/Eigen/FFT>
62 
63 //=============================================================================================================
64 // USED NAMESPACES
65 //=============================================================================================================
66 
67 using namespace CONNECTIVITYLIB;
68 using namespace Eigen;
69 using namespace UTILSLIB;
70 
71 //=============================================================================================================
72 // DEFINE GLOBAL METHODS
73 //=============================================================================================================
74 
75 //=============================================================================================================
76 // DEFINE MEMBER METHODS
77 //=============================================================================================================
78 
80 {
81 }
82 
83 //*******************************************************************************************************
84 
86 {
87 // QElapsedTimer timer;
88 // qint64 iTime = 0;
89 // timer.start();
90 
91  Network finalNetwork("USPLI");
92 
93  if(connectivitySettings.isEmpty()) {
94  qDebug() << "UnbiasedSquaredPhaseLagIndex::calculate - Input data is empty";
95  return finalNetwork;
96  }
97 
98  if(AbstractMetric::m_bStorageModeIsActive == false) {
99  connectivitySettings.clearIntermediateData();
100  }
101 
102  finalNetwork.setSamplingFrequency(connectivitySettings.getSamplingFrequency());
103 
104  #ifdef EIGEN_FFTW_DEFAULT
105  fftw_make_planner_thread_safe();
106  #endif
107 
108  //Create nodes
109  int rows = connectivitySettings.at(0).matData.rows();
110  RowVectorXf rowVert = RowVectorXf::Zero(3);
111 
112  for(int i = 0; i < rows; ++i) {
113  rowVert = RowVectorXf::Zero(3);
114 
115  if(connectivitySettings.getNodePositions().rows() != 0 && i < connectivitySettings.getNodePositions().rows()) {
116  rowVert(0) = connectivitySettings.getNodePositions().row(i)(0);
117  rowVert(1) = connectivitySettings.getNodePositions().row(i)(1);
118  rowVert(2) = connectivitySettings.getNodePositions().row(i)(2);
119  }
120 
121  finalNetwork.append(NetworkNode::SPtr(new NetworkNode(i, rowVert)));
122  }
123 
124  // Check that iNfft >= signal length
125  int iSignalLength = connectivitySettings.at(0).matData.cols();
126  int iNfft = connectivitySettings.getFFTSize();
127 
128  // Generate tapers
129  QPair<MatrixXd, VectorXd> tapers = Spectral::generateTapers(iSignalLength, connectivitySettings.getWindowType());
130 
131  // Initialize
132  int iNRows = connectivitySettings.at(0).matData.rows();
133  int iNFreqs = int(floor(iNfft / 2.0)) + 1;
134 
135  // Check if start and bin amount need to be reset to full spectrum
136  if(m_iNumberBinStart == -1 ||
137  m_iNumberBinAmount == -1 ||
138  m_iNumberBinStart > iNFreqs ||
139  m_iNumberBinAmount > iNFreqs ||
140  m_iNumberBinAmount + m_iNumberBinStart > iNFreqs) {
141  qDebug() << "UnbiasedSquaredPhaseLagIndex::calculate - Resetting to full spectrum";
142  AbstractMetric::m_iNumberBinStart = 0;
143  AbstractMetric::m_iNumberBinAmount = iNFreqs;
144  }
145 
146  // Pass information about the FFT length. Use iNFreqs because we only use the half spectrum
147  finalNetwork.setFFTSize(iNFreqs);
148  finalNetwork.setUsedFreqBins(AbstractMetric::m_iNumberBinAmount);
149 
150  QMutex mutex;
151 
152  std::function<void(ConnectivitySettings::IntermediateTrialData&)> computeLambda = [&](ConnectivitySettings::IntermediateTrialData& inputData) {
153  compute(inputData,
154  connectivitySettings.getIntermediateSumData().vecPairCsdSum,
155  connectivitySettings.getIntermediateSumData().vecPairCsdImagSignSum,
156  mutex,
157  iNRows,
158  iNFreqs,
159  iNfft,
160  tapers);
161  };
162 
163 // iTime = timer.elapsed();
164 // qWarning() << "Preparation" << iTime;
165 // timer.restart();
166 
167  // Compute DSWPLV in parallel for all trials
168  QFuture<void> result = QtConcurrent::map(connectivitySettings.getTrialData(),
169  computeLambda);
170  result.waitForFinished();
171 
172 // iTime = timer.elapsed();
173 // qWarning() << "ComputeSpectraPSDCSD" << iTime;
174 // timer.restart();
175 
176  // Compute USPLI
177  computeUSPLI(connectivitySettings,
178  finalNetwork);
179 
180 // iTime = timer.elapsed();
181 // qWarning() << "Compute" << iTime;
182 // timer.restart();
183 
184  return finalNetwork;
185 }
186 
187 //=============================================================================================================
188 
190  QVector<QPair<int,MatrixXcd> >& vecPairCsdSum,
191  QVector<QPair<int,MatrixXd> >& vecPairCsdImagSignSum,
192  QMutex& mutex,
193  int iNRows,
194  int iNFreqs,
195  int iNfft,
196  const QPair<MatrixXd, VectorXd>& tapers)
197 {
198  if(inputData.vecPairCsdImagSign.size() == iNRows) {
199  //qDebug() << "UnbiasedSquaredPhaseLagIndex::compute - vecPairCsdImagSign was already computed for this trial.";
200  return;
201  }
202 
203  int i,j;
204 
205  // Calculate tapered spectra if not available already
206  // This code was copied and changed modified Utils/Spectra since we do not want to call the function due to time loss.
207  if(inputData.vecTapSpectra.size() != iNRows) {
208  inputData.vecTapSpectra.clear();
209 
210  RowVectorXd vecInputFFT, rowData;
211  RowVectorXcd vecTmpFreq;
212 
213  MatrixXcd matTapSpectrum(tapers.first.rows(), iNFreqs);
214 
215  FFT<double> fft;
216  fft.SetFlag(fft.HalfSpectrum);
217 
218  for (i = 0; i < iNRows; ++i) {
219  // Substract mean
220  rowData.array() = inputData.matData.row(i).array() - inputData.matData.row(i).mean();
221 
222  // Calculate tapered spectra if not available already
223  for(j = 0; j < tapers.first.rows(); j++) {
224  // Zero padd if necessary. The zero padding in Eigen's FFT is only working for column vectors.
225  if (rowData.cols() < iNfft) {
226  vecInputFFT.setZero(iNfft);
227  vecInputFFT.block(0,0,1,rowData.cols()) = rowData.cwiseProduct(tapers.first.row(j));;
228  } else {
229  vecInputFFT = rowData.cwiseProduct(tapers.first.row(j));
230  }
231 
232  // FFT for freq domain returning the half spectrum and multiply taper weights
233  fft.fwd(vecTmpFreq, vecInputFFT, iNfft);
234  matTapSpectrum.row(j) = vecTmpFreq * tapers.second(j);
235  }
236 
237  inputData.vecTapSpectra.append(matTapSpectrum);
238  }
239  }
240 
241  // Compute CSD
242  if(inputData.vecPairCsd.isEmpty()) {
243  double denomCSD = sqrt(tapers.second.cwiseAbs2().sum()) * sqrt(tapers.second.cwiseAbs2().sum()) / 2.0;
244 
245  bool bNfftEven = false;
246  if (iNfft % 2 == 0){
247  bNfftEven = true;
248  }
249 
250  MatrixXcd matCsd = MatrixXcd(iNRows, m_iNumberBinAmount);
251 
252  for (i = 0; i < iNRows; ++i) {
253  for (j = i; j < iNRows; ++j) {
254  // Compute CSD (average over tapers if necessary)
255  matCsd.row(j) = inputData.vecTapSpectra.at(i).block(0,m_iNumberBinStart,inputData.vecTapSpectra.at(i).rows(),m_iNumberBinAmount).cwiseProduct(inputData.vecTapSpectra.at(j).block(0,m_iNumberBinStart,inputData.vecTapSpectra.at(j).rows(),m_iNumberBinAmount).conjugate()).colwise().sum() / denomCSD;
256 
257  // Divide first and last element by 2 due to half spectrum
258  if(m_iNumberBinStart == 0) {
259  matCsd.row(j)(0) /= 2.0;
260  }
261 
262  if(bNfftEven && m_iNumberBinStart + m_iNumberBinAmount >= iNFreqs) {
263  matCsd.row(j).tail(1) /= 2.0;
264  }
265  }
266 
267  inputData.vecPairCsd.append(QPair<int,MatrixXcd>(i,matCsd));
268  inputData.vecPairCsdImagSign.append(QPair<int,MatrixXd>(i,matCsd.imag().cwiseSign()));
269  }
270 
271  mutex.lock();
272 
273  if(vecPairCsdSum.isEmpty()) {
274  vecPairCsdSum = inputData.vecPairCsd;
275  vecPairCsdImagSignSum = inputData.vecPairCsdImagSign;
276  } else {
277  for (int j = 0; j < vecPairCsdSum.size(); ++j) {
278  vecPairCsdSum[j].second += inputData.vecPairCsd.at(j).second;
279  vecPairCsdImagSignSum[j].second += inputData.vecPairCsdImagSign.at(j).second;
280  }
281  }
282 
283  mutex.unlock();
284  } else {
285  if(inputData.vecPairCsdImagSign.isEmpty()) {
286  for (i = 0; i < inputData.vecPairCsd.size(); ++i) {
287  inputData.vecPairCsdImagSign.append(QPair<int,MatrixXd>(i,inputData.vecPairCsd.at(i).second.imag().cwiseSign()));
288  }
289 
290  mutex.lock();
291 
292  if(vecPairCsdImagSignSum.isEmpty()) {
293  vecPairCsdImagSignSum = inputData.vecPairCsdImagSign;
294  } else {
295  for (int j = 0; j < vecPairCsdImagSignSum.size(); ++j) {
296  vecPairCsdImagSignSum[j].second += inputData.vecPairCsdImagSign.at(j).second;
297  }
298  }
299 
300  mutex.unlock();
301  }
302  }
303 
304  if(!m_bStorageModeIsActive) {
305  inputData.vecPairCsd.clear();
306  inputData.vecTapSpectra.clear();
307  inputData.vecPairCsdImagSign.clear();
308  }
309 }
310 
311 //=============================================================================================================
312 
314  Network& finalNetwork)
315 {
316  // Compute final DSWPLV and create Network
317  MatrixXd matNom;
318  MatrixXd matWeight;
319  QSharedPointer<NetworkEdge> pEdge;
320  int j;
321  double dNTrials = double(connectivitySettings.size() - 1.0);
322 
323  for (int i = 0; i < connectivitySettings.getIntermediateSumData().vecPairCsdImagSignSum.size(); ++i) {
324  matNom = connectivitySettings.getIntermediateSumData().vecPairCsdImagSignSum.at(i).second.cwiseAbs() / connectivitySettings.size();
325  matNom = (connectivitySettings.size() * matNom.array().square() - 1.0) / dNTrials;
326 
327  for(j = i; j < matNom.rows(); ++j) {
328  matWeight = matNom.row(j).transpose();
329 
330  pEdge = QSharedPointer<NetworkEdge>(new NetworkEdge(i, j, matWeight));
331 
332  finalNetwork.getNodeAt(i)->append(pEdge);
333  finalNetwork.getNodeAt(j)->append(pEdge);
334  finalNetwork.append(pEdge);
335  }
336  }
337 }
338 
CONNECTIVITYLIB::ConnectivitySettings::IntermediateTrialData
Definition: connectivitysettings.h:98
spectral.h
Declaration of Spectral class.
CONNECTIVITYLIB::Network
This class holds information about a network, can compute a distance table and provide network metric...
Definition: network.h:88
CONNECTIVITYLIB::Network::append
void append(QSharedPointer< NetworkEdge > newEdge)
CONNECTIVITYLIB::UnbiasedSquaredPhaseLagIndex::computeUSPLI
static void computeUSPLI(ConnectivitySettings &connectivitySettings, Network &finalNetwork)
Definition: unbiasedsquaredphaselagindex.cpp:313
CONNECTIVITYLIB::Network::getNodeAt
QSharedPointer< NetworkNode > getNodeAt(int i)
Definition: network.cpp:163
unbiasedsquaredphaselagindex.h
UnbiasedSquaredPhaseLagIndex class declaration.
CONNECTIVITYLIB::UnbiasedSquaredPhaseLagIndex::compute
static void compute(ConnectivitySettings::IntermediateTrialData &inputData, QVector< QPair< int, Eigen::MatrixXcd > > &vecPairCsdSum, QVector< QPair< int, Eigen::MatrixXd > > &vecPairCsdImagSignSum, QMutex &mutex, int iNRows, int iNFreqs, int iNfft, const QPair< Eigen::MatrixXd, Eigen::VectorXd > &tapers)
Definition: unbiasedsquaredphaselagindex.cpp:189
CONNECTIVITYLIB::Network::setSamplingFrequency
void setSamplingFrequency(float fSFreq)
Definition: network.cpp:492
CONNECTIVITYLIB::UnbiasedSquaredPhaseLagIndex::UnbiasedSquaredPhaseLagIndex
UnbiasedSquaredPhaseLagIndex()
Definition: unbiasedsquaredphaselagindex.cpp:79
CONNECTIVITYLIB::Network::setUsedFreqBins
void setUsedFreqBins(int iNumberFreqBins)
Definition: network.cpp:506
CONNECTIVITYLIB::NetworkEdge
This class holds an object to describe the edge of a network.
Definition: networkedge.h:79
CONNECTIVITYLIB::Network::setFFTSize
void setFFTSize(int iFFTSize)
Definition: network.cpp:513
CONNECTIVITYLIB::ConnectivitySettings
This class is a container for connectivity settings.
Definition: connectivitysettings.h:91
CONNECTIVITYLIB::UnbiasedSquaredPhaseLagIndex::calculate
static Network calculate(ConnectivitySettings &connectivitySettings)
Definition: unbiasedsquaredphaselagindex.cpp:85
CONNECTIVITYLIB::NetworkNode::SPtr
QSharedPointer< NetworkNode > SPtr
Definition: networknode.h:85
CONNECTIVITYLIB::NetworkNode
This class holds an object to describe the node of a network.
Definition: networknode.h:81