MuonAnalysisResultTableTab.cpp 16.9 KB
Newer Older
1
2
3
4
5
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidQtCustomInterfaces/MuonAnalysisResultTableTab.h"
#include "MantidKernel/ConfigService.h"
6
#include "MantidKernel/TimeSeriesProperty.h"
7
8
9
10
11
12
13
14
15
16
17

#include "MantidQtAPI/UserSubWindow.h"

#include <boost/shared_ptr.hpp>

#include <QLineEdit>
#include <QFileDialog>
#include <QHash>
#include <QMessageBox>
#include <QDesktopServices>

18
19
#include <algorithm>

20
21
22
23
24
25
26
27
28
29
30
31
32
//-----------------------------------------------------------------------------


namespace MantidQt
{
namespace CustomInterfaces
{
namespace Muon
{
  using namespace MantidQt::API;
  using namespace Mantid::Kernel;
  using namespace MantidQt::MantidWidgets;

33

34
35
36
/**
* Init the layout.
*/
37
38
void MuonAnalysisResultTableTab::initLayout()
{
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  // Connect the help button to the wiki page.
  connect(m_uiForm.muonAnalysisHelpResults, SIGNAL(clicked()), this, SLOT(helpResultsClicked()));
  
  // add check boxes for the include columns on log table and fitting table.
  for (int i = 0; i < m_uiForm.valueTable->rowCount(); i++)
  {
    m_uiForm.valueTable->setCellWidget(i,3, new QCheckBox);
  }
  for (int i = 0; i < m_uiForm.fittingResultsTable->rowCount(); i++)
  {
    m_uiForm.fittingResultsTable->setCellWidget(i,1, new QCheckBox);
  }

  //Set the default name
  m_uiForm.tableName->setText("ResultsTable");

  // Connect the select/deselect all buttons.
  connect(m_uiForm.selectAllLogValues, SIGNAL(clicked()), this, SLOT(selectAllLogs()));
  connect(m_uiForm.selectAllFittingResults, SIGNAL(clicked()), this, SLOT(selectAllFittings()));

  // Connect the create table button
  connect(m_uiForm.createTableBtn, SIGNAL(clicked()), this, SLOT(createTable()));
61
62
63
}


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/**
* Muon Analysis Results Table Help (slot)
*/
void MuonAnalysisResultTableTab::helpResultsClicked()
{
  QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") +
            "MuonAnalysisResultsTable"));
}


/**
* Select/Deselect all log values to be included in the table
*/
void MuonAnalysisResultTableTab::selectAllLogs()
{
  if (m_uiForm.selectAllLogValues->isChecked())
  {
    for (int i = 0; i < m_uiForm.valueTable->rowCount(); i++)
    {
      QTableWidgetItem* temp = static_cast<QTableWidgetItem*>(m_uiForm.valueTable->item(i,0));
      // If there is an item there then check the box
      if (temp != NULL)
      {
        QCheckBox* includeCell = static_cast<QCheckBox*>(m_uiForm.valueTable->cellWidget(i,3));
        includeCell->setChecked(true);
      }
    }
  }
  else
  {
    for (int i = 0; i < m_uiForm.valueTable->rowCount(); i++)
    {
      QCheckBox* includeCell = static_cast<QCheckBox*>(m_uiForm.valueTable->cellWidget(i,3));
      includeCell->setChecked(false);
    }
  }
}


/**
* Select/Deselect all fitting results to be included in the table
*/
void MuonAnalysisResultTableTab::selectAllFittings()
{
  if (m_uiForm.selectAllFittingResults->isChecked())
  {
    for (int i = 0; i < m_uiForm.fittingResultsTable->rowCount(); i++)
    {
      QTableWidgetItem* temp = static_cast<QTableWidgetItem*>(m_uiForm.fittingResultsTable->item(i,0));
      // If there is an item there then check the box
      if (temp != NULL)
      {
        QCheckBox* includeCell = static_cast<QCheckBox*>(m_uiForm.fittingResultsTable->cellWidget(i,1));
        includeCell->setChecked(true);
      }
    }
  }
  else
  {
    for (int i = 0; i < m_uiForm.fittingResultsTable->rowCount(); i++)
    {
      QCheckBox* includeCell = static_cast<QCheckBox*>(m_uiForm.fittingResultsTable->cellWidget(i,1));
      includeCell->setChecked(false);
    }
  }
}

131

132
133
134
135
136
/**
* Populates the tables with all the correct log values and fitting results. It takes the
* given workspace list and checks to see if a fit has been done to the data set and if so
* adds it to a new workspace list.
*
137
* @param wsList :: A list containing all the data set workspaces that have been loaded
138
139
140
141
*                   by muon analysis.
*/
void MuonAnalysisResultTableTab::populateTables(const QStringList& wsList)
{
142
143
144
  // Clear the previous table values
  m_tableValues.clear();
  QVector<QString> fittedWsList;
145
  // Get all the workspaces from the fitPropertyBrowser and find out whether they have had fitting done to them.
146
  for (int i(0); i<wsList.size(); ++i)
147
  {
148
    if((Mantid::API::AnalysisDataService::Instance().doesExist(wsList[i].toStdString() + "_parameters"))&&(Mantid::API::AnalysisDataService::Instance().doesExist(wsList[i].toStdString()))) 
149
      fittedWsList.append(wsList[i]);
150
  }
151
152
153
     
  // Make sure all params match.
  QVector<QString> sameFittedWsList(getWorkspacesWithSameParams(fittedWsList));
154

155
156
157
  // Populate the individual log values and fittings into their respective tables.
  populateFittings(sameFittedWsList);
  populateLogsAndValues(sameFittedWsList);
158
159
}

160

161
162
163
/**
* Populates the items (log values) into their table.
*
164
* @param fittedWsList :: a workspace list containing ONLY the workspaces that have parameter
165
166
*                   tables associated with it.
*/
167
void MuonAnalysisResultTableTab::populateLogsAndValues(const QVector<QString>& fittedWsList)
168
{
169
  // Clear the logs if not empty and then repopulate.
170
  QVector<QString> logsToDisplay;
171
  
172
173
  for (int i=0; i<fittedWsList.size(); i++)
  { 
174
    QMap<QString, double> allLogs;
175

176
    // Get log information
177
    Mantid::API::ExperimentInfo_sptr ws = boost::dynamic_pointer_cast<Mantid::API::ExperimentInfo>(Mantid::API::AnalysisDataService::Instance().retrieve(fittedWsList[i].toStdString()));
178
179
180
181
    if (!ws)
    {
      throw std::runtime_error("Wrong type of Workspace");
    }
182

183
184
185
186
    const std::vector< Mantid::Kernel::Property * > & logData = ws->run().getLogData();
    std::vector< Mantid::Kernel::Property * >::const_iterator pEnd = logData.end();
    for( std::vector< Mantid::Kernel::Property * >::const_iterator pItr = logData.begin();
          pItr != pEnd; ++pItr )
187
    {  
188
189
190
      QString logFile(QFileInfo((**pItr).name().c_str()).fileName());
      // Just get the num.series log values
      Mantid::Kernel::TimeSeriesProperty<double> *tspd = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double> *>(*pItr);
191

192
      if( tspd )//If it is then it must be num.series
193
      {
194
        allLogs[logFile] = tspd->nthValue(0);
195
        if (i == 0)
196
          logsToDisplay.push_back(logFile);
197
198
199
        else
        {
          bool reg(true);
200
          for(int j=0; j<logsToDisplay.size(); ++j)
201
202
          {
            //if log file already registered then don't register it again.
203
            if (logsToDisplay[j] == logFile)
204
205
206
207
208
209
            {
              reg = false;
              break;
            }
          }
          if (reg==true)
210
          logsToDisplay.push_back(logFile);
211
        }
212
213
214
      }
    }

215
    // Add all data collected from one workspace to another map. Will be used when creating table.
216
    m_tableValues[fittedWsList[i]] = allLogs;
217
218
219

  } // End loop over all workspace's log information and param information

220
  // Remove the logs that don't appear in all workspaces
221
  QVector<int> toRemove;
222
  for(int i=0; i<logsToDisplay.size(); ++i)
223
224
225
226
  {
    QMap<QString,QMap<QString, double> >::Iterator itr; 
    for (itr = m_tableValues.begin(); itr != m_tableValues.end(); itr++)
    { 
227
      QMap<QString, double> logsAndValues = itr.value();
228

229
      if (!(logsAndValues.contains(logsToDisplay[i])))
230
231
232
233
234
235
236
237
238
      {      
        toRemove.push_back(i);
        break;
      }
    }      
  }

  for(int i=0; i<toRemove.size(); ++i)
  {
239
    logsToDisplay.remove(toRemove[i]-i);
240
241
  }

242
243
  // If there isn't enough rows in the table to populate all logs then display error message
  if(logsToDisplay.size() > m_uiForm.valueTable->rowCount())
244
245
246
247
248
249
250
251
  {
    QMessageBox::information(this, "Mantid - Muon Analysis", "There is not enough room in the table to populate all fitting parameter results");
  }
  else
  {
    // Populate table with all log values available without repeating any.
    for (int row = 0; row < m_uiForm.valueTable->rowCount(); row++)
    {
252
253
      if (row < logsToDisplay.size())
        m_uiForm.valueTable->setItem(row,0, new QTableWidgetItem(logsToDisplay[row]));
254
255
256
257
      else
        m_uiForm.valueTable->setItem(row,0, NULL);
    }
  }
258

259
260
  // Save the number of logs displayed so don't have to search through all cells.
  m_numLogsdisplayed = logsToDisplay.size();
261
262
263
264
265
266
}


/**
* Populates the items (fitted workspaces) into their table.
*
267
268
* @param fittedWsList :: a workspace list containing ONLY the workspaces that have parameter
*                        tables associated with it.
269
*/
270
void MuonAnalysisResultTableTab::populateFittings(const QVector<QString>& fittedWsList)
271
{
272
  if(fittedWsList.size() > m_uiForm.fittingResultsTable->rowCount())
273
274
275
276
277
  {
    QMessageBox::information(this, "Mantid - Muon Analysis", "There is not enough room in the table to populate all fitting parameter results");
  }
  else
  {
278
    for (int row = 0; row < m_uiForm.fittingResultsTable->rowCount(); row++)
279
    {
280
      // Fill values and delete previous old ones.
281
282
      if (row < fittedWsList.size())
        m_uiForm.fittingResultsTable->setItem(row,0, new QTableWidgetItem(fittedWsList[row]));
283
284
      else
        m_uiForm.fittingResultsTable->setItem(row,0, NULL);
285
286
287
288
    }
  }
}

289

290
291
292
293
/**
* Creates the table using the information selected by the user in the tables
*/
void MuonAnalysisResultTableTab::createTable()
294
{  
295
296
297
298
299
300
  if (m_tableValues.size() == 0)
  {
    QMessageBox::information(this, "Mantid - Muon Analysis", "No workspace found with suitable fitting.");
    return;
  }

301
302
303
  // Get the user selection
  QVector<QString> wsSelected = getSelectedWs();
  QVector<QString> logsSelected = getSelectedLogs();
304

305
  if ((wsSelected.size() == 0) || logsSelected.size() == 0)
306
  {
307
308
    QMessageBox::information(this, "Mantid - Muon Analysis", "Please select options from both tables.");
    return;
309
310
  }

311
312
313
314
  // Create the results table
  Mantid::API::ITableWorkspace_sptr table = Mantid::API::WorkspaceFactory::Instance().createTable("TableWorkspace");
  table->addColumn("str","Run Name");
  for(int i=0; i<logsSelected.size(); ++i)
315
  {
316
    table->addColumn("double", logsSelected[i].toStdString());
317
318
  }

319
320
321
322
  // Get param information
  QMap<QString, QMap<QString, double> > wsParamsList;
  QVector<QString> paramsToDisplay;
  for(int i=0; i<wsSelected.size(); ++i)
323
  {
324
325
    QMap<QString, double> paramsList;
    Mantid::API::ITableWorkspace_sptr paramWs = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsSelected[i].toStdString() + "_parameters") );
326

327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
    Mantid::API::TableRow paramRow = paramWs->getFirstRow();
    
