Skip to content
Snippets Groups Projects
ReflTableViewPresenter.cpp 47.6 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 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 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 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 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 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
#include "MantidQtCustomInterfaces/Reflectometry/ReflTableViewPresenter.h"
#include "MantidAPI/AlgorithmManager.h"
#include "MantidAPI/CatalogManager.h"
#include "MantidAPI/ITableWorkspace.h"
#include "MantidAPI/MatrixWorkspace.h"
#include "MantidAPI/NotebookWriter.h"
#include "MantidAPI/TableRow.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidGeometry/Instrument.h"
#include "MantidGeometry/Instrument/ParameterMap.h"
#include "MantidKernel/CatalogInfo.h"
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/FacilityInfo.h"
#include "MantidKernel/ProgressBase.h"
#include "MantidKernel/Strings.h"
#include "MantidKernel/TimeSeriesProperty.h"
#include "MantidKernel/UserCatalogInfo.h"
#include "MantidKernel/Utils.h"
#include "MantidQtCustomInterfaces/ParseKeyValueString.h"
#include "MantidQtCustomInterfaces/ProgressableView.h"
#include "MantidQtCustomInterfaces/Reflectometry/QReflTableModel.h"
#include "MantidQtCustomInterfaces/Reflectometry/QtReflOptionsDialog.h"
#include "MantidQtCustomInterfaces/Reflectometry/ReflCatalogSearcher.h"
#include "MantidQtCustomInterfaces/Reflectometry/ReflGenerateNotebook.h"
#include "MantidQtCustomInterfaces/Reflectometry/ReflLegacyTransferStrategy.h"
#include "MantidQtCustomInterfaces/Reflectometry/ReflMeasureTransferStrategy.h"
#include "MantidQtCustomInterfaces/Reflectometry/ReflNexusMeasurementItemSource.h"
#include "MantidQtCustomInterfaces/Reflectometry/ReflSearchModel.h"
#include "MantidQtCustomInterfaces/Reflectometry/ReflTableView.h"
#include "MantidQtMantidWidgets/AlgorithmHintStrategy.h"

#include <boost/regex.hpp>
#include <boost/tokenizer.hpp>
#include <fstream>
#include <sstream>

using namespace Mantid::API;
using namespace Mantid::Geometry;
using namespace Mantid::Kernel;
using namespace MantidQt::MantidWidgets;

namespace {

class ReflProgress : public Mantid::Kernel::ProgressBase {
private:
  MantidQt::CustomInterfaces::ProgressableView *const m_progressableView;

public:
  ReflProgress(
      double start, double end, int64_t nSteps,
      MantidQt::CustomInterfaces::ProgressableView *const progressableView)
      : ProgressBase(static_cast<int>(start), static_cast<int>(end),
                     static_cast<int>(nSteps)),
        m_progressableView(progressableView) {
    if (!progressableView) {
      throw std::runtime_error("ProgressableView is null");
    }
    m_progressableView->clearProgress();
    m_progressableView->setProgressRange(static_cast<int>(start),
                                         static_cast<int>(end));
  }

  void doReport(const std::string &) {
    m_progressableView->setProgress(static_cast<int>(m_i));
  }
  void clear() { m_progressableView->clearProgress(); }
  ~ReflProgress() {}
};

void validateModel(ITableWorkspace_sptr model) {
  if (!model)
    throw std::runtime_error("Null pointer");

  if (model->columnCount() != 9)
    throw std::runtime_error("Selected table has the incorrect number of "
                             "columns (9) to be used as a reflectometry "
                             "table.");

  try {
    model->String(0, 0);
    model->String(0, 1);
    model->String(0, 2);
    model->String(0, 3);
    model->String(0, 4);
    model->String(0, 5);
    model->Double(0, 6);
    model->Int(0, 7);
    model->String(0, 8);
  } catch (const std::runtime_error &) {
    throw std::runtime_error("Selected table does not meet the specifications "
                             "to become a model for this interface.");
  }
}

bool isValidModel(Workspace_sptr model) {
  try {
    validateModel(boost::dynamic_pointer_cast<ITableWorkspace>(model));
  } catch (...) {
    return false;
  }
  return true;
}

ITableWorkspace_sptr createWorkspace() {
  ITableWorkspace_sptr ws = WorkspaceFactory::Instance().createTable();
  auto colRuns = ws->addColumn("str", "Run(s)");
  auto colTheta = ws->addColumn("str", "ThetaIn");
  auto colTrans = ws->addColumn("str", "TransRun(s)");
  auto colQmin = ws->addColumn("str", "Qmin");
  auto colQmax = ws->addColumn("str", "Qmax");
  auto colDqq = ws->addColumn("str", "dq/q");
  auto colScale = ws->addColumn("double", "Scale");
  auto colStitch = ws->addColumn("int", "StitchGroup");
  auto colOptions = ws->addColumn("str", "Options");

  colRuns->setPlotType(0);
  colTheta->setPlotType(0);
  colTrans->setPlotType(0);
  colQmin->setPlotType(0);
  colQmax->setPlotType(0);
  colDqq->setPlotType(0);
  colScale->setPlotType(0);
  colStitch->setPlotType(0);
  colOptions->setPlotType(0);

  return ws;
}

ITableWorkspace_sptr createDefaultWorkspace() {
  // Create a blank workspace with one line and set the scale column to 1
  auto ws = createWorkspace();
  ws->appendRow();
  ws->Double(0, MantidQt::CustomInterfaces::ReflTableSchema::COL_SCALE) = 1.0;
  return ws;
}
}

