示例#1
0
void TW_CALL SkinningCallback::compute_weights(void * clientData)
{
  Skinning * skinning = scast(clientData);
  skinning->auto_dof = false;
  verbose("Computing BBW weights\n");
  // Determine which Bones have weights
  bool success = distribute_weight_indices(skinning->skel->roots);
  if(!success)
  {
    return;
  }
  // Gather samples along controls
  MatrixXd S;
  gather_samples(skinning->skel->roots,10,S);
  VectorXi IM;
  faces_first(skinning->V,skinning->F,IM);
  skinning->Tets = 
    skinning->Tets.unaryExpr(bind1st(mem_fun( static_cast<VectorXi::Scalar&
    (VectorXi::*)(VectorXi::Index)>(&VectorXi::operator())),
    &IM)).eval();
  // Surface vertices
  MatrixXd SV = 
    skinning->V.block(0,0,skinning->F.maxCoeff()+1,skinning->V.cols());
  // Remesh at control samples
  MatrixXd VS = cat(1,SV,S);
  // Boundary faces
  MatrixXi BF;
  cout<<"tetgen begin()"<<endl;
  int status = 
    igl::tetgen::tetrahedralize(
      VS,skinning->F,"Ypq100",skinning->V,skinning->Tets,BF);
  cout<<"tetgen end()"<<endl;
  if(BF.rows() != skinning->F.rows())
  {
    //assert(BF.maxCoeff() == skinning->F.maxCoeff());
    verbose("^%s: Warning: boundary faces != orignal faces\n",__FUNCTION__);
  }
  if(status != 0)
  {
    verbose(
        "************************************************************\n"
        "************************************************************\n"
        "************************************************************\n"
        "************************************************************\n"
        "* ^%s: tetgen failed. Just meshing convex hull\n"
        "************************************************************\n"
        "************************************************************\n"
        "************************************************************\n"
        "************************************************************\n"
        ,__FUNCTION__);
    status =
      igl::tetgen::tetrahedralize(
        VS,skinning->F,"q1.414",skinning->V,skinning->Tets,BF);
    assert(skinning->F.maxCoeff() < skinning->V.rows());
    if(status != 0)
    {
      verbose("^%s: tetgen failed again.\n",__FUNCTION__);
      return;
    }
  }
#ifdef __APPLE__
    launch_medit(skinning->V,skinning->Tets,skinning->F,false);
#endif
  skinning->initialize_mesh();

  // Get boundary conditions
  VectorXi b;
  MatrixXd bc;
  boundary_conditions(skinning->V,skinning->Tets,skinning->skel->roots,b,bc);

  //    call BBW 
  igl::bbw::BBWData bbw_data;
  bbw_data.active_set_params.max_iter = 10;
  success = igl::bbw::bbw(
    skinning->V,
    skinning->Tets,
    b,
    bc,
    bbw_data,
    skinning->OW
    );
  skinning->OW = 
    (skinning->OW.array().colwise() / 
      skinning->OW.rowwise().sum().array()).eval();
  if(!success)
  {
    return;
  }
  // Clear extra weights
  skinning->skel->set_editing(false);
  skinning->EW.resize(skinning->OW.rows(),0);
  skinning->initialize_weights();
}
示例#2
0
int main(int argc, char *argv[])
{
    const char *inLabelExt = ".txt";
    const char *outScoreFile = NULL;
    bool bShowConfusion = false;

    // process commandline arguments
    DRWN_BEGIN_CMDLINE_PROCESSING(argc, argv)
        DRWN_CMDLINE_STR_OPTION("-inLabels", inLabelExt)
        DRWN_CMDLINE_STR_OPTION("-outScores", outScoreFile)
        DRWN_CMDLINE_BOOL_OPTION("-confusion", bShowConfusion)
    DRWN_END_CMDLINE_PROCESSING(usage());

    if (DRWN_CMDLINE_ARGC != 1) {
        usage();
        return -1;
    }

    drwnCodeProfiler::tic(drwnCodeProfiler::getHandle("main"));

    // read list of evaluation images
    const char *evalList = DRWN_CMDLINE_ARGV[0];

    DRWN_LOG_MESSAGE("Reading evaluation list from " << evalList << "...");
    vector<string> baseNames = drwnReadFile(evalList);
    DRWN_LOG_MESSAGE("...read " << baseNames.size() << " images");

    const int nLabels = gMultiSegRegionDefs.maxKey() + 1;
    drwnConfusionMatrix confusion(nLabels);
    vector<double> scores(baseNames.size());

    // process results
    DRWN_LOG_MESSAGE("Processing results (" << inLabelExt << ")...");
    int hProcessImage = drwnCodeProfiler::getHandle("processImage");
    for (int i = 0; i < (int)baseNames.size(); i++) {
        drwnCodeProfiler::tic(hProcessImage);
        string lblFilename = gMultiSegConfig.filename("lblDir", baseNames[i], "lblExt");
        string resFilename = gMultiSegConfig.filebase("outputDir", baseNames[i]) + string(inLabelExt);
        DRWN_LOG_STATUS("..." << baseNames[i] << " (" << (i + 1) << " of "
            << baseNames.size() << ")");

        // read ground-truth labels
        MatrixXi actualLabels;
        //drwnReadUnknownMatrix(actualLabels, lblFilename.c_str());
        drwnLoadPixelLabels(actualLabels, lblFilename.c_str(), nLabels);

        // read inferred labels
        MatrixXi predictedLabels(actualLabels.rows(), actualLabels.cols());
        drwnReadMatrix(predictedLabels, resFilename.c_str());

        DRWN_ASSERT((predictedLabels.rows() == actualLabels.rows()) &&
            (predictedLabels.cols() == actualLabels.cols()));

        // accumulate results for this image
        drwnConfusionMatrix imageConfusion(nLabels);
        for (int y = 0; y < actualLabels.rows(); y++) {
            for (int x = 0; x < actualLabels.cols(); x++) {
                if (actualLabels(y, x) < 0) continue;
                imageConfusion.accumulate(actualLabels(y, x), predictedLabels(y, x));
            }
        }

        scores[i] = imageConfusion.accuracy();

        // add to dataset results
        confusion.accumulate(imageConfusion);

        drwnCodeProfiler::toc(hProcessImage);
    }

    // display results
    if (bShowConfusion) {
        confusion.printRowNormalized(cout, "--- Class Confusion Matrix ---");
        confusion.printPrecisionRecall(cout, "--- Recall/Precision (by Class) ---");
        confusion.printF1Score(cout, "--- F1-Score (by Class) ---");
        confusion.printJaccard(cout, "--- Intersection/Union Metric (by Class) ---");
    }

    DRWN_LOG_MESSAGE("Overall class accuracy: " << confusion.accuracy() << " (" << evalList << ")");
    DRWN_LOG_MESSAGE("Average class accuracy: " << confusion.avgRecall() << " (" << evalList << ")");
    DRWN_LOG_MESSAGE("Average jaccard score:  " << confusion.avgJaccard() << " (" << evalList << ")");

    // write scores
    if (outScoreFile != NULL) {
        ofstream ofs(outScoreFile);
        DRWN_ASSERT_MSG(!ofs.fail(), outScoreFile);
        for (int i = 0; i < (int)scores.size(); i++) {
            ofs << scores[i] << "\n";
        }
        ofs.close();
    }

    // clean up and print profile information
    drwnCodeProfiler::toc(drwnCodeProfiler::getHandle("main"));
    drwnCodeProfiler::print();
    return 0;
}
示例#3
0
文件: main.cpp 项目: GBeret/mne-cpp
/**
* 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();
}
示例#4
0
文件: main.cpp 项目: eh1255/mne-cpp
/**
* 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);

    QFile t_fileRaw("./MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
    QString t_sEventName = "./MNE-sample-data/MEG/sample/sample_audvis_raw-eve.fif";
    QFile t_fileFwd("./MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif");
    AnnotationSet t_annotationSet("./MNE-sample-data/subjects/sample/label/lh.aparc.a2009s.annot", "./MNE-sample-data/subjects/sample/label/rh.aparc.a2009s.annot");
    SurfaceSet t_surfSet("./MNE-sample-data/subjects/sample/surf/lh.white", "./MNE-sample-data/subjects/sample/surf/rh.white");

//    QFile t_fileRaw("E:/Data/sl_data/MEG/mind006/mind006_051209_auditory01_raw.fif");
//    QString t_sEventName = "E:/Data/sl_data/MEG/mind006/mind006_051209_auditory01_raw-eve.fif";
//    QFile t_fileFwd("E:/Data/sl_data/MEG/mind006/mind006_051209_auditory01_raw-oct-6p-fwd.fif");
//    AnnotationSet t_annotationSet("E:/Data/sl_data/subjects/mind006/label/lh.aparc.a2009s.annot", "E:/Data/sl_data/subjects/mind006/label/rh.aparc.a2009s.annot");
//    SurfaceSet t_surfSet("E:/Data/sl_data/subjects/mind006/surf/lh.white", "E:/Data/sl_data/subjects/mind006/surf/rh.white");

//    QFile t_fileRaw("E:/Data/sl_data/MEG/mind006/mind006_051209_median01_raw.fif");
//    QString t_sEventName = "E:/Data/sl_data/MEG/mind006/mind006_051209_median01_raw-eve.fif";
//    QFile t_fileFwd("E:/Data/sl_data/MEG/mind006/mind006_051209_median01_raw-oct-6-fwd.fif");
//    AnnotationSet t_annotationSet("E:/Data/sl_data/subjects/mind006/label/lh.aparc.a2009s.annot", "E:/Data/sl_data/subjects/mind006/label/rh.aparc.a2009s.annot");
//    SurfaceSet t_surfSet("E:/Data/sl_data/subjects/mind006/surf/lh.white", "E:/Data/sl_data/subjects/mind006/surf/rh.white");

    QString t_sFileNameStc("");//("mind006_051209_auditory01.stc");


    bool doMovie = false;//true;

    qint32 numDipolePairs = 7;

    qint32 event = 1;

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

    bool keep_comp = false;
    fiff_int_t dest_comp = 0;
    bool pick_all  = true;

    qint32 k, p;


    // Parse command line parameters
    for(qint32 i = 0; i < argc; ++i)
    {
        if(strcmp(argv[i], "-stc") == 0 || strcmp(argv[i], "--stc") == 0)
        {
            if(i + 1 < argc)
                t_sFileNameStc = QString::fromUtf8(argv[i+1]);
        }
    }

    //
    // 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
//    qint32 numAverages = 99;
//    VectorXi vecSel(numAverages);
//    srand (time(NULL)); // initialize random seed

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

    //Option 2
//    VectorXi vecSel(20);

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

//    vecSel << 65, 22, 47, 55, 16, 29, 14, 36, 57, 97, 89, 46, 9, 93, 83, 52, 71, 52, 3, 96;

    //Option 3 Newest
//    VectorXi vecSel(10);

//    vecSel << 0, 96, 80, 55, 66, 25, 26, 2, 55, 58, 6, 88;


    VectorXi vecSel(1);

    vecSel << 0;


    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
    //
    RapMusic t_rapMusic(t_clusteredFwd, false, numDipolePairs);

    if(doMovie)
        t_rapMusic.setStcAttr(200,0.5);

    MNESourceEstimate sourceEstimate = t_rapMusic.calculateInverse(pickedEvoked);

    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);

    View3D::SPtr testWindow = View3D::SPtr(new View3D());
    testWindow->addBrainData("Subject01", "HemiLRSet", t_surfSet, t_annotationSet);

    QList<BrainRTSourceLocDataTreeItem*> rtItemList = testWindow->addRtBrainData("Subject01", "HemiLRSet", sourceEstimate, t_clusteredFwd);

    testWindow->show();

    Control3DWidget::SPtr control3DWidget = Control3DWidget::SPtr(new Control3DWidget());
    control3DWidget->setView3D(testWindow);
    control3DWidget->show();

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

    return a.exec();//1;//a.exec();
}
示例#5
0
int main(int argc, char *argv[]) {
    cout << "Usage: " << argv[0] << " [FILENAME].[off|obj|ply] [1-7] [sl]"
         << endl;
    cout << "where 1-7 is the cost function to use" << endl;
    cout << "      s = save images at all decimation steps" << endl;
    cout << "      l = disable lighting" << endl;
    cout << endl;
    cout << "Keybindings:" << endl;
    cout << "  [space]  toggle animation." << endl;
    cout << "  'r'  reset." << endl;
    cout << "  '1'  edge collapse." << endl;
    cout << "  '2'  vertex split." << endl;
    cout << "  's'  save screenshot." << endl;
    cout << "  'c'  switch color mode." << endl;
    cout << "  'f'  cycle cost function." << endl;
    cout << endl;
    // Load a closed manifold mesh
    string filename;
    if (argc >= 2) {
        filename = argv[1];
    } else {
        return 0;
    }
    if (argc >= 3) {
        int idx = stoi(argv[2]) - 1;
        cost_function_n = idx;
        if (idx >= 0 && idx < cost_functions.size())
            shortest_edge_and_midpoint = *(cost_functions.begin() + idx);
    }

    if (!igl::read_triangle_mesh(filename, OV, OF)) {
        cout << "could not read mesh from \"" << filename << "\"" << endl;
        return 1;
    }

    // compute normals
    igl::per_face_normals(OV, OF, normals);

    // Prepare array-based edge data structures and priority queue
    // EMAP is a map from faces to edges.
    // Index into it like EMAP(face + i*F.rows()) where i is an edge index
    // between 0 and 2 corresponding to the three edges of a triangle.
    VectorXi EMAP;

    // E is a map from edges to vertices. Given some edge index e,
    // E(e, 0) and E(e, 1) are the two vertices that the edge is composed of.
    MatrixXi E;

    // EF is a map from edges to faces. For some edge index e,
    // EF(e, 0) and E(e, 1) are the two faces that contain the edge e.
    MatrixXi EF;

    // EI is a map from edges to face corners. For some edge index e,
    // EI(e, 0) is the index i such that EMAP(EF(e, 0) + i*F.rows()) == e and
    // EI(e, 1) is the index i such that EMAP(EF(e, 1) + i*F.rows()) == e.
    MatrixXi EI;

    typedef std::set<std::pair<double, int>> PriorityQueue;
    // Q stores the list of possible edge collapses and their costs
    PriorityQueue Q;
    std::vector<PriorityQueue::iterator> Qit;
    // If an edge were collapsed, we'd collapse it to these points:
    MatrixXd C;

    // Keep some info on edge collapses for reversal and debug reasons
    int num_collapsed;
    std::vector<MeshModification> mods;
    std::vector<int> iters;
    int total_decimations = 0;

    const auto &reset_view = [&]() {
        viewer.data.clear();
        viewer.data.set_mesh(V, F);
        switch (color_mode) {
        case DISTANCE_VISUALIZATION:
            generate_distance_field();
        case COST_VISUALIZATION:
            viewer.data.set_colors(colors);
            break;
        case SOLID:
            viewer.data.set_colors(RowVector3d(1.0, 1.0, 1.0));
            break;
        }
        viewer.data.set_face_based(false);
    };

    // Function to reset original mesh and data structures
    const auto &reset = [&]() {
        total_decimations = 0;
        mods.clear();
        iters.clear();
        F = OF;
        V = OV;
        igl::edge_flaps(F, E, EMAP, EF, EI);
        Qit.resize(E.rows());

        C.resize(E.rows(), V.cols());
        colors.resize(V.rows(), 3);
        colors.setZero();
        VectorXd costs(V.rows());
        costs.setZero();
        for (int e = 0; e < E.rows(); e++) {
            double cost = e;
            RowVectorXd p(1, 3);

            shortest_edge_and_midpoint(e, V, F, E, EMAP, EF, EI, cost, p);
            C.row(e) = p;
            Qit[e] = Q.insert(std::pair<double, int>(cost, e)).first;
            costs(E(e, 0)) += cost;
            costs(E(e, 1)) += cost;
        }
        igl::jet(costs, true, colors);
        num_collapsed = 0;
        reset_view();
    };

    const auto &collapse_edges = [&](igl::viewer::Viewer &viewer) -> bool {
        // If animating then collapse 10% of edges
        if (viewer.core.is_animating && !Q.empty()) {
            bool something_collapsed = false;
            // collapse edge
            const int num_iters = 50;

            // Store the state from before the collapse so that it can be
            // reversed later.
            MatrixXd prev_V = V;
            MatrixXi prev_F = F;
            MatrixXi prev_E = E;
            num_collapsed = 0;

            int total_failures = 0; // If a certain number of failures have
                                    // occurred, we exit an infinte fail loop.

            for (int j = 0; j < num_iters; j++) {
                int e, e1, e2, f1, f2;
                std::vector<int> faceInd, vertInd;

                if (Q.empty())
                    break;

                if (!collapse_edge(shortest_edge_and_midpoint, V, F, E, EMAP,
                                   EF, EI, Q, Qit, C, e, e1, e2, f1, f2,
                                   faceInd)) {
                    total_failures++;
                    j--;
                    if (total_failures > 1000) {
                        break;
                    }
                    continue;
                } else {
                    total_decimations++;
                    num_collapsed++;
                }

                MatrixXi faces(faceInd.size() + 2, 3);
                faceInd.push_back(f1);
                faceInd.push_back(f2);
                for (int i = 0; i < faceInd.size(); i++) {
                    faces.row(i) = prev_F.row(faceInd[i]);
                    // cout << "ffF" << faces.row(i) << endl;
                }

                MatrixXd verts(2, 3);
                vertInd.push_back(prev_E(e, 0));
                vertInd.push_back(prev_E(e, 1));
                for (int i = 0; i < vertInd.size(); i++) {
                    verts.row(i) = prev_V.row(vertInd[i]);
                }

                mods.push_back(
                    MeshModification(vertInd, verts, faceInd, faces));
                something_collapsed = true;
            }
            if (something_collapsed) {
                iters.push_back(num_collapsed);
                reset_view();
            }
        }
        cout << "Collapsed an Edge\n"
             << "Decimations: " << total_decimations << "\n";
        return false;
    };

    // function to reverse edge collapse
    const auto &uncollapse_edges = [&](igl::viewer::Viewer &viewer) -> bool {
        if (viewer.core.is_animating && !mods.empty() && !iters.empty()) {

            int max_iter = iters.back();
            iters.pop_back();

            for (int i = 0; i < max_iter; i++) {
                MeshModification mod = mods.back();
                mods.pop_back();
                total_decimations--;

                for (int i = 0; i < mod.vertInd.size(); i++) {
                    V.row(mod.vertInd[i]) = mod.verts.row(i);
                }

                for (int i = 0; i < mod.faceInd.size(); i++) {
                    F.row(mod.faceInd[i]) = mod.faces.row(i);
                }
            }

            reset_view();
            cout << "Uncollapsed an Edge\n"
                 << "Decimations: " << total_decimations << "\n";
        }
    };

    const auto &save_images = [&]() -> bool {
        reset();
        viewer.draw();

        save_screenshot(viewer, "images/before.png");
        char fn[100];
        char command[512];
        ofstream distfile("surface_distances", ofstream::trunc);
        for (int i = 0; i <= 50; i++) {
            collapse_edges(viewer);
            distfile << generate_distance_field() << endl;
            viewer.draw();
            sprintf(fn, "images/after%03d.png", i);
            save_screenshot(viewer, fn);
            sprintf(command, "composite images/before.png "
                             "images/after%03d.png -compose difference "
                             "images/diff%03d.png ",
                    i, i);
            system(command);
            sprintf(command, "composite images/after%03d.png "
                             "images/after%03d.png -compose difference "
                             "images/delta%03d.png ",
                    i, i - 1, i);
            system(command);
            cout << "Step " << i << " / 100" << endl;
        }
        distfile.close();
        exit(EXIT_SUCCESS);

    };

    const auto &key_down = [&](igl::viewer::Viewer &viewer, unsigned char key,
                               int mod) -> bool {
        switch (key) {
        case ' ':
            viewer.core.is_animating ^= 1;
            break;
        case 'R':
        case 'r':
            reset();
            break;
        case '1':
            collapse_edges(viewer);
            break;
        case '2':
            uncollapse_edges(viewer);
            break;
        case '3':
            save_images();
            break;
        case 'S':
        case 's':
            save_screenshot(viewer, "images/screen.png");
            cout << "saved screen to images/screen.png" << endl;
            break;
        case 'C':
        case 'c':
            ((int &)color_mode)++;
            ((int &)color_mode) %= MAX_COLOR_MODE;
            reset_view();
            break;
        case 'F':
        case 'f':
            cost_function_n++;
            cost_function_n %= cost_functions.size();
            shortest_edge_and_midpoint =
                *(cost_functions.begin() + cost_function_n);
            reset();
            break;
        case 'g':
        case 'G':
            cout << generate_distance_field() << endl;
            break;
        default:
            return false;
        }
        return true;
    };

    const auto &s_option = [&](igl::viewer::Viewer &viewer) -> bool {
        if (argc >= 4) {
            for (char c : string(argv[3])) {
                switch (c) {
                case 's':
                    save_images();
                    break;
                case 'l':
                    viewer.core.shininess = 1.0;
                    viewer.core.lighting_factor = 0.0;
                    break;
                }
            }
        }
    };

    reset();
    viewer.core.is_animating = true;
    viewer.callback_key_pressed = key_down;
    viewer.callback_init = s_option;
    viewer.core.show_lines = false;
    viewer.core.camera_zoom = 2.0;
    return viewer.launch();
}
示例#6
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[])
{
    QGuiApplication app(argc, argv);
    QGuiApplication::setApplicationName("RTC Evaluation");
    QGuiApplication::setApplicationVersion("Revision 1");

    ///////////////////////////////////// #1 CLI Parser /////////////////////////////////////
    QCommandLineParser parser;
    parser.setApplicationDescription("RTC Evaluation");
    parser.addHelpOption();
    parser.addVersionOption();

    // MEG Source Directory
    QCommandLineOption srcDirectoryOption(QStringList() << "s" << "meg-source-directory",
            QCoreApplication::translate("main", "Read MEG (fwd, cov, raw, eve) source files from <directory>."),
            QCoreApplication::translate("main", "directory"),
            "./MNE-sample-data/MEG/sample/");
    parser.addOption(srcDirectoryOption);

    // Forward Solution File
    QCommandLineOption fwdFileOption(QStringList() << "fwd" << "forward-solution",
            QCoreApplication::translate("main", "The forward solution <file>."),
            QCoreApplication::translate("main", "file"),
            "sample_audvis-meg-eeg-oct-6-fwd.fif");
    parser.addOption(fwdFileOption);

    // Raw MEG File
    QCommandLineOption rawFileOption(QStringList() << "raw" << "raw-file",
            QCoreApplication::translate("main", "The raw MEG data <file>."),
            QCoreApplication::translate("main", "file"),
            "sample_audvis_raw.fif");
    parser.addOption(rawFileOption);

    // Event File
    QCommandLineOption eveFileOption(QStringList() << "eve" << "event-file",
            QCoreApplication::translate("main", "The event <file>."),
            QCoreApplication::translate("main", "file"),
            "sample_audvis_raw-eve.fif");
    parser.addOption(eveFileOption);

    // Event Num
    QCommandLineOption evenNumOption(QStringList() << "evenum" << "event-number",
            QCoreApplication::translate("main", "The <event number>."),
            QCoreApplication::translate("main", "event"),
            "1");//2;//3;//4;
    parser.addOption(evenNumOption);

    // FS Subject Directory
    QCommandLineOption subjDirectoryOption(QStringList() << "subjdir" << "subject-directory",
            QCoreApplication::translate("main", "The FreeSurfer <subjects directory>."),
            QCoreApplication::translate("main", "directory"),
            "./MNE-sample-data/subjects");
    parser.addOption(subjDirectoryOption);

    // FS Subject
    QCommandLineOption subjIdOption(QStringList() << "subjid" << "subject-id",
            QCoreApplication::translate("main", "The FreeSurfer <subject id>."),
            QCoreApplication::translate("main", "subject id"),
            "sample");
    parser.addOption(subjIdOption);

    // Target Directory
    QCommandLineOption targetDirectoryOption(QStringList() << "t" << "target-directory",
            QCoreApplication::translate("main", "Copy all result files into <directory>."),
            QCoreApplication::translate("main", "directory"));
    parser.addOption(targetDirectoryOption);

    // Target Prefix
    QCommandLineOption targetPrefixOption(QStringList() << "p" << "prefix",
            QCoreApplication::translate("main", "The result file's <prefix>."),
            QCoreApplication::translate("main", "prefix"));
    parser.addOption(targetPrefixOption);

    // tmin
    QCommandLineOption tMinOption(QStringList() << "tmin" << "t-min",
            QCoreApplication::translate("main", "The starting time point <tmin>."),
            QCoreApplication::translate("main", "tmin"),
            "0.1");
    parser.addOption(tMinOption);

    // tmax
    QCommandLineOption tMaxOption(QStringList() << "tmax" << "t-max",
            QCoreApplication::translate("main", "The end time point <tmax>."),
            QCoreApplication::translate("main", "tmax"),
            "0.2");
    parser.addOption(tMaxOption);

    // Process the actual command line arguments given by the user
    parser.process(app);


    //////////////////////////////// #2 get parsed values /////////////////////////////////

    //Sources
    QString sFwdName = parser.value(srcDirectoryOption)+parser.value(fwdFileOption);
    qDebug() << "Forward Solution" << sFwdName;

    QString sRawName = parser.value(srcDirectoryOption)+parser.value(rawFileOption);
    qDebug() << "Raw data" << sRawName;

    QString t_sEventName = parser.value(srcDirectoryOption)+parser.value(eveFileOption);
    qDebug() << "Events" << t_sEventName;

    qint32 eveNum = (qint32)parser.value(evenNumOption).toInt();
    qDebug() << "Event Number" << eveNum;

    QString t_sSubjectsDir = parser.value(subjDirectoryOption);
    qDebug() << "Subjects Directory" << t_sSubjectsDir;

    QString t_sSubject = parser.value(subjIdOption);
    qDebug() << "Subject" << t_sSubject;

    //Targets
    QString sTargetDir = parser.value(targetDirectoryOption);
    qDebug() << "Target Directory" << sTargetDir;

    QString sTargetPrefix = parser.value(targetPrefixOption);
    qDebug() << "Target Prefix" << sTargetPrefix;

    //Parameters
    float tmin = (float)parser.value(tMinOption).toFloat();
    qDebug() << "tMin" << tmin;

    float tmax = (float)parser.value(tMaxOption).toFloat();
    qDebug() << "tMax" << tmax;

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


    AnnotationSet t_annotationSet(t_sSubject, 2, "aparc.a2009s", t_sSubjectsDir);

//    std::cout << "LabelIDs:\n" << t_annotationSet[0].getColortable().getLabelIds() << std::endl;

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

    QFile t_fileRaw(sRawName);


//    bool doMovie = false;//true;

    qint32 numDipolePairs = 1;

    bool keep_comp = false;
    fiff_int_t dest_comp = 0;
    bool 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 = 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
        }
    }

//    std::cout << "Events:\n" << events << std::endl;

    //
    //    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) == eveNum)
        {
            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 = eveNum;
            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();
    }




    //
    // Init RAP-MUSIC
    //
    RapMusic t_rapMusic(t_clusteredFwd, false, numDipolePairs);




    //
    // calculate the average
    //
    for(qint32 numAverages = 1; numAverages <= 20; numAverages += 1)
    {
        for(qint32 it = 0; it <= 30; ++it)
        {
            //
            // calculate the average
            //
            VectorXi vecSel(numAverages);
            srand (time(NULL)); // initialize random seed

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

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

//            QString sSelFile = QString("aveInfo_%1_%2.txt").arg(numAverages).arg(it);
//            std::ofstream selFile(sSelFile.toLatin1().constData());
//            if (selFile.is_open())
//            {
//              selFile << vecSel << '\n';
//            }


            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

//            if(doMovie)
//                t_pwlRapMusic.setStcAttr(200,0.5);

            MNESourceEstimate sourceEstimate = t_rapMusic.calculateInverse(pickedEvoked);

//            std::cout << "Source Estimate:\n" << sourceEstimate.data << std::endl;

//            std::cout << "Source Estimate vertices:\n" << sourceEstimate.vertices << std::endl;



            if(!sourceEstimate.isEmpty())
            {
                QString t_sFileNameStc = sTargetDir+QString("%1_%2_ave_it_%3.stc").arg(sTargetPrefix).arg(numAverages).arg(it);

                qDebug() << "Write to:" << t_sFileNameStc;


                QDir dir(sTargetDir);
                if (!dir.exists()) {
                    dir.mkpath(".");
                }

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

    return 0;//app.exec();
}
示例#7
0
文件: main.cpp 项目: GBeret/mne-cpp
/**
* 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[])
{
    QGuiApplication app(argc, argv);
    QGuiApplication::setApplicationName("MNE ROI Cluster Evaluation");
    QGuiApplication::setApplicationVersion("Revision 2");

    ///////////////////////////////////// #1 CLI Parser /////////////////////////////////////
    QCommandLineParser parser;
    parser.setApplicationDescription("MNE ROI Cluster Evaluation");
    parser.addHelpOption();
    parser.addVersionOption();

    // MEG Source Directory
    QCommandLineOption srcDirectoryOption(QStringList() << "s" << "meg-source-directory",
            QCoreApplication::translate("main", "Read MEG (fwd, cov, raw, eve) source files from <directory>."),
            QCoreApplication::translate("main", "directory"),
            "./MNE-sample-data/MEG/sample/");
    parser.addOption(srcDirectoryOption);

    // Forward Solution File
    QCommandLineOption fwdFileOption(QStringList() << "fwd" << "forward-solution",
            QCoreApplication::translate("main", "The forward solution <file>."),
            QCoreApplication::translate("main", "file"),
            "sample_audvis-meg-eeg-oct-6-fwd.fif");
    parser.addOption(fwdFileOption);

    // Fixed Forward Solution File
    QCommandLineOption xfwdFileOption(QStringList() << "xfwd" << "fixed-forward-solution",
            QCoreApplication::translate("main", "The fixed forward solution <file>."),
            QCoreApplication::translate("main", "file"),
            "sample_audvis-meg-eeg-oct-6-fwd-fixed.fif");//"D:/Data/MEG/mind006/mind006_051209_auditory01_raw-oct-6-fwd-fixed.fif");
    parser.addOption(xfwdFileOption);

    // Covariance File
    QCommandLineOption covFileOption(QStringList() << "cov" << "covariance",
            QCoreApplication::translate("main", "The covariance <file>."),
            QCoreApplication::translate("main", "file"),
            "sample_audvis-cov.fif");
    parser.addOption(covFileOption);

    // Raw MEG File
    QCommandLineOption rawFileOption(QStringList() << "raw" << "raw-file",
            QCoreApplication::translate("main", "The raw MEG data <file>."),
            QCoreApplication::translate("main", "file"),
            "sample_audvis_raw.fif");
    parser.addOption(rawFileOption);

    // Event File
    QCommandLineOption eveFileOption(QStringList() << "eve" << "event-file",
            QCoreApplication::translate("main", "The event <file>."),
            QCoreApplication::translate("main", "file"),
            "sample_audvis_raw-eve.fif");
    parser.addOption(eveFileOption);

    // Event Num
    QCommandLineOption evenNumOption(QStringList() << "evenum" << "event-number",
            QCoreApplication::translate("main", "The <event number>."),
            QCoreApplication::translate("main", "event"),
            "1");//2;//3;//4;
    parser.addOption(evenNumOption);

    // FS Subject Directory
    QCommandLineOption subjDirectoryOption(QStringList() << "subjdir" << "subject-directory",
            QCoreApplication::translate("main", "The FreeSurfer <subjects directory>."),
            QCoreApplication::translate("main", "directory"),
            "./MNE-sample-data/subjects");
    parser.addOption(subjDirectoryOption);

    // FS Subject
    QCommandLineOption subjIdOption(QStringList() << "subjid" << "subject-id",
            QCoreApplication::translate("main", "The FreeSurfer <subject id>."),
            QCoreApplication::translate("main", "subject id"),
            "sample");
    parser.addOption(subjIdOption);

    // Target Directory
    QCommandLineOption targetDirectoryOption(QStringList() << "t" << "target-directory",
            QCoreApplication::translate("main", "Copy all result files into <directory>."),
            QCoreApplication::translate("main", "directory"));
    parser.addOption(targetDirectoryOption);

    // Target Prefix
    QCommandLineOption targetPrefixOption(QStringList() << "p" << "prefix",
            QCoreApplication::translate("main", "The result file's <prefix>."),
            QCoreApplication::translate("main", "prefix"));
    parser.addOption(targetPrefixOption);

    //// Source estimate parameters ////
    // SNR
    QCommandLineOption snrOption(QStringList() << "snr" << "signal-to-noise-ratio",
            QCoreApplication::translate("main", "The <snr> estimation for the given data file."),
            QCoreApplication::translate("main", "snr"),
            "1.0");//0.1f;//1.0f;//3.0f;
    parser.addOption(snrOption);

    // METHOD
    QCommandLineOption methodOption(QStringList() << "m" << "method",
            QCoreApplication::translate("main", "The estimation <method>."),
            QCoreApplication::translate("main", "method"),
            "dSPM");//"MNE" | "dSPM" | "sLORETA"
    parser.addOption(methodOption);

    // File Name Clustered Inverse Operator
    QCommandLineOption clustInvFileOption(QStringList() << "icf" << "inverse-clustered-file",
            QCoreApplication::translate("main", "Target <file> to store clustered inverse operator to."),
            QCoreApplication::translate("main", "file"));
    parser.addOption(clustInvFileOption);

    // File Name of the Source Estimate
    QCommandLineOption stcFileOption(QStringList() << "stcf" << "stc-file",
            QCoreApplication::translate("main", "Target <stcfile> to store stc to."),
            QCoreApplication::translate("main", "file"));//"mind006_051209_auditory01.stc"
    parser.addOption(stcFileOption);


    // Process the actual command line arguments given by the user
    parser.process(app);


    //////////////////////////////// #2 get parsed values /////////////////////////////////

    //Sources
    QString sFwdName = parser.value(srcDirectoryOption)+parser.value(fwdFileOption);
    qDebug() << "Forward Solution" << sFwdName;

    QString sXFwdName = parser.value(srcDirectoryOption)+parser.value(xfwdFileOption);
    qDebug() << "Fixed Forward Solution" << sXFwdName;
//    QFile t_fileXFwd(sXFwdName);

    QString sCovName = parser.value(srcDirectoryOption)+parser.value(covFileOption);
    qDebug() << "Covariance matrix" << sCovName;

    QString sRawName = parser.value(srcDirectoryOption)+parser.value(rawFileOption);
    qDebug() << "Raw data" << sRawName;

    QString t_sEventName = parser.value(srcDirectoryOption)+parser.value(eveFileOption);
    qDebug() << "Events" << t_sEventName;

    qint32 eveNum = (qint32)parser.value(evenNumOption).toInt();
    qDebug() << "Event Number" << eveNum;

    QString t_sSubjectsDir = parser.value(subjDirectoryOption);
    qDebug() << "Subjects Directory" << t_sSubjectsDir;

    QString t_sSubject = parser.value(subjIdOption);
    qDebug() << "Subject" << t_sSubject;

    AnnotationSet t_annotationSet(t_sSubject, 2, "aparc.a2009s", t_sSubjectsDir);
    SurfaceSet t_surfSet(t_sSubject, 2, "white", t_sSubjectsDir);

    //Targets
    QString sTargetDir = parser.value(targetDirectoryOption);
    qDebug() << "Target Directory" << sTargetDir;

    QString sTargetPrefix = parser.value(targetPrefixOption);
    qDebug() << "Target Prefix" << sTargetPrefix;

    //// Source estimate parameters ////
    double snr = parser.value(snrOption).toFloat();
    qDebug() << "SNR" << snr;

    QString method = parser.value(methodOption);
    qDebug() << "Method" << method;

    QString t_sFileNameClusteredInv = parser.value(clustInvFileOption);
    qDebug() << "Store clustered inverse operator to:" << t_sFileNameClusteredInv;

    QString t_sFileNameStc = parser.value(stcFileOption);
    qDebug() << "Store stc to:" << t_sFileNameStc;




    //OLD
//    QFile t_fileFwd("./MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif");
//    QFile t_fileCov("./MNE-sample-data/MEG/sample/sample_audvis-cov.fif");
//    QFile t_fileRaw("./MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
//    QString t_sEventName = "./MNE-sample-data/MEG/sample/sample_audvis_raw-eve.fif";
//    AnnotationSet t_annotationSet("sample", 2, "aparc.a2009s", "./MNE-sample-data/subjects");
//    SurfaceSet t_surfSet("sample", 2, "white", "./MNE-sample-data/subjects");

//    QFile t_fileFwd("D:/Data/MEG/mind006/mind006_051209_auditory01_raw-oct-6p-fwd.fif");
//    QFile t_fileCov("D:/Data/MEG/mind006/mind006_051209_auditory01_raw-cov.fif");
//    QFile t_fileRaw("D:/Data/MEG/mind006/mind006_051209_auditory01_raw.fif");
//    QString t_sEventName = "D:/Data/MEG/mind006/mind006_051209_auditory01_raw-eve.fif";
//    AnnotationSet t_annotationSet("mind006", 2, "aparc.a2009s", "D:/Data/subjects");
//    SurfaceSet t_surfSet("mind006", 2, "white", "D:/Data/subjects");


    ///////////////////////////////////// #3 read data //////////////////////////////////////
    qint32 event = eveNum;//1;

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

    bool keep_comp = false;
    fiff_int_t dest_comp = 0;
    bool pick_all  = true;

    qint32 k, p;

    //
    //   Setup for reading the raw data
    //
    QFile t_fileRaw(sRawName);
    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);
    }

    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 = 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;
        }
        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());
//    std::cout << "Events:\n" << events << std::endl;
    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;
        }
    }

    //DEBUG Output
    if(data.size() > 0)
    {
        printf("Sampling frequency, %f\n", raw.info.sfreq);

        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();
    }

    /////////////////////////////////// #4 process data /////////////////////////////////////

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


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

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

//    // Load data
//    fiff_int_t setno = 1;
//    QPair<QVariant, QVariant> baseline(QVariant(), 0);
//    FiffEvoked evoked(t_fileEvoked, setno, baseline);
//    if(evoked.isEmpty())
//        return 1;

    QFile t_fileFwd(sFwdName);
    MNEForwardSolution t_Fwd(t_fileFwd);
    if(t_Fwd.isEmpty())
        return 1;

    QFile t_fileFwdFixed(sXFwdName);
    MNEForwardSolution t_FwdFixed(t_fileFwdFixed);
    if(t_FwdFixed.isEmpty())
        return 1;

    QFile t_fileCov(sCovName);
    FiffCov noise_cov(t_fileCov);

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


    qDebug() << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 1. t_Fwd <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<";

    QString sG = sTargetDir + sTargetPrefix + QString("G.txt");
    std::ofstream ofs_G(sG.toUtf8().constData(), std::ofstream::out);
    if (ofs_G.is_open())
    {
        printf("writing to %s\n",sG.toUtf8().constData());
        ofs_G << t_Fwd.sol->data << '\n';
    }
    else
        printf("Not writing to %s\n",sG.toUtf8().constData());
    ofs_G.close();

//    qDebug() << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 1. t_Fwd_whitened <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<";
//    //
//    // Whiten L1 gain matrix
//    //
//    MatrixXd t_Fwd_whitened(0,0);

//    //
//    // Whiten gain matrix before clustering -> cause diffenerent units Magnetometer, Gradiometer and EEG
//    //
//    if(!noise_cov.isEmpty() && !evoked.info.isEmpty())
//    {
//        FiffInfo p_outFwdInfo;
//        FiffCov p_outNoiseCov;
//        MatrixXd p_outWhitener;
//        qint32 p_outNumNonZero;
//        //do whitening with noise cov
//        t_Fwd.prepare_forward(evoked.info, noise_cov, false, p_outFwdInfo, t_Fwd_whitened, p_outNoiseCov, p_outWhitener, p_outNumNonZero);
//        printf("\tWhitening the forward solution.\n");

//        t_Fwd_whitened = p_outWhitener*t_Fwd_whitened;
//    }

//    QString sG_Whitened = sTargetDir + sTargetPrefix + QString("G_whitened.txt");
//    std::ofstream ofs_G_Whitened(sG_Whitened.toUtf8().constData(), std::ofstream::out);//"G_whitened.txt", std::ofstream::out);
//    if (ofs_G_Whitened.is_open())
//    {
//        printf("writing to %s\n",sG_Whitened.toUtf8().constData());
//        ofs_G_Whitened << t_Fwd_whitened << '\n';
//    }
//    else
//        printf("Not writing to %s\n",sG_Whitened.toUtf8().constData());
//    ofs_G_Whitened.close();

//    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    //
    // Cluster forward solution;
    //
    MatrixXd D_L1;

    std::cout << "t_Fwd " << t_Fwd.sol->data.rows() << " x " << t_Fwd.sol->data.cols() << std::endl;

    MNEForwardSolution t_clusteredFwd_L1 = t_Fwd.cluster_forward_solution(t_annotationSet, 20, D_L1, noise_cov, evoked.info, "cityblock");
    QString sCILHL1 = sTargetDir + sTargetPrefix + QString("ClusterInfoLH_L1.txt");
    t_clusteredFwd_L1.src[0].cluster_info.write(sCILHL1);
    QString sCIRHL1 = sTargetDir + sTargetPrefix + QString("ClusterInfoRH_L1.txt");
    t_clusteredFwd_L1.src[1].cluster_info.write(sCIRHL1);


    qDebug() << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 2. t_clusteredFwd_L1 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<";

    QString sG_L1 = sTargetDir + sTargetPrefix + QString("G_L1.txt");
    std::ofstream ofs_G_L1(sG_L1.toUtf8().constData(), std::ofstream::out);
    if (ofs_G_L1.is_open())
    {
        printf("writing to %s\n",sG_L1.toUtf8().constData());
        ofs_G_L1 << t_clusteredFwd_L1.sol->data << '\n';
    }
    else
        printf("Not writing to %s\n",sG_L1.toUtf8().constData());
    ofs_G_L1.close();


//    qDebug() << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 2. t_clusteredFwd_L1_whitened <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<";
//    //
//    // Whiten L1 gain matrix
//    //
//    MatrixXd t_clusteredFwd_L1_whitened(0,0);

//    //
//    // Whiten gain matrix before clustering -> cause diffenerent units Magnetometer, Gradiometer and EEG
//    //
//    if(!noise_cov.isEmpty() && !evoked.info.isEmpty())
//    {
//        FiffInfo p_outFwdInfo;
//        FiffCov p_outNoiseCov;
//        MatrixXd p_outWhitener;
//        qint32 p_outNumNonZero;
//        //do whitening with noise cov
//        t_clusteredFwd_L1.prepare_forward(evoked.info, noise_cov, false, p_outFwdInfo, t_clusteredFwd_L1_whitened, p_outNoiseCov, p_outWhitener, p_outNumNonZero);
//        printf("\tWhitening the forward solution.\n");

//        t_clusteredFwd_L1_whitened = p_outWhitener*t_clusteredFwd_L1_whitened;
//    }

//    QString sG_L1_Whitened = sTargetDir + sTargetPrefix + QString("G_L1_whitened.txt");
//    std::ofstream ofs_G_L1_Whitened(sG_L1_Whitened.toUtf8().constData(), std::ofstream::out);//"G_L1_whitened.txt", std::ofstream::out);
//    if (ofs_G_L1_Whitened.is_open())
//    {
//        printf("writing to %s\n",sG_L1_Whitened.toUtf8().constData());
//        ofs_G_L1_Whitened << t_clusteredFwd_L1_whitened << '\n';
//    }
//    else
//        printf("Not writing to %s\n",sG_L1_Whitened.toUtf8().constData());
//    ofs_G_L1_Whitened.close();

//    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    std::cout << "D_L1 " << D_L1.rows() << " x " << D_L1.cols() << std::endl;
    std::cout << "t_clusteredFwd_L1 " << t_clusteredFwd_L1.sol->data.rows() << " x " << t_clusteredFwd_L1.sol->data.cols() << std::endl;

    MatrixXd D_L2;

    MNEForwardSolution t_clusteredFwd_L2 = t_Fwd.cluster_forward_solution(t_annotationSet, 20, D_L2, noise_cov, evoked.info, "sqeuclidean");
    QString sCILH_L2 = sTargetDir + sTargetPrefix + QString("ClusterInfoLH_L2.txt");
    t_clusteredFwd_L2.src[0].cluster_info.write(sCILH_L2);
    QString sCIRH_L2 = sTargetDir + sTargetPrefix + QString("ClusterInfoRH_L2.txt");
    t_clusteredFwd_L2.src[1].cluster_info.write(sCIRH_L2);

    std::cout << "D_L2 " << D_L2.rows() << " x " << D_L2.cols() << std::endl;
    std::cout << "t_clusteredFwd_L2 " << t_clusteredFwd_L2.sol->data.rows() << " x " << t_clusteredFwd_L2.sol->data.cols() << std::endl;


    qDebug() << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 3. t_clusteredFwd_L2 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<";

    QString sG_L2 = sTargetDir + sTargetPrefix + QString("G_L2.txt");
    std::ofstream ofs_G_L2(sG_L2.toUtf8().constData(), std::ofstream::out);
    if (ofs_G_L2.is_open())
    {
        printf("writing to %s\n",sG_L2.toUtf8().constData());
        ofs_G_L2 << t_clusteredFwd_L2.sol->data << '\n';
    }
    else
        printf("Not writing to %s\n",sG_L2.toUtf8().constData());
    ofs_G_L2.close();

//    qDebug() << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 3. t_clusteredFwd_L2_whitened <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<";
//    //
//    // Whiten L1 gain matrix
//    //
//    MatrixXd t_clusteredFwd_L2_whitened(0,0);

//    //
//    // Whiten gain matrix before clustering -> cause diffenerent units Magnetometer, Gradiometer and EEG
//    //
//    if(!noise_cov.isEmpty() && !evoked.info.isEmpty())
//    {
//        FiffInfo p_outFwdInfo;
//        FiffCov p_outNoiseCov;
//        MatrixXd p_outWhitener;
//        qint32 p_outNumNonZero;
//        //do whitening with noise cov
//        t_clusteredFwd_L2.prepare_forward(evoked.info, noise_cov, false, p_outFwdInfo, t_clusteredFwd_L2_whitened, p_outNoiseCov, p_outWhitener, p_outNumNonZero);
//        printf("\tWhitening the forward solution.\n");

//        t_clusteredFwd_L2_whitened = p_outWhitener*t_clusteredFwd_L2_whitened;
//    }

//    QString sG_L2_Whitened = sTargetDir + sTargetPrefix + QString("G_L2_whitened.txt");
//    std::ofstream ofs_G_L2_Whitened(sG_L2_Whitened.toUtf8().constData(), std::ofstream::out);//"G_L2_whitened.txt", std::ofstream::out);
//    if (ofs_G_L2_Whitened.is_open())
//    {
//        printf("writing to %s\n",sG_L2_Whitened.toUtf8().constData());
//        ofs_G_L2_Whitened << t_clusteredFwd_L2_whitened << '\n';
//    }
//    else
//        printf("Not writing to %s\n",sG_L2_Whitened.toUtf8().constData());
//    ofs_G_L2_Whitened.close();

    return CommandLineOk;

//    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


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

    QFile t_fileSelectedFwd(sFwdName);


//    QFile t_fileFwd("D:/Data/MEG/mind006/mind006_051209_auditory01_raw-oct-6p-fwd.fif");
//    QFile t_fileCov("D:/Data/MEG/mind006/mind006_051209_auditory01_raw-cov.fif");
//    QFile t_fileRaw("D:/Data/MEG/mind006/mind006_051209_auditory01_raw.fif");
//    QString t_sEventName = "D:/Data/MEG/mind006/mind006_051209_auditory01_raw-eve.fif";
//    AnnotationSet t_annotationSet("mind006", 2, "aparc.a2009s", "D:/Data/subjects");
//    SurfaceSet t_surfSet("mind006", 2, "white", "D:/Data/subjects");


    MNEForwardSolution t_selectedRawFwd(t_fileSelectedFwd);
    if(t_selectedRawFwd.isEmpty())
        return 1;

    MatrixXd D_selected;
    MNEForwardSolution t_selectedFwd = t_selectedRawFwd.reduce_forward_solution(t_clusteredFwd_L2.isFixedOrient() ? t_clusteredFwd_L2.sol->data.cols() : t_clusteredFwd_L2.sol->data.cols()/3, D_selected);

//    qDebug() << "#### t_selectedFwd" << t_selectedFwd.sol->data.rows() << "x" << t_selectedFwd.sol->data.cols();

    MNEInverseOperator inverse_operator_selected(info, t_selectedFwd, noise_cov, 0.2f, 0.8f);

    MNEInverseOperator inverse_operator_clustered_L1(info, t_clusteredFwd_L1, noise_cov, 0.2f, 0.8f);

    MNEInverseOperator inverse_operator_clustered_L2(info, t_clusteredFwd_L2, noise_cov, 0.2f, 0.8f);

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

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


    //
    // Compute inverse solution
    //
    MinimumNorm minimumNormSelected(inverse_operator_selected, lambda2, method);

    MinimumNorm minimumNormClustered_L1(inverse_operator_clustered_L1, lambda2, method);

    MinimumNorm minimumNormClustered_L2(inverse_operator_clustered_L2, lambda2, method);

    MinimumNorm minimumNorm(inverse_operator, lambda2, method);


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

//    MNESourceEstimate sourceEstimate;
//    QList<qint64> qVecElapsedTime;
//    for(qint32 i = 0; i < 100; ++i)
//    {
//        //Benchmark time
//        QElapsedTimer timer;
//        timer.start();
//        sourceEstimate = minimumNormClustered.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 sourceEstimateSelected =

    minimumNormSelected.calculateInverse(evoked);

//    MNESourceEstimate sourceEstimateClustered_L1 =

    minimumNormClustered_L1.calculateInverse(evoked);

//    MNESourceEstimate sourceEstimateClustered_L2 =

    minimumNormClustered_L2.calculateInverse(evoked);

//    MNESourceEstimate sourceEstimate =

    minimumNorm.calculateInverse(evoked);
//#endif


//    ////////////////////////////////// original
//    // #### R calculation ####
//    printf("R original calculation\n");
//    MatrixXd M_orig = minimumNorm.getKernel();

//    MatrixXd R_orig = M_orig * t_FwdFixed.sol->data;

//    QString sROrig = sTargetDir + sTargetPrefix + QString("R_orig.txt");
//    std::ofstream ofs_R_orig(sROrig.toUtf8().constData(), std::ofstream::out);//, std::ofstream::out);
//    if (ofs_R_orig.is_open())
//    {
//        printf("writing to %s\n", sROrig.toUtf8().constData());
//        ofs_R_orig << R_orig << '\n';
//    }
//    else
//        printf("Not writing to %s\n", sROrig.toUtf8().constData());
//    ofs_R_orig.close();

//    R_orig.resize(0,0);


//    //ToDo:just original
//    return CommandLineOk;


    ////////////////////////////////// L1 calculations

    MatrixXd D_MT_L1;
    MatrixXd MT_clustered_L1 = minimumNorm.getPreparedInverseOperator().cluster_kernel(t_annotationSet, 20, D_MT_L1, "cityblock");

    // #### R calculation ####
    //// Option II_L1
    //Cluster Inverse operator
    MatrixXd M_L1 = D_L1.transpose() * minimumNorm.getKernel();

    MatrixXd R_L1 = M_L1 * t_FwdFixed.sol->data;


//    QString sTargetDir = parser.value(targetDirectoryOption);
//    qDebug() << "Target Directory" << sTargetDir;

//    QString sTargetPrefix = parser.value(targetPrefixOption);
//    qDebug() << "Target Prefix" << sTargetPrefix;


    QString sR_L1 = sTargetDir + sTargetPrefix + QString("R_L1.txt");

    std::ofstream ofs_R_L1(sR_L1.toUtf8().constData(), std::ofstream::out);//"R_L1.txt", std::ofstream::out);
    if (ofs_R_L1.is_open())
    {
        printf("writing to %s\n",sR_L1.toUtf8().constData());

        ofs_R_L1 << R_L1 << '\n';
    }
    else
        printf("Not writing to %s\n",sR_L1.toUtf8().constData());
    ofs_R_L1.close();

    M_L1.resize(0,0);
    R_L1.resize(0,0);

    //// Option I_L1
    printf("[3]\n");
    MatrixXd M_clusterd_L1 = minimumNormClustered_L1.getKernel();

    printf("[4]\n");
    MatrixXd R_clustered_L1 = M_clusterd_L1 * t_FwdFixed.sol->data;

    QString sRClustered_L1 = sTargetDir + sTargetPrefix + QString("R_clustered_L1.txt");
    std::ofstream ofs_R_clustered_L1(sRClustered_L1.toUtf8().constData(), std::ofstream::out);//, std::ofstream::out);
    if (ofs_R_clustered_L1.is_open())
    {
        printf("writing to %s\n", sRClustered_L1.toUtf8().constData());
        ofs_R_clustered_L1 << R_clustered_L1 << '\n';
    }
    else
        printf("Not writing to %s\n", sRClustered_L1.toUtf8().constData());
    ofs_R_clustered_L1.close();

    M_clusterd_L1.resize(0,0);
    R_clustered_L1.resize(0,0);

//Cluster Operator D_L1
    QString sD_L1 = sTargetDir + sTargetPrefix + QString("D_L1.txt");
    std::ofstream ofs_D_L1(sD_L1.toUtf8().constData(), std::ofstream::out);//"D_L1.txt", std::ofstream::out);
    if (ofs_D_L1.is_open())
    {
        printf("writing to %s\n",sD_L1.toUtf8().constData());
        ofs_D_L1 << D_L1 << '\n';
    }
    else
        printf("Not writing to %s\n",sD_L1.toUtf8().constData());
    ofs_D_L1.close();


    //// Option III_L1
    printf("[5]\n");
    MatrixXd R_MT_clustered_L1 = MT_clustered_L1.transpose() * t_FwdFixed.sol->data;

    QString sRMTClust_L1 = sTargetDir + sTargetPrefix + QString("R_MT_clustered_L1.txt");
    std::ofstream ofs_R_MT_clustered_L1(sRMTClust_L1.toUtf8().constData(), std::ofstream::out);
    if (ofs_R_MT_clustered_L1.is_open())
    {
        printf("writing to %s\n",sRMTClust_L1.toUtf8().constData());
        ofs_R_MT_clustered_L1 << R_MT_clustered_L1 << '\n';
    }
    else
        printf("Not writing to %s\n",sRMTClust_L1.toUtf8().constData());
    ofs_R_MT_clustered_L1.close();

    R_MT_clustered_L1.resize(0,0);

    //Cluster Operator D
    QString sDMT_L1 = sTargetDir + sTargetPrefix + QString("D_MT_L1.txt");
    std::ofstream ofs_D_MT_L1(sDMT_L1.toUtf8().constData(), std::ofstream::out);
    if (ofs_D_MT_L1.is_open())
    {
        printf("writing to %s\n",sDMT_L1.toUtf8().constData());
        ofs_D_MT_L1 << D_MT_L1 << '\n';
    }
    else
        printf("Not writing to %s\n",sDMT_L1.toUtf8().constData());
    ofs_D_MT_L1.close();





    ////////////////////////////////// L2 calculations

    MatrixXd D_MT_L2;
    MatrixXd MT_clustered_L2 = minimumNorm.getPreparedInverseOperator().cluster_kernel(t_annotationSet, 20, D_MT_L2, "sqeuclidean");

    // #### R calculation ####

    //// Option II_L2
    MatrixXd M_L2 = D_L2.transpose() * minimumNorm.getKernel();

    MatrixXd R_L2 = M_L2 * t_FwdFixed.sol->data;


//    QString sTargetDir = parser.value(targetDirectoryOption);
//    qDebug() << "Target Directory" << sTargetDir;

//    QString sTargetPrefix = parser.value(targetPrefixOption);
//    qDebug() << "Target Prefix" << sTargetPrefix;


    QString sR_L2 = sTargetDir + sTargetPrefix + QString("R_L2.txt");

    std::ofstream ofs_R_L2(sR_L2.toUtf8().constData(), std::ofstream::out);//"R_L2.txt", std::ofstream::out);
    if (ofs_R_L2.is_open())
    {
        printf("writing to %s\n",sR_L2.toUtf8().constData());

        ofs_R_L2 << R_L2 << '\n';
    }
    else
        printf("Not writing to %s\n",sR_L2.toUtf8().constData());
    ofs_R_L2.close();

    M_L2.resize(0,0);
    R_L2.resize(0,0);


    //// Option I_L2
    printf("[3]\n");
    MatrixXd M_clusterd_L2 = minimumNormClustered_L2.getKernel();

    printf("[4]\n");
    MatrixXd R_clustered_L2 = M_clusterd_L2 * t_FwdFixed.sol->data;

    QString sRClustered_L2 = sTargetDir + sTargetPrefix + QString("R_clustered_L2.txt");
    std::ofstream ofs_R_clustered_L2(sRClustered_L2.toUtf8().constData(), std::ofstream::out);//, std::ofstream::out);
    if (ofs_R_clustered_L2.is_open())
    {
        printf("writing to %s\n", sRClustered_L2.toUtf8().constData());
        ofs_R_clustered_L2 << R_clustered_L2 << '\n';
    }
    else
        printf("Not writing to %s\n", sRClustered_L2.toUtf8().constData());
    ofs_R_clustered_L2.close();

    M_clusterd_L2.resize(0,0);
    R_clustered_L2.resize(0,0);

//Cluster Operator D_L2
    QString sD_L2 = sTargetDir + sTargetPrefix + QString("D_L2.txt");
    std::ofstream ofs_D_L2(sD_L2.toUtf8().constData(), std::ofstream::out);//"D_L2.txt", std::ofstream::out);
    if (ofs_D_L2.is_open())
    {
        printf("writing to %s\n",sD_L2.toUtf8().constData());
        ofs_D_L2 << D_L2 << '\n';
    }
    else
        printf("Not writing to %s\n",sD_L2.toUtf8().constData());
    ofs_D_L2.close();


    //// Option III_L2
    printf("[5]\n");
    MatrixXd R_MT_clustered_L2 = MT_clustered_L2.transpose() * t_FwdFixed.sol->data;

    QString sRMTClust_L2 = sTargetDir + sTargetPrefix + QString("R_MT_clustered_L2.txt");
    std::ofstream ofs_R_MT_clustered_L2(sRMTClust_L2.toUtf8().constData(), std::ofstream::out);
    if (ofs_R_MT_clustered_L2.is_open())
    {
        printf("writing to %s\n",sRMTClust_L2.toUtf8().constData());
        ofs_R_MT_clustered_L2 << R_MT_clustered_L2 << '\n';
    }
    else
        printf("Not writing to %s\n",sRMTClust_L2.toUtf8().constData());
    ofs_R_MT_clustered_L2.close();

    R_MT_clustered_L2.resize(0,0);

    //Cluster Operator D
    QString sDMT_L2 = sTargetDir + sTargetPrefix + QString("D_MT_L2.txt");
    std::ofstream ofs_D_MT_L2(sDMT_L2.toUtf8().constData(), std::ofstream::out);
    if (ofs_D_MT_L2.is_open())
    {
        printf("writing to %s\n",sDMT_L2.toUtf8().constData());
        ofs_D_MT_L2 << D_MT_L2 << '\n';
    }
    else
        printf("Not writing to %s\n",sDMT_L2.toUtf8().constData());
    ofs_D_MT_L2.close();





    ////////////////////////////////// Selection calculation

    //option d)
    MatrixXd M_selected = minimumNormSelected.getKernel();

//    qDebug() << "M_selected: " << M_selected.rows() << "x" << M_selected.cols();


    printf("[7]\n");
    MatrixXd R_selected= M_selected * t_FwdFixed.sol->data;

    QString sRselected = sTargetDir + sTargetPrefix + QString("R_selected.txt");
    std::ofstream ofs_R_selected(sRselected.toUtf8().constData(), std::ofstream::out);//"R_selected.txt", std::ofstream::out);
    if (ofs_R_selected.is_open())
    {
        printf("writing to %s\n",sRselected.toUtf8().constData());
        ofs_R_selected << R_selected << '\n';
    }
    else
        printf("Not writing to %s\n",sRselected.toUtf8().constData());
    ofs_R_selected.close();

    R_selected.resize(0,0);

    //Cluster Operator D
    QString sDselected = sTargetDir + sTargetPrefix + QString("D_selected.txt");
    std::ofstream ofs_D_selected(sDselected.toUtf8().constData(), std::ofstream::out);//"D_selected.txt", std::ofstream::out);
    if (ofs_D_selected.is_open())
    {
        printf("writing to %s\n",sDselected.toUtf8().constData());
        ofs_D_selected << D_selected << '\n';
    }
    else
        printf("Not writing to %s\n",sDselected.toUtf8().constData());
    ofs_D_selected.close();

    // #### R calculation end ####















    /////////////////////////////////// #5 METHOD I /////////////////////////////////////
    // I) M_D -> I_L1
//    {
//        qDebug() << "METHOD I_L1";
//    }


    /////////////////////////////////// #6 METHOD II /////////////////////////////////////
    // II) D_G^T M -> II_L1
//    {
//        qDebug() << "METHOD II_L1";
//    }


    /////////////////////////////////// #7 METHOD III /////////////////////////////////////
    // III) D^T_{M^T} M -> III_L1
//    {
//        qDebug() << "METHOD III_L1";
//    }


    /////////////////////////////////// #8 METHOD IV /////////////////////////////////////
    // IV) M_D -> I_L2
//    {
//        qDebug() << "METHOD I_L2";
//    }


    /////////////////////////////////// #9 METHOD V /////////////////////////////////////
    // V) D^T_G M -> II_L2
//    {
//        qDebug() << "METHOD II_L2";
//    }


    /////////////////////////////////// #10 METHOD VI /////////////////////////////////////
    // VI) D^T_{M^T} M -> III_L2
//    {
//        qDebug() << "METHOD III_L2";
//    }


    /////////////////////////////////// #11 METHOD VII /////////////////////////////////////
    // VII) M -> IV
//    {
//        qDebug() << "METHOD IV";
//    }






















//    //Condition Numbers Attention - Condition only with fixed orientation!!!!!!!!!
//    VectorXd s;

//    double t_dConditionNumber = MNEMath::getConditionNumber(t_Fwd.sol->data, s);
//    std::cout << "Condition Number:\n" << t_dConditionNumber << std::endl;

//    //
//    QString sKappa = sTargetDir + sTargetPrefix + QString("Kappa.txt");
//    std::ofstream ofs_Kappa(sKappa.toUtf8().constData(), std::ofstream::out);
//    if (ofs_Kappa.is_open())
//    {
//        printf("writing to %s\n",sKappa.toUtf8().constData());
//        ofs_Kappa << t_dConditionNumber << '\n';
//    }
//    else
//        printf("Not writing to %s\n",sKappa.toUtf8().constData());
//    ofs_Kappa.close();

//    // s
//    QString sS = sTargetDir + sTargetPrefix + QString("S.txt");
//    std::ofstream ofs_sS(sS.toUtf8().constData(), std::ofstream::out);
//    if (ofs_sS.is_open())
//    {
//        printf("writing to %s\n",sS.toUtf8().constData());
//        ofs_sS << s << '\n';
//    }
//    else
//        printf("Not writing to %s\n",sS.toUtf8().constData());
//    ofs_sS.close();



//    double t_dConditionNumberClustered_L1 = MNEMath::getConditionNumber(t_clusteredFwd_L1.sol->data, s);
//    std::cout << "Clustered L1 Condition Number:\n" << t_dConditionNumberClustered_L1 << std::endl;

//    //
//    QString sKappaL1 = sTargetDir + sTargetPrefix + QString("Kappa_L1.txt");
//    std::ofstream ofs_KappaL1(sKappaL1.toUtf8().constData(), std::ofstream::out);
//    if (ofs_KappaL1.is_open())
//    {
//        printf("writing to %s\n",sKappaL1.toUtf8().constData());
//        ofs_KappaL1 << t_dConditionNumberClustered_L1 << '\n';
//    }
//    else
//        printf("Not writing to %s\n",sKappaL1.toUtf8().constData());
//    ofs_KappaL1.close();

//    // s
//    QString sSL1 = sTargetDir + sTargetPrefix + QString("S_L1.txt");
//    std::ofstream ofs_SL1(sSL1.toUtf8().constData(), std::ofstream::out);
//    if (ofs_SL1.is_open())
//    {
//        printf("writing to %s\n",sSL1.toUtf8().constData());
//        ofs_SL1 << s << '\n';
//    }
//    else
//        printf("Not writing to %s\n",sSL1.toUtf8().constData());
//    ofs_SL1.close();



//    double t_dConditionNumberClustered_L2 = MNEMath::getConditionNumber(t_clusteredFwd_L2.sol->data, s);
//    std::cout << "Clustered L2 Condition Number:\n" << t_dConditionNumberClustered_L2 << std::endl;

//    // Kappa
//    QString sKappaL2 = sTargetDir + sTargetPrefix + QString("Kappa_L2.txt");
//    std::ofstream ofs_KappaL2(sKappaL2.toUtf8().constData(), std::ofstream::out);
//    if (ofs_KappaL2.is_open())
//    {
//        printf("writing to %s\n",sKappaL2.toUtf8().constData());
//        ofs_KappaL2 << t_dConditionNumberClustered_L2 << '\n';
//    }
//    else
//        printf("Not writing to %s\n",sKappaL2.toUtf8().constData());
//    ofs_KappaL2.close();

//    // s
//    QString sSL2 = sTargetDir + sTargetPrefix + QString("S_L2.txt");
//    std::ofstream ofs_SL2(sSL2.toUtf8().constData(), std::ofstream::out);
//    if (ofs_SL2.is_open())
//    {
//        printf("writing to %s\n",sSL2.toUtf8().constData());
//        ofs_SL2 << s << '\n';
//    }
//    else
//        printf("Not writing to %s\n",sSL2.toUtf8().constData());
//    ofs_SL2.close();


//    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;


    return CommandLineOk;
}
示例#8
0
RcppExport SEXP BMEclustering(SEXP mat, SEXP moda, SEXP nb_cluster, SEXP partition_initiale, SEXP nb_init,SEXP stop_criterion){
	srand(time(0));

	MatrixXi data=convertMatrix<MatrixXi,NumericMatrix>(mat);
	VectorXi modalite=convertvector<VectorXi,NumericVector>(moda);
	datafile dataF(data,modalite);

	NumericMatrix red=convertMatrix<NumericMatrix,MatrixXi>(dataF.Get_mat_datafile());
	VectorXi partition_vbles=convertvector<VectorXi,NumericVector>(partition_initiale);
	MatrixXi m;
	int g=as<int>(nb_cluster);
	//int borne=as<int>(nbiter);
	m.resize(g,partition_vbles.rows());
	for (int k=0;k<g;k++){
		m.row(k)=partition_vbles;
	}
	NumericMatrix test=convertMatrix<NumericMatrix,MatrixXi>(m);
	int nbinit=as<int>(nb_init);
	int borne=as<int>(stop_criterion);
	MCMCAlgo ref(dataF,m,m.rows(),2,1,2,6,borne);
	for (int ini=0;ini<nbinit;ini++){
		MCMCAlgo test(dataF,m,m.rows(),2,1,2,6,borne);
		if (test.Get_best_bic()>ref.Get_best_bic()){
			ref=test;
		}
	}
	//sauvegarde des caractéristiques du modèle
	NumericMatrix model=convertMatrix<NumericMatrix,MatrixXi>(ref.Get_best_omega());
	double bic=ref.Get_best_bic();
	double likelihood=ref.Get_best_like();
	NumericMatrix probapost=convertMatrix<NumericMatrix,MatrixXd>(ref.Sauv_probapost());
	NumericVector localise=convertvector<NumericVector,VectorXi>(dataF.Get_localise());

	vector< vector< NumericVector > > tau;
	vector< vector< vector< NumericVector > > > delta;
	vector< vector< vector< NumericVector > > > alpha;
	vector< vector< double > > rho;
	tau.resize(g);
	rho.resize(g);
	delta.resize(g);
	alpha.resize(g);
	for (int k=0;k<g;k++){
		tau[k].resize(ref.Get_best_omega().row(k).maxCoeff()+1);
		rho[k].resize(ref.Get_best_omega().row(k).maxCoeff()+1);
		delta[k].resize(ref.Get_best_omega().row(k).maxCoeff()+1);
		alpha[k].resize(ref.Get_best_omega().row(k).maxCoeff()+1);
		for (int b=0;b<=ref.Get_best_omega().row(k).maxCoeff();b++){
		//for (int b=0;b<2;b++){
			//vectblock[k][b]=ref.Get_rho(k,b);
			//vector < VectorXd > passe=ref.Get_alpha(k,b);
			if ((ref.Get_best_omega().row(k).array()==b).count()>0){
				vector<VectorXd> passe=ref.Get_alpha(k,b);
				alpha[k][b].resize((ref.Get_best_omega().row(k).array()==b).count());
				for (int loc=0;loc<((ref.Get_best_omega().row(k).array()==b).count());loc++){
					alpha[k][b][loc]=convertvector<NumericVector,VectorXd>(passe[loc]);
				}
			}
			if ((ref.Get_best_omega().row(k).array()==b).count()>1){
				MatrixXi passe=ref.Get_delta(k,b);
				delta[k][b].resize(passe.cols());
				tau[k][b]=convertvector<NumericVector,VectorXd>(ref.Get_tau(k,b));
				for (int loc=0;loc<passe.cols();loc++){
					delta[k][b][loc]=convertvector<NumericVector,VectorXi>(passe.col(loc));
				}
				//delta[k][b]=convertMatrix<NumericMatrix,MatrixXi>(ref.Get_delta(k,b));
				rho[k][b]=ref.Get_rho(k,b);
			}
		}
	}

	List param=List::create(Rcpp::Named("tau")=tau,Rcpp::Named("rho")=rho,Rcpp::Named("delta")=delta,Rcpp::Named("alpha")=alpha,Rcpp::Named("proportions")=convertvector<NumericVector,VectorXd>(ref.Get_propor()));
    List desc_model = List::create(Rcpp::Named("sigma")=model,Rcpp::Named("bic")=bic,Rcpp::Named("likelihood")=likelihood,Rcpp::Named("probapost")=probapost,Rcpp::Named("partition")=localise,Rcpp::Named("nbcluster")=nb_cluster,Rcpp::Named("parameters")=param);

    return desc_model;
}
示例#9
0
void drwnNNGraphImageData::setLabels(const MatrixXi& labels)
{
    DRWN_ASSERT(((size_t)labels.rows() == height()) && ((size_t)labels.cols() == width()));
    _labels = labels;
}
示例#10
0
void mexFunction(
  int nlhs, mxArray *plhs[], 
  int nrhs, const mxArray *prhs[])
{
  using namespace std;
  using namespace Eigen;
  using namespace igl;
  using namespace igl::matlab;

  igl::matlab::MexStream mout;        
  std::streambuf *outbuf = cout.rdbuf(&mout);
  //mexPrintf("Compiled at %s on %s\n",__TIME__,__DATE__);

  MatrixXd P,V,C,N;
  MatrixXi F;
  VectorXi I;
  VectorXd S;
  SignedDistanceType type;
  parse_rhs(nrhs,prhs,P,V,F,type);

  if(F.rows() > 0)
  {
    switch(V.cols())
    {
      case 2:
      {
        // Persistent data not supported for 2D
        signed_distance(P,V,F,type,S,I,C,N);
        break;
      }
      case 3:
      {
        if(g_sign_type != type || g_V != V || g_F != F)
        {
          g_V = V;
          g_F = F;
          g_sign_type = type;
          // Clear the tree
          g_tree.deinit();

          // Prepare distance computation
          g_tree.init(V,F);
          switch(type)
          {
            default:
              assert(false && "Unknown SignedDistanceType");
            case SIGNED_DISTANCE_TYPE_DEFAULT:
            case SIGNED_DISTANCE_TYPE_WINDING_NUMBER:
              g_hier.set_mesh(V,F);
              g_hier.grow();
              break;
            case SIGNED_DISTANCE_TYPE_PSEUDONORMAL:
              // "Signed Distance Computation Using the Angle Weighted Pseudonormal"
              // [Bærentzen & Aanæs 2005]
              per_face_normals(V,F,g_FN);
              per_vertex_normals(V,F,PER_VERTEX_NORMALS_WEIGHTING_TYPE_ANGLE,
                g_FN,g_VN);
              per_edge_normals(
                V,F,PER_EDGE_NORMALS_WEIGHTING_TYPE_UNIFORM,
                g_FN,g_EN,g_E,g_EMAP);
              break;
          }
        }

        N.resize(P.rows(),3);
        S.resize(P.rows(),1);
        I.resize(P.rows(),1);
        C.resize(P.rows(),3);
        //for(int p = 0;p<P.rows();p++)
        igl::parallel_for(P.rows(),[&](const int p)
        {
          const Eigen::RowVector3d q(P(p,0),P(p,1),P(p,2));
          double s,sqrd;
          Eigen::RowVector3d c;
          int i;
          switch(type)
          {
            default:
              assert(false && "Unknown SignedDistanceType");
            case SIGNED_DISTANCE_TYPE_DEFAULT:
            case SIGNED_DISTANCE_TYPE_WINDING_NUMBER:
              signed_distance_winding_number(
                g_tree,g_V,g_F,g_hier,q,s,sqrd,i,c);
              break;
            case SIGNED_DISTANCE_TYPE_PSEUDONORMAL:
            {
              RowVector3d n(0,0,0);
              signed_distance_pseudonormal(
                g_tree,g_V,g_F,g_FN,g_VN,g_EN,g_EMAP,
                q,s,sqrd,i,c,n);
              N.row(p) = n;
              break;
            }
          }
          I(p) = i;
          S(p) = s*sqrt(sqrd);
          C.row(p) = c;
        },10000);
        break;
      }
    }
  }

  switch(nlhs)
  {
    default:
    {
      mexErrMsgTxt(false,"Too many output parameters.");
    }
    case 4:
    {
      prepare_lhs_double(N,plhs+3);
      // Fall through
    }
    case 3:
    {
      prepare_lhs_double(C,plhs+2);
      // Fall through
    }
    case 2:
    {
      prepare_lhs_index(I,plhs+1);
      // Fall through
    }
    case 1:
    {
      prepare_lhs_double(S,plhs+0);
      // Fall through
    }
    case 0: break;
  }

  // Restore the std stream buffer Important!
  std::cout.rdbuf(outbuf);
}
示例#11
0
文件: main.cpp 项目: Lx37/mne-cpp
/**
* 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[])
{
    QGuiApplication a(argc, argv);




//    QFile t_fileFwd("./MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif");
//    QFile t_fileCov("./MNE-sample-data/MEG/sample/sample_audvis-cov.fif");
//    QFile t_fileRaw("./MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
//    QString t_sEventName = "./MNE-sample-data/MEG/sample/sample_audvis_raw-eve.fif";
//    AnnotationSet t_annotationSet("./MNE-sample-data/subjects/sample/label/lh.aparc.a2009s.annot", "./MNE-sample-data/subjects/sample/label/rh.aparc.a2009s.annot");
//    SurfaceSet t_surfSet("./MNE-sample-data/subjects/sample/surf/lh.white", "./MNE-sample-data/subjects/sample/surf/rh.white");

    QFile t_fileFwd("E:/Data/sl_data/MEG/mind006/mind006_051209_auditory01_raw-oct-6p-fwd.fif");
    QFile t_fileCov("E:/Data/sl_data/MEG/mind006/mind006_051209_auditory01_raw-cov.fif");
    QFile t_fileRaw("E:/Data/sl_data/MEG/mind006/mind006_051209_auditory01_raw.fif");
    QString t_sEventName = "E:/Data/sl_data/MEG/mind006/mind006_051209_auditory01_raw-eve.fif";
    AnnotationSet t_annotationSet("E:/Data/sl_data/subjects/mind006/label/lh.aparc.a2009s.annot", "E:/Data/sl_data/subjects/mind006/label/rh.aparc.a2009s.annot");
    SurfaceSet t_surfSet("E:/Data/sl_data/subjects/mind006/surf/lh.white", "E:/Data/sl_data/subjects/mind006/surf/rh.white");


    qint32 event = 1;

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

    bool keep_comp = false;
    fiff_int_t dest_comp = 0;
    bool 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
//    qint32 numAverages = 99;
//    VectorXi vecSel(numAverages);
//    srand (time(NULL)); // initialize random seed

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

//    //Option 2
//    VectorXi vecSel(20);

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

//    vecSel << 65, 22, 47, 55, 16, 29, 14, 36, 57, 97, 89, 46, 9, 93, 83, 52, 71, 52, 3, 96;

    //Option 3 Newest
    VectorXi vecSel(10);

    vecSel << 0, 96, 80, 55, 66, 25, 26, 2, 55, 58, 6, 88;


    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

    double snr = 1.0f;//0.1f;//1.0f;//3.0f;//0.1f;//3.0f;
    QString method("dSPM"); //"MNE" | "dSPM" | "sLORETA"

    QString t_sFileNameClusteredInv("");
    QString t_sFileNameStc("mind006_051209_auditory01.stc");

    // Parse command line parameters
    for(qint32 i = 0; i < argc; ++i)
    {
        if(strcmp(argv[i], "-snr") == 0 || strcmp(argv[i], "--snr") == 0)
        {
            if(i + 1 < argc)
                snr = atof(argv[i+1]);
        }
        else if(strcmp(argv[i], "-method") == 0 || strcmp(argv[i], "--method") == 0)
        {
            if(i + 1 < argc)
                method = QString::fromUtf8(argv[i+1]);
        }
        else if(strcmp(argv[i], "-inv") == 0 || strcmp(argv[i], "--inv") == 0)
        {
            if(i + 1 < argc)
                t_sFileNameClusteredInv = QString::fromUtf8(argv[i+1]);
        }
        else if(strcmp(argv[i], "-stc") == 0 || strcmp(argv[i], "--stc") == 0)
        {
            if(i + 1 < argc)
                t_sFileNameStc = QString::fromUtf8(argv[i+1]);
        }
    }

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

//    // Load data
//    fiff_int_t setno = 1;
//    QPair<QVariant, QVariant> baseline(QVariant(), 0);
//    FiffEvoked evoked(t_fileEvoked, setno, baseline);
//    if(evoked.isEmpty())
//        return 1;

    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;
    //
    MNEForwardSolution t_clusteredFwd = t_Fwd.cluster_forward_solution_ccr(t_annotationSet, 20);//40);

    //
    // 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
    MNESourceEstimate sourceEstimate;
    QList<qint64> qVecElapsedTime;
    for(qint32 i = 0; i < 20; ++i)
    {
        //Benchmark time
        QElapsedTimer timer;
        timer.start();
        sourceEstimate = minimumNorm.calculateInverse(evoked);
        qVecElapsedTime.append(timer.elapsed());
    }

    double meanTime = 0.0;
    for(qint32 i = 0; i < qVecElapsedTime.size(); ++i)
        meanTime += qVecElapsedTime[i];

    meanTime /= qVecElapsedTime.size();
    qDebug() << "MNE calculation took" << meanTime << "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);

    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);

    InverseView view(minimumNorm.getSourceSpace(), t_qListLabels, t_qListRGBAs, 24, true, false, true);

    if (view.stereoType() != QGLView::RedCyanAnaglyph)
        view.camera()->setEyeSeparation(0.3f);
    QStringList args = QCoreApplication::arguments();
    int w_pos = args.indexOf("-width");
    int h_pos = args.indexOf("-height");
    if (w_pos >= 0 && h_pos >= 0)
    {
        bool ok = true;
        int w = args.at(w_pos + 1).toInt(&ok);
        if (!ok)
        {
            qWarning() << "Could not parse width argument:" << args;
            return 1;
        }
        int h = args.at(h_pos + 1).toInt(&ok);
        if (!ok)
        {
            qWarning() << "Could not parse height argument:" << args;
            return 1;
        }
        view.resize(w, h);
    }
    else
    {
        view.resize(800, 600);
    }
    view.show();

    //Push Estimate
    view.pushSourceEstimate(sourceEstimate);

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

//*/
    return a.exec();//1;//a.exec();
}