    // Loop over all rows and get values and errors.
    do
    {  
      std::string key;
      double value;
      double error;
      paramRow >> key >> value >> error;
      if (i == 0)
      {
        table->addColumn("double", key);
        table->addColumn("double", key + "Error");
        paramsToDisplay.append(QString::fromStdString(key));
        paramsToDisplay.append(QString::fromStdString(key) + "Error");
      }
      paramsList[QString::fromStdString(key)] = value;
      paramsList[QString::fromStdString(key) + "Error"] = error;
    }
    while(paramRow.next());
347

348
    wsParamsList[wsSelected[i]] = paramsList;
349
  }
350

351
352
353
354
355
356
357
  // Add data to table
  QMap<QString,QMap<QString, double> >::Iterator itr; 
  for (itr = m_tableValues.begin(); itr != m_tableValues.end(); itr++)
  { 
    for(int i=0; i<wsSelected.size(); ++i)
    {
      if (wsSelected[i] == itr.key())
358
      {
359
        //Add new row and add run name
360
        Mantid::API::TableRow row = table->appendRow();
361
362
363
364
365
366
367
368
369
        QString runName(itr.key().left(itr.key().find(';')));
        row << runName.toStdString();

        // Add log values
        QMap<QString, double> logsAndValues = itr.value();
        for(int j=0; j<logsSelected.size(); ++j)
        {
          row << logsAndValues.find(logsSelected[j]).value();
        }
370

371
372
373
        // Add param values (presume params the same for all workspaces)
        QMap<QString, double> paramsList = wsParamsList.find(itr.key()).value();
        for(int j=0; j<paramsToDisplay.size(); ++j)
374
        {
375
          row << paramsList.find(paramsToDisplay[j]).value();
376
        }
377
378
379
      }
    }  
  }
