void AlgorithmHistoryWindow::writeToScriptFile() { QString prevDir = MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory(); QString scriptDir(""); // Default script directory if(prevDir.isEmpty()) { scriptDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("pythonscripts.directory")); } else { scriptDir = prevDir; } QString filePath = QFileDialog::getSaveFileName(this,tr("Save Script As "),scriptDir,tr("Script files (*.py)")); // An empty string indicates they clicked cancel if( filePath.isEmpty() ) return; IAlgorithm_sptr genPyScript = AlgorithmManager::Instance().createUnmanaged("GeneratePythonScript"); genPyScript->initialize(); genPyScript->setChild(true); // Use as utility genPyScript->setRethrows(true); // Make it throw to catch errors messages and display them in a more obvious place for this window genPyScript->setPropertyValue("InputWorkspace",m_wsName.toStdString()); genPyScript->setPropertyValue("Filename",filePath.toStdString()); try { genPyScript->execute(); } catch(std::exception &) { QMessageBox::information(this, "Generate Python Script", "Unable to generate script, see log window for details."); } MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(filePath).absoluteDir().path()); }
void AlgorithmHistoryWindow::copytoClipboard() { // We retrieve a string containing the script by outputting the result of GeneratePythonScript // to a temp file, and parsing it from there. // QTemporaryFile will not allow its files to have extensions, and the GeneratePythonScript // validator must contains a list of accepted extensions. For that reason we choose the // workaround of: // - create a temp file through QTemporaryFile; // - take its filepath and append ".py" to it; // - use the filepath to create our own temp file, which we will handle the deletion of. QTemporaryFile temp; temp.open(); temp.close(); std::string tempFilename = temp.fileName().toStdString() + ".py"; // Create and run algorithm. IAlgorithm_sptr genPyScript = AlgorithmManager::Instance().createUnmanaged("GeneratePythonScript"); genPyScript->initialize(); genPyScript->setChild(true); // Use as utility genPyScript->setRethrows(true); // Make it throw to catch errors messages and display them in a more obvious place for this window genPyScript->setPropertyValue("InputWorkspace",m_wsName.toStdString()); genPyScript->setPropertyValue("Filename",tempFilename); try { genPyScript->execute(); } catch(std::exception &) { QMessageBox::information(this, "Generate Python Script", "Unable to generate script, see log window for details."); return; } QString script; std::ifstream file(tempFilename.c_str(), std::ifstream::in); std::stringstream buffer; // Retrieve script from file. buffer << file.rdbuf(); std::string contents(buffer.str()); script.append(contents.c_str()); file.close(); remove(tempFilename.c_str()); // Send to clipboard. QClipboard *clipboard = QApplication::clipboard(); if(NULL != clipboard) { clipboard->setText(script); } }
/** Execute the algorithm. */ void NormaliseByDetector::exec() { MatrixWorkspace_sptr inWS = getProperty("InputWorkspace"); // Do the work of extracting functions and applying them to each bin on each // histogram. The denominator workspace is mutable. MatrixWorkspace_sptr denominatorWS = processHistograms(inWS); // Perform the normalisation. IAlgorithm_sptr divideAlg = this->createChildAlgorithm("Divide", 0.9, 1.0, true); divideAlg->setRethrows(true); divideAlg->setProperty("LHSWorkspace", inWS); divideAlg->setProperty("RHSWorkspace", denominatorWS); divideAlg->executeAsChildAlg(); MatrixWorkspace_sptr outputWS = divideAlg->getProperty("OutputWorkspace"); setProperty("OutputWorkspace", outputWS); }
/** Apply dead-time corrections. The calculation is done by ApplyDeadTimeCorr * algorithm * @param loadedWs :: [input/output] Workspace to apply corrections to * @param deadTimes :: [input] Corrections to apply */ void PlotAsymmetryByLogValue::applyDeadtimeCorr(Workspace_sptr &loadedWs, Workspace_sptr deadTimes) { ScopedWorkspace ws(loadedWs); ScopedWorkspace dt(deadTimes); IAlgorithm_sptr applyCorr = AlgorithmManager::Instance().create("ApplyDeadTimeCorr"); applyCorr->setLogging(false); applyCorr->setRethrows(true); applyCorr->setPropertyValue("InputWorkspace", ws.name()); applyCorr->setPropertyValue("OutputWorkspace", ws.name()); applyCorr->setProperty("DeadTimeTable", dt.name()); applyCorr->execute(); // Workspace should've been replaced in the ADS by ApplyDeadTimeCorr, so // need to // re-assign it loadedWs = ws.retrieve(); }
/** * Start fitting process. */ void MuonSequentialFitDialog::startFit() { if ( m_state != Stopped ) throw std::runtime_error("Couln't start: already running"); setState(Preparing); // Explicitly run the file search. This might be needed when Start is clicked straigh after // editing the run box. In that case, lost focus event might not be processed yet and search // might not have been started yet. Otherwise, search is not done as the widget sees that it // has not been changed. Taken from LoadDialog.cpp:124. m_ui.runs->findFiles(); // Wait for file search to finish. while ( m_ui.runs->isSearching() ) { QApplication::processEvents(); } // To process events from the finished thread QApplication::processEvents(); // Validate input fields if ( ! isInputValid() ) { QMessageBox::critical(this, "Input is not valid", "One or more input fields are invalid.\n\nInvalid fields are marked with a '*'."); setState(Stopped); return; } QStringList runFilenames = m_ui.runs->getFilenames(); const std::string label = m_ui.labelInput->text().toStdString(); const std::string labelGroupName = SEQUENTIAL_PREFIX + label; AnalysisDataServiceImpl& ads = AnalysisDataService::Instance(); if ( ads.doesExist(labelGroupName) ) { QMessageBox::StandardButton answer = QMessageBox::question(this, "Label already exists", "Label you specified was used for one of the previous fits. Do you want to overwrite it?", QMessageBox::Yes | QMessageBox::Cancel); if ( answer != QMessageBox::Yes ) { setState(Stopped); return; } ads.deepRemoveGroup(labelGroupName); } // Create a group for label ads.add(labelGroupName, boost::make_shared<WorkspaceGroup>()); // Tell progress bar how many iterations we will need to make and reset it m_ui.progress->setRange( 0, runFilenames.size() ); m_ui.progress->setFormat("%p%"); m_ui.progress->setValue(0); // Clear diagnosis table for new fit m_ui.diagnosisTable->setRowCount(0); // Get fit function as specified by user in the fit browser IFunction_sptr fitFunction = FunctionFactory::Instance().createInitialized( m_fitPropBrowser->getFittingFunction()->asString() ); // Whether we should use initial function for every fit bool useInitFitFunction = (m_ui.paramTypeGroup->checkedButton() == m_ui.paramTypeInitial); setState(Running); m_stopRequested = false; for ( auto fileIt = runFilenames.constBegin(); fileIt != runFilenames.constEnd(); ++fileIt ) { // Process events (so that Stop button press is processed) QApplication::processEvents(); // Stop if requested by user if ( m_stopRequested ) break; MatrixWorkspace_sptr ws; try { auto load = AlgorithmManager::Instance().create("MuonLoad"); load->initialize(); load->setChild(true); load->setRethrows(true); load->updatePropertyValues(*m_loadAlg); load->setPropertyValue("Filename", fileIt->toStdString()); load->setPropertyValue("OutputWorkspace", "__YouDontSeeMeIAmNinja"); if (m_fitPropBrowser->rawData()) // TODO: or vice verca? load->setPropertyValue("RebinParams", ""); load->execute(); ws = load->getProperty("OutputWorkspace"); } catch (...) { QMessageBox::critical( this, "Loading failed", "Unable to load one of the files.\n\nCheck log for details"); break; } const std::string runTitle = getRunTitle(ws); const std::string wsBaseName = labelGroupName + "_" + runTitle; IFunction_sptr functionToFit; if ( useInitFitFunction ) // Create a copy so that the original function is not changed functionToFit = FunctionFactory::Instance().createInitialized( fitFunction->asString() ); else // Use the same function over and over, so that previous fitted params are used for the next fit functionToFit = fitFunction; IAlgorithm_sptr fit = AlgorithmManager::Instance().create("Fit"); fit->setRethrows(true); try { // Set function. Gets updated when fit is done. fit->setProperty("Function", functionToFit); fit->setProperty("InputWorkspace", ws); fit->setProperty("Output", wsBaseName); // We should have one spectra only in the workspace, so use the first one. fit->setProperty("WorkspaceIndex", 0); // Various properties from the fit prop. browser fit->setProperty("StartX", m_fitPropBrowser->startX()); fit->setProperty("EndX", m_fitPropBrowser->endX()); fit->setProperty("Minimizer", m_fitPropBrowser->minimizer()); fit->setProperty("CostFunction", m_fitPropBrowser->costFunction()); fit->execute(); } catch(...) { QMessageBox::critical(this, "Fitting failed", "Unable to fit one of the files.\n\nCheck log for details"); break; } // Make sure created fit workspaces end-up in the group // TODO: this really should use loop ads.addToGroup(labelGroupName, wsBaseName + "_NormalisedCovarianceMatrix"); ads.addToGroup(labelGroupName, wsBaseName + "_Parameters"); ads.addToGroup(labelGroupName, wsBaseName + "_Workspace"); // Copy log values auto fitWs = ads.retrieveWS<MatrixWorkspace>(wsBaseName + "_Workspace"); fitWs->copyExperimentInfoFrom(ws.get()); // Add information about the fit to the diagnosis table addDiagnosisEntry(runTitle, fit->getProperty("OutputChi2OverDof"), functionToFit); // Update progress m_ui.progress->setFormat("%p% - " + QString::fromStdString(runTitle) ); m_ui.progress->setValue( m_ui.progress->value() + 1 ); } setState(Stopped); }