namespace MantidQt {
namespace CustomInterfaces {
ReflTableViewPresenter::ReflTableViewPresenter(ReflTableView *tableView,
                                               ProgressableView *progressView)
    : WorkspaceObserver(), m_tableView(tableView), m_progressView(progressView),
      m_tableDirty(false) {

  // TODO. Select strategy.
  /*
  std::unique_ptr<CatalogConfigService> catConfigService(
  makeCatalogConfigServiceAdapter(ConfigService::Instance()));
  UserCatalogInfo catalogInfo(
  ConfigService::Instance().getFacility().catalogInfo(), *catConfigService);
  */

  // Initialise options
  initOptions();

  // Set up the instrument selectors
  std::vector<std::string> instruments;
  instruments.emplace_back("INTER");
  instruments.emplace_back("SURF");
  instruments.emplace_back("CRISP");
  instruments.emplace_back("POLREF");
  instruments.emplace_back("OFFSPEC");

  // If the user's configured default instrument is in this list, set it as the
  // default, otherwise use INTER
  const std::string defaultInst =
      Mantid::Kernel::ConfigService::Instance().getString("default.instrument");
  if (std::find(instruments.begin(), instruments.end(), defaultInst) !=
      instruments.end())
    m_tableView->setInstrumentList(instruments, defaultInst);
  else
    m_tableView->setInstrumentList(instruments, "INTER");

  // Populate an initial list of valid tables to open, and subscribe to the ADS
  // to keep it up to date
  Mantid::API::AnalysisDataServiceImpl &ads =
      Mantid::API::AnalysisDataService::Instance();

  auto items = ads.getObjectNames();
  for (auto const &name : items) {
    Workspace_sptr ws = ads.retrieve(name);

    if (isValidModel(ws))
      m_workspaceList.insert(name);
  }
  observeAdd();
  observePostDelete();
  observeRename();
  observeADSClear();
  observeAfterReplace();
  m_tableView->setTableList(m_workspaceList);

  // Provide autocompletion hints for the options column. We use the algorithm's
  // properties minus
  // those we blacklist. We blacklist any useless properties or ones we're
  // handling that the user
  // should'nt touch.
  IAlgorithm_sptr alg =
      AlgorithmManager::Instance().create("ReflectometryReductionOneAuto");
  std::set<std::string> blacklist{"ThetaIn",
                                  "ThetaOut",
                                  "InputWorkspace",
                                  "OutputWorkspace",
                                  "OutputWorkspaceWavelength",
                                  "FirstTransmissionRun",
                                  "SecondTransmissionRun"};
  m_tableView->setOptionsHintStrategy(
      new AlgorithmHintStrategy(alg, blacklist));

  // Start with a blank table
  newTable();
}

ReflTableViewPresenter::~ReflTableViewPresenter() {}

/**
* Finds the first unused group id
*/
int ReflTableViewPresenter::getUnusedGroup(std::set<int> ignoredRows) const {
  std::set<int> usedGroups;

  // Scan through all the rows, working out which group ids are used
  for (int idx = 0; idx < m_model->rowCount(); ++idx) {
    if (ignoredRows.find(idx) != ignoredRows.end())
      continue;

    // This is an unselected row. Add it to the list of used group ids
    usedGroups.insert(
        m_model->data(m_model->index(idx, ReflTableSchema::COL_GROUP)).toInt());
  }

  int groupId = 0;

  // While the group id is one of the used ones, increment it by 1
  while (usedGroups.find(groupId) != usedGroups.end())
    groupId++;

  return groupId;
}

/**
Process selected rows
*/
void ReflTableViewPresenter::process() {
  if (m_model->rowCount() == 0) {
    m_tableView->giveUserWarning("Cannot process an empty Table", "Warning");
    return;
  }

  std::set<int> rows = m_tableView->getSelectedRows();
  if (rows.empty()) {
    if (m_options["WarnProcessAll"].toBool()) {
      // Does the user want to abort?
      if (!m_tableView->askUserYesNo(
              "This will process all rows in the table. Continue?",
              "Process all rows?"))
        return;
    }

    // They want to process all rows, so populate rows with every index in the
    // model
    for (int idx = 0; idx < m_model->rowCount(); ++idx)
      rows.insert(idx);
  }

  // Map group numbers to the set of rows in that group we want to process
  std::map<int, std::set<int>> groups;
  for (auto it = rows.begin(); it != rows.end(); ++it)
    groups[m_model->data(m_model->index(*it, ReflTableSchema::COL_GROUP))
               .toInt()]
        .insert(*it);

  // Check each group and warn if we're only partially processing it
  for (auto gIt = groups.begin(); gIt != groups.end(); ++gIt) {
    const int &groupId = gIt->first;
    const std::set<int> &groupRows = gIt->second;
    // Are we only partially processing a group?
    if (groupRows.size() < numRowsInGroup(gIt->first) &&
        m_options["WarnProcessPartialGroup"].toBool()) {
      std::stringstream err;
      err << "You have only selected " << groupRows.size() << " of the ";
      err << numRowsInGroup(groupId) << " rows in group " << groupId << ".";
      err << " Are you sure you want to continue?";
      if (!m_tableView->askUserYesNo(err.str(), "Continue Processing?"))
        return;
    }
  }

  if (!rowsValid(rows)) {
    return;
  }

  if (!processGroups(groups, rows)) {
    return;
  }

  // If "Output Notebook" checkbox is checked then create an ipython notebook
  if (m_tableView->getEnableNotebook()) {
    saveNotebook(groups, rows);
  }
}

/**
Display a dialog to choose save location for notebook, then save the notebook
there
@param groups : groups of rows to stitch
@param rows : rows selected for processing
*/
void ReflTableViewPresenter::saveNotebook(std::map<int, std::set<int>> groups,
                                          std::set<int> rows) {

  std::string filename = m_tableView->requestNotebookPath();
  if (filename == "") {
    return;
  }

  auto notebook = Mantid::Kernel::make_unique<ReflGenerateNotebook>(
      m_wsName, m_model, m_tableView->getProcessInstrument(),
      ReflTableSchema::COL_RUNS, ReflTableSchema::COL_TRANSMISSION,
      ReflTableSchema::COL_OPTIONS, ReflTableSchema::COL_ANGLE,
      ReflTableSchema::COL_QMIN, ReflTableSchema::COL_QMAX,
      ReflTableSchema::COL_DQQ, ReflTableSchema::COL_SCALE,
      ReflTableSchema::COL_GROUP);
  std::string generatedNotebook = notebook->generateNotebook(groups, rows);

  std::ofstream file(filename.c_str(), std::ofstream::trunc);
  file << generatedNotebook;
  file.flush();
  file.close();
}

/**
Process stitch groups
@param rows : rows in the model
@param groups : groups of rows to stitch
@returns true if successful, otherwise false
*/
bool ReflTableViewPresenter::processGroups(std::map<int, std::set<int>> groups,
                                           std::set<int> rows) {
  int progress = 0;
  // Each group and each row within count as a progress step.
  const int maxProgress = (int)(rows.size() + groups.size());
  ReflProgress progressReporter(progress, maxProgress, maxProgress,
                                m_progressView);

  for (auto gIt = groups.begin(); gIt != groups.end(); ++gIt) {
    const std::set<int> groupRows = gIt->second;

    // Reduce each row
    for (auto rIt = groupRows.begin(); rIt != groupRows.end(); ++rIt) {
      try {
        reduceRow(*rIt);
        progressReporter.report();
      } catch (std::exception &ex) {
        const std::string rowNo =
            Mantid::Kernel::Strings::toString<int>(*rIt + 1);
        const std::string message =
            "Error encountered while processing row " + rowNo + ":\n";
        m_view->giveUserCritical(message + ex.what(), "Error");
        progressReporter.clear();
        return false;
      }
    }

    try {
      stitchRows(groupRows);
      progressReporter.report();
    } catch (std::exception &ex) {
      const std::string groupNo =
          Mantid::Kernel::Strings::toString<int>(gIt->first);
      const std::string message =
          "Error encountered while stitching group " + groupNo + ":\n";
      m_view->giveUserCritical(message + ex.what(), "Error");
      progressReporter.clear();
      return false;
    }
  }
  return true;
}

/**
Validate rows.
@param rows : Rows in the model to validate
@returns true if all rows are valid and false otherwise
*/
bool ReflTableViewPresenter::rowsValid(std::set<int> rows) {
  for (auto it = rows.begin(); it != rows.end(); ++it) {
    try {
      validateRow(*it);
      autofillRow(*it);
    } catch (std::exception &ex) {
      // Allow two theta to be blank
      if (ex.what() ==
          std::string("Value for two theta could not be found in log."))
        continue;

      const std::string rowNo = Mantid::Kernel::Strings::toString<int>(*it + 1);
      m_view->giveUserCritical(
          "Error found in row " + rowNo + ":\n" + ex.what(), "Error");
      return false;
    }
  }
  return true;
}

/**
Validate a row.
If a row passes validation, it is ready to be autofilled, but
not necessarily ready for processing.
@param rowNo : The row in the model to validate
@throws std::invalid_argument if the row fails validation
*/
void ReflTableViewPresenter::validateRow(int rowNo) const {
  if (rowNo >= m_model->rowCount())
    throw std::invalid_argument("Invalid row");

  if (m_model->data(m_model->index(rowNo, ReflTableSchema::COL_RUNS))
          .toString()
          .isEmpty())
    throw std::invalid_argument("Run column may not be empty.");
}

/**
Autofill a row
@param rowNo : The row in the model to autofill
@throws std::runtime_error if the row could not be auto-filled
*/
void ReflTableViewPresenter::autofillRow(int rowNo) {
  if (rowNo >= m_model->rowCount())
    throw std::runtime_error("Invalid row");

  const std::string runStr =
      m_model->data(m_model->index(rowNo, ReflTableSchema::COL_RUNS))
          .toString()
          .toStdString();
  auto runWS = prepareRunWorkspace(runStr);
  auto runMWS = boost::dynamic_pointer_cast<MatrixWorkspace>(runWS);
  auto runWSG = boost::dynamic_pointer_cast<WorkspaceGroup>(runWS);

  // If we've got a workspace group, use the first workspace in it
  if (!runMWS && runWSG)
    runMWS = boost::dynamic_pointer_cast<MatrixWorkspace>(runWSG->getItem(0));

  if (!runMWS)
    throw std::runtime_error("Could not convert " + runWS->name() +
                             " to a MatrixWorkspace.");

  // Fetch two theta from the log if needed
  if (m_model->data(m_model->index(rowNo, ReflTableSchema::COL_ANGLE))
          .toString()
          .isEmpty()) {
    Property *logData = NULL;

    // First try TwoTheta
    try {
      logData = runMWS->mutableRun().getLogData("Theta");
    } catch (std::exception &) {
      throw std::runtime_error(
          "Value for two theta could not be found in log.");
    }

    auto logPWV = dynamic_cast<const PropertyWithValue<double> *>(logData);
    auto logTSP = dynamic_cast<const TimeSeriesProperty<double> *>(logData);

    double thetaVal;
    if (logPWV)
      thetaVal = *logPWV;
    else if (logTSP && logTSP->realSize() > 0)
      thetaVal = logTSP->lastValue();
    else
      throw std::runtime_error(
          "Value for two theta could not be found in log.");

    // Update the model
    if (m_options["RoundAngle"].toBool())
      thetaVal =
          Utils::roundToDP(thetaVal, m_options["RoundAnglePrecision"].toInt());

    m_model->setData(m_model->index(rowNo, ReflTableSchema::COL_ANGLE),
                     thetaVal);
    m_tableDirty = true;
  }

  // If we need to calculate the resolution, do.
  if (m_model->data(m_model->index(rowNo, ReflTableSchema::COL_DQQ))
          .toString()
          .isEmpty()) {
    IAlgorithm_sptr calcResAlg =
        AlgorithmManager::Instance().create("CalculateResolution");
    calcResAlg->setProperty("Workspace", runMWS);
    calcResAlg->setProperty(
        "TwoTheta",
        m_model->data(m_model->index(rowNo, ReflTableSchema::COL_ANGLE))
            .toString()
            .toStdString());
    calcResAlg->execute();

    if (!calcResAlg->isExecuted())
      throw std::runtime_error("CalculateResolution failed. Please manually "
                               "enter a value in the dQ/Q column.");

    // Update the model
    double dqqVal = calcResAlg->getProperty("Resolution");

    if (m_options["RoundDQQ"].toBool())
      dqqVal = Utils::roundToDP(dqqVal, m_options["RoundDQQPrecision"].toInt());

    m_model->setData(m_model->index(rowNo, ReflTableSchema::COL_DQQ), dqqVal);
    m_tableDirty = true;
  }
}

/**
Extracts the run number of a workspace
@param ws : The workspace to fetch the run number from
@returns The run number of the workspace
*/
std::string ReflTableViewPresenter::getRunNumber(const Workspace_sptr &ws) {
  // If we can, use the run number from the workspace's sample log
  MatrixWorkspace_sptr mws = boost::dynamic_pointer_cast<MatrixWorkspace>(ws);
  if (mws) {
    try {
      const Property *runProperty = mws->mutableRun().getLogData("run_number");
      auto runNumber =
          dynamic_cast<const PropertyWithValue<std::string> *>(runProperty);
      if (runNumber)
        return *runNumber;
    } catch (Mantid::Kernel::Exception::NotFoundError &) {
      // We'll just fall back to looking at the workspace's name
    }
  }

  // Okay, let's see what we can get from the workspace's name
  const std::string wsName = ws->name();

  // Matches TOF_13460 -> 13460
  boost::regex outputRegex("(TOF|IvsQ|IvsLam)_([0-9]+)");

  // Matches INTER13460 -> 13460
  boost::regex instrumentRegex("[a-zA-Z]{3,}([0-9]{3,})");

  boost::smatch matches;

  if (boost::regex_match(wsName, matches, outputRegex)) {
    return matches[2].str();
  } else if (boost::regex_match(wsName, matches, instrumentRegex)) {
    return matches[1].str();
  }

  // Resort to using the workspace name
  return wsName;
}

/**
Takes a user specified run, or list of runs, and returns a pointer to the
desired TOF workspace
@param runStr : The run or list of runs (separated by '+')
@throws std::runtime_error if the workspace could not be prepared
@returns a shared pointer to the workspace
*/
Workspace_sptr
ReflTableViewPresenter::prepareRunWorkspace(const std::string &runStr) {
  const std::string instrument = m_tableView->getProcessInstrument();

  std::vector<std::string> runs;
  boost::split(runs, runStr, boost::is_any_of("+"));

  if (runs.empty())
    throw std::runtime_error("No runs given");

  // Remove leading/trailing whitespace from each run
  for (auto runIt = runs.begin(); runIt != runs.end(); ++runIt)
    boost::trim(*runIt);

  // If we're only given one run, just return that
  if (runs.size() == 1)
    return loadRun(runs[0], instrument);

  const std::string outputName = "TOF_" + boost::algorithm::join(runs, "_");

  // Check if we've already prepared it
  if (AnalysisDataService::Instance().doesExist(outputName))
    return AnalysisDataService::Instance().retrieveWS<Workspace>(outputName);

  /* Ideally, this should be executed as a child algorithm to keep the ADS tidy,
  * but
  * that doesn't preserve history nicely, so we'll just take care of tidying up
  * in
  * the event of failure.
  */
  IAlgorithm_sptr algPlus = AlgorithmManager::Instance().create("Plus");
  algPlus->initialize();
  algPlus->setProperty("LHSWorkspace", loadRun(runs[0], instrument)->name());
  algPlus->setProperty("OutputWorkspace", outputName);

  // Drop the first run from the runs list
  runs.erase(runs.begin());

  try {
    // Iterate through all the remaining runs, adding them to the first run
    for (auto runIt = runs.begin(); runIt != runs.end(); ++runIt) {
      algPlus->setProperty("RHSWorkspace", loadRun(*runIt, instrument)->name());
      algPlus->execute();

      // After the first execution we replace the LHS with the previous output
      algPlus->setProperty("LHSWorkspace", outputName);
    }
  } catch (...) {
    // If we're unable to create the full workspace, discard the partial version
    AnalysisDataService::Instance().remove(outputName);

    // We've tidied up, now re-throw.
    throw;
  }

  return AnalysisDataService::Instance().retrieveWS<Workspace>(outputName);
}

/**
Loads a run from disk or fetches it from the AnalysisDataService
@param run : The name of the run
@param instrument : The instrument the run belongs to
@throws std::runtime_error if the run could not be loaded
@returns a shared pointer to the workspace
*/
Workspace_sptr
ReflTableViewPresenter::loadRun(const std::string &run,
                                const std::string &instrument = "") {
  // First, let's see if the run given is the name of a workspace in the ADS
  if (AnalysisDataService::Instance().doesExist(run))
    return AnalysisDataService::Instance().retrieveWS<Workspace>(run);

  // Is the run string is numeric
  if (boost::regex_match(run, boost::regex("\\d+"))) {
    std::string wsName;

    // Look for "TOF_<run_number>" in the ADS
    wsName = "TOF_" + run;
    if (AnalysisDataService::Instance().doesExist(wsName))
      return AnalysisDataService::Instance().retrieveWS<Workspace>(wsName);

    // Look for "<instrument><run_number>" in the ADS
    wsName = instrument + run;
    if (AnalysisDataService::Instance().doesExist(wsName))
      return AnalysisDataService::Instance().retrieveWS<Workspace>(wsName);
  }

  // We'll just have to load it ourselves
  const std::string filename = instrument + run;
  IAlgorithm_sptr algLoadRun = AlgorithmManager::Instance().create("Load");
  algLoadRun->initialize();
  algLoadRun->setProperty("Filename", filename);
  algLoadRun->setProperty("OutputWorkspace", "TOF_" + run);
  algLoadRun->execute();

  if (!algLoadRun->isExecuted())
    throw std::runtime_error("Could not open " + filename);

  return AnalysisDataService::Instance().retrieveWS<Workspace>("TOF_" + run);
}

/**
Reduce a row
@param rowNo : The row in the model to reduce
@throws std::runtime_error if reduction fails
*/
void ReflTableViewPresenter::reduceRow(int rowNo) {
  const std::string runStr =
      m_model->data(m_model->index(rowNo, ReflTableSchema::COL_RUNS))
          .toString()
          .toStdString();
  const std::string transStr =
      m_model->data(m_model->index(rowNo, ReflTableSchema::COL_TRANSMISSION))
          .toString()
          .toStdString();
  const std::string options =
      m_model->data(m_model->index(rowNo, ReflTableSchema::COL_OPTIONS))
          .toString()
          .toStdString();

  double theta = 0;

  bool thetaGiven =
      !m_model->data(m_model->index(rowNo, ReflTableSchema::COL_ANGLE))
           .toString()
           .isEmpty();

  if (thetaGiven)
    theta = m_model->data(m_model->index(rowNo, ReflTableSchema::COL_ANGLE))
                .toDouble();

  auto runWS = prepareRunWorkspace(runStr);
  const std::string runNo = getRunNumber(runWS);

  Workspace_sptr transWS;
  if (!transStr.empty())
    transWS = makeTransWS(transStr);

  IAlgorithm_sptr algReflOne =
      AlgorithmManager::Instance().create("ReflectometryReductionOneAuto");
  algReflOne->initialize();
  algReflOne->setProperty("InputWorkspace", runWS->name());
  if (transWS)
    algReflOne->setProperty("FirstTransmissionRun", transWS->name());
  algReflOne->setProperty("OutputWorkspace", "IvsQ_" + runNo);
  algReflOne->setProperty("OutputWorkspaceWaveLength", "IvsLam_" + runNo);

  if (thetaGiven)
    algReflOne->setProperty("ThetaIn", theta);

  // Parse and set any user-specified options
  auto optionsMap = parseKeyValueString(options);
  for (auto kvp = optionsMap.begin(); kvp != optionsMap.end(); ++kvp) {
    try {
      algReflOne->setProperty(kvp->first, kvp->second);
    } catch (Mantid::Kernel::Exception::NotFoundError &) {
      throw std::runtime_error("Invalid property in options column: " +
                               kvp->first);
    }
  }

  algReflOne->execute();

  if (!algReflOne->isExecuted())
    throw std::runtime_error("Failed to run ReflectometryReductionOneAuto.");

  const double scale =
      m_model->data(m_model->index(rowNo, ReflTableSchema::COL_SCALE))
          .toDouble();
  if (scale != 1.0) {
    IAlgorithm_sptr algScale = AlgorithmManager::Instance().create("Scale");
    algScale->initialize();
    algScale->setProperty("InputWorkspace", "IvsQ_" + runNo);
    algScale->setProperty("OutputWorkspace", "IvsQ_" + runNo);
    algScale->setProperty("Factor", 1.0 / scale);
    algScale->execute();

    if (!algScale->isExecuted())
      throw std::runtime_error("Failed to run Scale algorithm");
  }

  // Reduction has completed. Put Qmin and Qmax into the table if needed, for
  // stitching.
  if (m_model->data(m_model->index(rowNo, ReflTableSchema::COL_QMIN))
          .toString()
          .isEmpty() ||
      m_model->data(m_model->index(rowNo, ReflTableSchema::COL_QMAX))
          .toString()
          .isEmpty()) {
    Workspace_sptr ws =
        AnalysisDataService::Instance().retrieveWS<Workspace>("IvsQ_" + runNo);
    std::vector<double> qrange = calcQRange(ws, theta);

    if (m_model->data(m_model->index(rowNo, ReflTableSchema::COL_QMIN))
            .toString()
            .isEmpty())
      m_model->setData(m_model->index(rowNo, ReflTableSchema::COL_QMIN),
                       qrange[0]);

    if (m_model->data(m_model->index(rowNo, ReflTableSchema::COL_QMAX))
            .toString()
            .isEmpty())
      m_model->setData(m_model->index(rowNo, ReflTableSchema::COL_QMAX),
                       qrange[1]);

    m_tableDirty = true;
  }

  // We need to make sure that qmin and qmax are respected, so we rebin to
  // those limits here.
  IAlgorithm_sptr algCrop = AlgorithmManager::Instance().create("Rebin");
  algCrop->initialize();
  algCrop->setProperty("InputWorkspace", "IvsQ_" + runNo);
  algCrop->setProperty("OutputWorkspace", "IvsQ_" + runNo);
  const double qmin =
      m_model->data(m_model->index(rowNo, ReflTableSchema::COL_QMIN))
          .toDouble();
  const double qmax =
      m_model->data(m_model->index(rowNo, ReflTableSchema::COL_QMAX))
          .toDouble();
  const double dqq =
      m_model->data(m_model->index(rowNo, ReflTableSchema::COL_DQQ)).toDouble();
  std::vector<double> params;
  params.push_back(qmin);
  params.push_back(-dqq);
  params.push_back(qmax);
  algCrop->setProperty("Params", params);
  algCrop->execute();

  if (!algCrop->isExecuted())
    throw std::runtime_error("Failed to run Rebin algorithm");

  // Also fill in theta if needed
  if (m_model->data(m_model->index(rowNo, ReflTableSchema::COL_ANGLE))
          .toString()
          .isEmpty() &&
      thetaGiven)
    m_model->setData(m_model->index(rowNo, ReflTableSchema::COL_ANGLE), theta);
}

/**
Inserts a new row in the specified location
@param index The index to insert the new row before
*/
void ReflTableViewPresenter::insertRow(int index) {
  const int groupId = getUnusedGroup();
  if (!m_model->insertRow(index))
    return;
  // Set the default scale to 1.0
  m_model->setData(m_model->index(index, ReflTableSchema::COL_SCALE), 1.0);
  // Set the group id of the new row
  m_model->setData(m_model->index(index, ReflTableSchema::COL_GROUP), groupId);
}

/**
Insert a row after the last selected row
*/
void ReflTableViewPresenter::appendRow() {
  std::set<int> rows = m_tableView->getSelectedRows();
  if (rows.empty())
    insertRow(m_model->rowCount());
  else
    insertRow(*rows.rbegin() + 1);
  m_tableDirty = true;
}

/**
Insert a row before the first selected row
*/
void ReflTableViewPresenter::prependRow() {
  std::set<int> rows = m_tableView->getSelectedRows();
  if (rows.empty())
    insertRow(0);
  else
    insertRow(*rows.begin());
  m_tableDirty = true;
}

/**
Get the index of the first blank row, or if none exists, returns -1.
*/
int ReflTableViewPresenter::getBlankRow() {
  // Go through every column of every row (except for the scale column) and
  // check if it's blank.
  // If there's a blank row, return it.
  const int rowCount = m_model->rowCount();
  for (int i = 0; i < rowCount; ++i) {
    bool isBlank = true;
    for (int j = ReflTableSchema::COL_RUNS; j <= ReflTableSchema::COL_OPTIONS;
         ++j) {
      // Don't bother checking the scale or group column, it'll always have a
      // value.
      if (j == ReflTableSchema::COL_SCALE || j == ReflTableSchema::COL_GROUP)
        continue;

      if (!m_model->data(m_model->index(i, j)).toString().isEmpty()) {
        isBlank = false;
        break;
      }
    }

    if (isBlank)
      return i;
  }

  // There are no blank rows
  return -1;
}

/**
Delete row(s) from the model
*/
void ReflTableViewPresenter::deleteRow() {
  std::set<int> rows = m_tableView->getSelectedRows();
  for (auto row = rows.rbegin(); row != rows.rend(); ++row)
    m_model->removeRow(*row);

  m_tableDirty = true;
}

/**
Group rows together
*/
void ReflTableViewPresenter::groupRows() {
  const std::set<int> rows = m_tableView->getSelectedRows();
  // Find the first unused group id, ignoring the selected rows
  const int groupId = getUnusedGroup(rows);

  // Now we just have to set the group id on the selected rows
  for (auto it = rows.begin(); it != rows.end(); ++it)
    m_model->setData(m_model->index(*it, ReflTableSchema::COL_GROUP), groupId);

  m_tableDirty = true;
}

/**
Used by the view to tell the presenter something has changed
*/
void ReflTableViewPresenter::notify(IReflTablePresenter::Flag flag) {
  switch (flag) {
  case IReflTablePresenter::SaveAsFlag:
    saveTableAs();
    break;
  case IReflTablePresenter::SaveFlag:
    saveTable();
    break;
  case IReflTablePresenter::AppendRowFlag:
    appendRow();
    break;
  case IReflTablePresenter::PrependRowFlag:
    prependRow();
    break;
  case IReflTablePresenter::DeleteRowFlag:
    deleteRow();
    break;
  case IReflTablePresenter::ProcessFlag:
    process();
    break;
  case IReflTablePresenter::GroupRowsFlag:
    groupRows();
    break;
  case IReflTablePresenter::NewTableFlag:
    newTable();
    break;
  case IReflTablePresenter::TableUpdatedFlag:
    m_tableDirty = true;
    break;
  case IReflTablePresenter::ExpandSelectionFlag:
    expandSelection();
    break;
  case IReflTablePresenter::OptionsDialogFlag:
    showOptionsDialog();
    break;
  case IReflTablePresenter::ClearSelectedFlag:
    clearSelected();
    break;
  case IReflTablePresenter::CopySelectedFlag:
    copySelected();
    break;
  case IReflTablePresenter::CutSelectedFlag:
    cutSelected();
    break;
  case IReflTablePresenter::PasteSelectedFlag:
    pasteSelected();
    break;
  case IReflTablePresenter::ImportTableFlag:
    importTable();
    break;
  case IReflTablePresenter::OpenTableFlag:
    openTable();
    break;
  case IReflTablePresenter::ExportTableFlag:
    exportTable();
    break;
  case IReflTablePresenter::PlotRowFlag:
    plotRow();
    break;
  case IReflTablePresenter::PlotGroupFlag:
    plotGroup();
    break;
  }
  // Not having a 'default' case is deliberate. gcc issues a warning if there's
  // a flag we aren't handling.
}

/**
Press changes to the same item in the ADS
*/
void ReflTableViewPresenter::saveTable() {
  if (!m_wsName.empty()) {
    AnalysisDataService::Instance().addOrReplace(
        m_wsName, boost::shared_ptr<ITableWorkspace>(m_ws->clone().release()));
    m_tableDirty = false;
  } else {
    saveTableAs();
  }
}

/**
Press changes to a new item in the ADS
*/
void ReflTableViewPresenter::saveTableAs() {
  const std::string userString = m_tableView->askUserString(
      "Save As", "Enter a workspace name:", "Workspace");
  if (!userString.empty()) {
    m_wsName = userString;
    saveTable();
  }
}

/**
Start a new, untitled table
*/
void ReflTableViewPresenter::newTable() {
  if (m_tableDirty && m_options["WarnDiscardChanges"].toBool())
    if (!m_tableView->askUserYesNo(
            "Your current table has unsaved changes. Are you "
            "sure you want to discard them?",
            "Start New Table?"))
      return;