380

381
382
  // Save the table to the ADS
  Mantid::API::AnalysisDataService::Instance().addOrReplace(getFileName(),table);
383
384
}

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426

/**
* Get the user selected workspaces with _parameters files associated with it
*
* @return wsSelected :: A vector of QString's containing the workspace that are selected.
*/
QVector<QString> MuonAnalysisResultTableTab::getSelectedWs()
{
  QVector<QString> wsSelected;
  for (int i = 0; i < m_tableValues.size(); i++)
  {
    QCheckBox* includeCell = static_cast<QCheckBox*>(m_uiForm.fittingResultsTable->cellWidget(i,1));
    if (includeCell->isChecked())
    {
      QTableWidgetItem* wsName = static_cast<QTableWidgetItem*>(m_uiForm.fittingResultsTable->item(i,0));
      wsSelected.push_back(wsName->text());
    }
  }
  return wsSelected;
}


/**
* Get the user selected log file
*
* @return logsSelected :: A vector of QString's containing the logs that are selected.
*/
QVector<QString> MuonAnalysisResultTableTab::getSelectedLogs()
{
  QVector<QString> logsSelected;
  for (int i = 0; i < m_numLogsdisplayed; i++)
  {
    QCheckBox* includeCell = static_cast<QCheckBox*>(m_uiForm.valueTable->cellWidget(i,3));
    if (includeCell->isChecked())
    {
      QTableWidgetItem* logParam = static_cast<QTableWidgetItem*>(m_uiForm.valueTable->item(i,0));
      logsSelected.push_back(logParam->text());
    }
  }
  return logsSelected;
}

427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499

/**
* Looks through all the parameter tables and trys to match the parameters within them.
* If one or more workspaces were fitted using different parameters then a suitable
* error message will be displayed.
*
* QVector<QString> fittedWsList :: List of workspaces with parameter tables.
* @return sameFittedWsList :: A list of workspaces that all share a parameter table
*                             with the same parameters fitted.
*/
QVector<QString> MuonAnalysisResultTableTab::getWorkspacesWithSameParams(const QVector<QString>& fittedWsList)
{
  QVector<QString> sameFittedWsList;
  // Check all parameters are the same.
  if (fittedWsList.size() > 0)
  {
    bool differentParams(false);
    std::vector<std::string> firstParams;

    // Find the first parameter table and use this as a comparison for all the other tables.
    Mantid::API::ITableWorkspace_sptr paramWs = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(fittedWsList[0].toStdString() + "_parameters") );

    Mantid::API::TableRow paramRow = paramWs->getFirstRow();
    do
    {  
      std::string key;
      paramRow >> key;
      firstParams.push_back(key);
    }
    while(paramRow.next());

    sameFittedWsList.push_back(fittedWsList[0]);

    // Compare to all the other parameters.
    for (int i=1; i<fittedWsList.size(); ++i)
    {
      std::vector<std::string> nextParams;
      Mantid::API::ITableWorkspace_sptr paramWs = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(fittedWsList[i].toStdString() + "_parameters") );

      Mantid::API::TableRow paramRow = paramWs->getFirstRow();
      do
      {  
        std::string key;
        paramRow >> key;
        nextParams.push_back(key);
      }
      while(paramRow.next());

      if (firstParams == nextParams)
      {
        // If they are the same parameter then add to the vector which will be populated in the tables.
        sameFittedWsList.push_back(fittedWsList[i]);
      }
      else
      {
        differentParams = true;
      }
    }

    if(differentParams) // Params were found to be different from the ones in the first table, therefore output warning message.
    {
      QMessageBox::information(this, "Mantid - Muon Analysis", "The parameters didn't match for each workspace. Default to display\n"
        "all the parameters that match the first workspace " + fittedWsList[0]);
    } 
  }
  else // if there is only one fitted workspace then no need to for check to see if they are the same.
  {
    sameFittedWsList = fittedWsList;
  }

  return sameFittedWsList;
}

500
501
502
503
504
505
506
507
508
509
510
511
512

/**
* Checks that the file name isn't been used, displays the appropriate message and
* then returns the name in which to save.
*
* @return name :: The name the results table should be created with.
*/
std::string MuonAnalysisResultTableTab::getFileName()
{
  std::string fileName(m_uiForm.tableName->text());
  
  if (Mantid::API::AnalysisDataService::Instance().doesExist(fileName))
  {
513
514
515
516
    int choice = QMessageBox::question(this, tr("MantidPlot - Overwrite Warning"), QString::fromStdString(fileName) +
          tr("already exists. Do you want to replace it?"),
          QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape);
    if (choice == QMessageBox::No)
517
    {
518
519
520
521
522
523
524
      int versionNum(2); 
      fileName += " #";
      while(Mantid::API::AnalysisDataService::Instance().doesExist(fileName + boost::lexical_cast<std::string>(versionNum)))
      {
        versionNum += 1;
      }
      return (fileName + boost::lexical_cast<std::string>(versionNum));
525
526
    }
  }
527
  return fileName;
528
}
529
530
531
532
533


}
}
}