void MainWindow::documentOpen(void) { PluginFileIOFactory *fileIOFactory = sharedPluginFileIOFactory(); QString filter = tr("Dunnart diagrams (") + fileIOFactory->openableFileTypesString() + ")"; // Determine the working directory. QSettings settings; QString workingDir(QDir::homePath()); QVariant workingDirSetting = settings.value("workingDirectory"); if (workingDirSetting.isValid()) { workingDir = workingDirSetting.toString(); } QString fileNameString = QFileDialog::getOpenFileName(this, tr("Open Diagram"), workingDir, filter); if (!fileNameString.isEmpty()) { QSettings settings; settings.setValue("workingDirectory", QFileInfo(fileNameString).absolutePath()); settings.sync(); loadDiagram(fileNameString); } }
void RunPotentialParamsQueue::updateTable(const utility::DataTable::Key & key, const StructureDataType * const structureData) { utility::insertStructureInfoAndPotentialParams(key, *structureData, workingDir(), myTableSupport.getTable()); }
bool validate(const FilePath& userHomePath, bool projectSharingEnabled) const { // ensure the scratch path and properties paths exist if (!scratchPath_.exists() || !propertiesPath_.exists()) return false; // ensure the properties are there if (project().empty() || workingDir().empty() || (lastUsed() == 0)) return false; // for projects validate that the base directory still exists std::string theProject = project(); if (theProject != kProjectNone) { FilePath projectDir = FilePath::resolveAliasedPath(theProject, userHomePath); if (!projectDir.exists()) return false; // check for project file FilePath projectPath = r_util::projectFromDirectory(projectDir); if (!projectPath.exists()) return false; // if we got this far the scope is valid, do one final check for // trying to open a shared project if sharing is disabled if (!projectSharingEnabled && r_util::isSharedPath(projectPath.absolutePath(), userHomePath)) return false; } // validated! return true; }
iCelHNavStruct* celHNavStructBuilder::LoadHNavStruct (iVFS* vfs, const char* directory) { csRef<iDocumentSystem> docsys = csLoadPluginCheck<iDocumentSystem>(objectRegistry, "crystalspace.documentsystem.tinyxml"); if (!docsys) { return 0; } // Mount file csString workingDir(vfs->GetCwd()); vfs->ChDir(directory); // Read XML file csRef<iDocument> doc = docsys->CreateDocument(); csRef<iFile> xmlFile = vfs->Open("navstruct.xml", VFS_FILE_READ); if(!xmlFile.IsValid()) { return 0; } const char* log = doc->Parse(xmlFile); if (log) { return 0; } csRef<iDocumentNode> root = doc->GetRoot(); csRef<iDocumentNode> mainNode = root->GetNode("iCelHNavStruct"); // Read parameters csRef<iDocumentNode> paramsNode = mainNode->GetNode("parameters"); csRef<iCelNavMeshParams> params; params.AttachNew(new celNavMeshParams()); ParseParameters(paramsNode, params); // Create navigation structure csRef<celHNavStruct> navStruct; navStruct.AttachNew(new celHNavStruct(params, objectRegistry)); // Read navigation meshes csRef<iDocumentNode> meshesNode = mainNode->GetNode("navmeshes"); csHash<csRef<iSector>, const char*> sectors; if(!ParseMeshes(meshesNode, sectors, navStruct, vfs, params)) { return 0; } // Read high level graph csRef<iDocumentNode> graphNode = mainNode->GetNode("highlevelgraph"); csRef<iCelGraph> graph = scfCreateInstance<iCelGraph>("cel.celgraph"); if(!ParseGraph(graphNode, graph, sectors)) { return 0; } navStruct->SetHighLevelGraph(graph); this->navStruct = navStruct; vfs->ChDir(workingDir.GetDataSafe()); return navStruct; }
int dir(vector<string>argVector) { //Execute dir command char workingDir_Cstr[FILENAME_MAX]; vector<string> dirContents; GetWorkingDir(workingDir_Cstr, sizeof(workingDir_Cstr)); string workingDir(workingDir_Cstr); cout << workingDir << '\n'; #ifdef WINDOWS workingDir = workingDir + "\\*"; WIN32_FIND_DATA fileData; HANDLE hFind; hFind = FindFirstFile(workingDir.c_str(), &fileData); if (hFind == INVALID_HANDLE_VALUE) { cout << "\n Failure accessing directory\n"; return 0; } while (FindNextFile(hFind, &fileData)) { if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { cout << "\t <DIR> " << fileData.cFileName << '\n'; } else { cout << "\t" << fileData.cFileName << '\n'; } } #else DIR *dp; struct dirent *dirp; string DIRstr; if ((dp = opendir(workingDir.c_str())) == NULL) { cout << "\n Failure accessing directory\n"; return 0; } while ((dirp = readdir(dp)) != NULL) { if (dirp->d_type == DT_DIR) { DIRstr = dirp->d_name; if ((DIRstr != ".") && (DIRstr != "..")) cout << "\t <DIR> " << dirp->d_name << '\n'; } else { cout << "\t" << dirp->d_name << '\n'; } } closedir(dp); #endif return 0; }
wxString MemCheckPlugin::PrepareCommand(const wxString& projectName, wxString& wd) { wd.clear(); if(!clCxxWorkspaceST::Get()->IsOpen()) { return ""; } ProjectPtr proj = clCxxWorkspaceST::Get()->GetProject(projectName); if(!proj) { clWARNING() << "MemCheckPlugin::PrepareCommand(): could not find project:" << projectName; return wxEmptyString; } BuildConfigPtr bldConf = clCxxWorkspaceST::Get()->GetProjBuildConf(projectName, wxEmptyString); if(!bldConf) { clWARNING() << "MemCheckPlugin::PrepareCommand(): failed to find project configuration for project:" << projectName; return wxEmptyString; } wxString projectPath = proj->GetFileName().GetPath(); // expand variables wxString cmd = bldConf->GetCommand(); cmd = MacroManager::Instance()->Expand(cmd, NULL, projectName); wxString cmdArgs = bldConf->GetCommandArguments(); cmdArgs = MacroManager::Instance()->Expand(cmdArgs, NULL, projectName); // Execute command & cmdArgs wd = bldConf->GetWorkingDirectory(); wd = MacroManager::Instance()->Expand(wd, NULL, projectName); wxFileName workingDir(wd, ""); if(workingDir.IsRelative()) { workingDir.MakeAbsolute(projectPath); } wxFileName fileExe(cmd); if(fileExe.IsRelative()) { fileExe.MakeAbsolute(workingDir.GetPath()); } fileExe.Normalize(); #ifdef __WXMSW__ if(!fileExe.Exists() && fileExe.GetExt().IsEmpty()) { // Try with .exe wxFileName withExe(fileExe); withExe.SetExt("exe"); if(withExe.Exists()) { fileExe = withExe; } } #endif wd = workingDir.GetPath(); cmd = fileExe.GetFullPath(); cmd = ::WrapWithQuotes(cmd); cmd << " " << cmdArgs; clDEBUG() << "Command to execute:" << cmd; clDEBUG() << "Working directory:" << wd; return cmd; }
void CefIPCPipeClient::startService() { #ifdef DEBUG const char* exeName = "desura_browserhost-d.exe"; #else const char* exeName = "desura_browserhost.exe"; #endif UserAgentFN userAgent = (UserAgentFN)WebCore::FactoryBuilder(WEBCORE_USERAGENT); gcString ua = userAgent(); gcString exe(exeName); gcString params("{3} {0} {1} {2}", m_szPipeId, m_szHostName, UTIL::STRING::base64_encode(ua.c_str(), ua.size()), exeName); DWORD dwExitCode = 0; STARTUPINFOA siStartupInfo; PROCESS_INFORMATION piProcessInfo; memset(&siStartupInfo, 0, sizeof(siStartupInfo)); memset(&piProcessInfo, 0, sizeof(piProcessInfo)); siStartupInfo.cb = sizeof(siStartupInfo); gcString workingDir(UTIL::OS::getCurrentDir()); UINT oldErrMode = SetErrorMode(0); BOOL res = CreateProcessA(const_cast<char*>(exe.c_str()), const_cast<char*>(params.c_str()), 0, 0, false, CREATE_DEFAULT_ERROR_MODE, 0, workingDir.c_str(), &siStartupInfo, &piProcessInfo); DWORD lastError = GetLastError(); SetErrorMode(oldErrMode); CloseHandle( piProcessInfo.hThread ); if (res == false) { CloseHandle( piProcessInfo.hProcess ); throw gcException(ERR_LAUNCH, lastError, "Failed to start render helper"); } else { #ifdef DEBUG WaitForInputIdle(piProcessInfo.hProcess, INFINITE); #else WaitForInputIdle(piProcessInfo.hProcess, 5000); #endif CloseHandle( piProcessInfo.hProcess ); } }
bool celHNavStruct::SaveToFile (iVFS* vfs, const char* directory) { csRef<iDocumentSystem> docsys = csLoadPluginCheck<iDocumentSystem>(objectRegistry, "crystalspace.documentsystem.tinyxml"); if (!docsys) { return false; } csString workingDir(vfs->GetCwd()); vfs->ChDir(directory); // Create XML file csRef<iDocument> doc = docsys->CreateDocument(); csRef<iDocumentNode> root = doc->CreateRoot(); csRef<iDocumentNode> mainNode = root->CreateNodeBefore(CS_NODE_ELEMENT); mainNode->SetValue("iCelHNavStruct"); // Create parameters subtree csRef<iDocumentNode> params = mainNode->CreateNodeBefore(CS_NODE_ELEMENT); params->SetValue("parameters"); SaveParameters(params); // Create navmeshes subtree csRef<iDocumentNode> navmeshes = mainNode->CreateNodeBefore(CS_NODE_ELEMENT); navmeshes->SetValue("navmeshes"); SaveNavMeshes(navmeshes, vfs); // Create highlevelgraph subtree csRef<iDocumentNode> hlgraph = mainNode->CreateNodeBefore(CS_NODE_ELEMENT); hlgraph->SetValue("highlevelgraph"); csRef<iDocumentNode> nodes = hlgraph->CreateNodeBefore(CS_NODE_ELEMENT); nodes->SetValue("nodes"); csRef<iDocumentNode> edges = hlgraph->CreateNodeBefore(CS_NODE_ELEMENT); edges->SetValue("edges"); SaveHighLevelGraph(nodes, edges); // Write xml file const char* log = doc->Write(vfs, "navstruct.xml"); vfs->ChDir(workingDir.GetDataSafe()); vfs->Sync(); if (log) { return false; } return true; }
status_t SVNSourceControl::DeleteRepository(const char *path) { if (!path || strlen(path) < 1) return B_ERROR; DPath workingDir(path); DPath repoPath(sRepoPath); repoPath << workingDir.GetFileName(); BString command("rm -r "); command << "'" << repoPath.GetFullPath() << "'"; BString out; RunCommand(command, out); return B_OK; }
status_t SVNSourceControl::CreateRepository(const char *path) { // The SourceControl class runs under the DSCM idea of the local directory // being a repository. Seeing how SVN doesn't allow for this, we create a // repository elsewhere on the hard drive, check it out to the path we were // given, and add the files to the repository. Checking in is not part of // this call, however. DPath workingDir(path); DPath repoPath(sRepoPath); repoPath << workingDir.GetFileName(); BDirectory dir(sRepoPath.String()); if (dir.InitCheck() != B_OK) create_directory(sRepoPath.String(), 0777); BString command("svnadmin create "); command << "'" << repoPath.GetFullPath() << "'"; BString out; RunCommand(command, out); BString repoURL = "file://"; repoURL << repoPath.GetFullPath(); SetURL(repoURL.String()); SetWorkingDirectory(path); CloneRepository(repoURL.String(), path); BPath svnpath(path); svnpath.Append(".svn"); if (!BEntry(svnpath.Path()).Exists()) return B_ERROR; command = ""; command << "cd '" << path << "'; " << "svn add --non-interactive *"; RunCommand(command, out); return B_OK; }
void FileTestContext::inputFile(const char* filename) { UtlString inputPath; inputFilePath(filename, inputPath); UtlString workingPath; workingFilePath(filename, workingPath); OsPath input(inputPath); OsPath working(workingPath); OsPath workingDirPath(working.getDirName()); workingDirPath.strip(UtlString::trailing, OsPath::separator(0)); OsDir workingDir(workingDirPath); if (!workingDir.exists()) { UtlString msg; msg.append("FileTestContext::inputFile failed to create working directory '"); msg.append(working.getDirName().data()); msg.append("'"); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), OS_SUCCESS,OsFileSystem::createDir(workingDirPath,TRUE)); } UtlString msg; msg.append("FileTestContext::inputFile copy failed from '"); msg.append(inputPath); msg.append("' -> '"); msg.append(workingPath); msg.append("'"); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), OS_SUCCESS, OsFileSystem::copy(input, working) ); Os::Logger::instance().log(FAC_UNIT_TEST, PRI_NOTICE, "FileTestContext::inputFile '%s' -> '%s'", inputPath.data(), workingPath.data()); }
void SearchStoichiometries::releaseBufferedStructures( const utility::DataTable::Key & tableKey) { // Send any finished structure data down my pipe utility::DataTable & table = myTableSupport.getTable(); ssio::ResourceLocator lastSavedRelative; BOOST_FOREACH(StructureDataType * const structure, myBuffer) { lastSavedRelative = common::getRelativeSavePath(*structure, workingDir()); if(!lastSavedRelative.empty()) { // Insert the relative path to the last place this structre was saved table.insert(tableKey, "lowest", lastSavedRelative.string()); } if(const unsigned int * const spacegroup = structure->properties().find( structure_properties::general::SPACEGROUP_NUMBER)) { table.insert(tableKey, "sg", boost::lexical_cast< std::string>(*spacegroup)); } // Try to calculate the energy/atom if(const double * const internalEnergy = structure->properties().find( structure_properties::general::ENERGY_INTERNAL)) { const size_t numAtoms = structure->getNumAtoms(); if(numAtoms != 0) table.insert(tableKey, "energy/atom", common::toString(*internalEnergy / numAtoms)); } // Pass the structure on out(structure); }
bool QGenieExport2DiskFileThread::copyFile(const QString &filePath,const QString &destDir) { qDebug () << "Copyt " << filePath << "to " << destDir; QString path2MK = filePath.mid(2,filePath.lastIndexOf("/") - 2); QDir workingDir(destDir); if(!workingDir.mkpath(path2MK)) { return false; } QDir destDir_(destDir); QString fileName = destDir_.absolutePath() + QDir::separator() + filePath.mid(2); if(QFile::exists(fileName)) { QFile::setPermissions(fileName,QFile::WriteOther); QFile::remove(fileName); } return QFile::copy(filePath,fileName); }
// Inject webinos.js // The file is loaded from the webinos\test\client folder if possible. // If this fails, the current folder is used. void ClientApp::InjectWebinos(CefRefPtr<CefFrame> frame) { CefRefPtr<CefCommandLine> commandLine = AppGetCommandLine(); // First try and load the platform-supplied webinos.js #if defined(OS_WIN) FilePath workingDir(commandLine->GetProgram().ToWString().c_str()); FilePath webinosJSPath = workingDir.DirName().Append(L"..\\..\\webinos\\web_root\\webinos.js"); #else FilePath workingDir(commandLine->GetProgram()); FilePath webinosJSPath = workingDir.DirName().Append("..\\..\\webinos\\web_root\\webinos.js"); #endif int64 webinosJSCodeSize; bool gotJSFile = file_util::GetFileSize(webinosJSPath, &webinosJSCodeSize); if (!gotJSFile) { // Unable to load the platform-supplied webinos.js, use the installed version. #if defined(OS_WIN) workingDir = FilePath(commandLine->GetProgram().ToWString().c_str()); webinosJSPath = workingDir.DirName().Append(L"webinos.js"); #else workingDir = FilePath(commandLine->GetProgram()); webinosJSPath = workingDir.DirName().Append("webinos.js"); #endif gotJSFile = file_util::GetFileSize(webinosJSPath, &webinosJSCodeSize); } if (gotJSFile) { char* webinosJSCode = new char[webinosJSCodeSize+1]; file_util::ReadFile(webinosJSPath, webinosJSCode, webinosJSCodeSize); webinosJSCode[webinosJSCodeSize] = 0; if (frame == NULL) { // Register as a Cef extension. CefRegisterExtension("webinos", webinosJSCode, NULL); } else { // Run the code in the frame javascript context right now, // but only if the URL refers to the widget server. int widgetServerPort; AppGetWebinosWRTConfig(NULL,&widgetServerPort); char injectionCandidate[MAX_URL_LENGTH]; sprintf(injectionCandidate,"http://localhost:%d",widgetServerPort); std::string url = frame->GetURL(); if (url.substr(0,strlen(injectionCandidate)) == injectionCandidate) frame->ExecuteJavaScript(webinosJSCode, url, 0); } delete[] webinosJSCode; } else { LOG(ERROR) << "Can't find webinos.js"; } }
int main( int argc, char *argv[] ) { // try { time_t programStartTime(time(NULL) ); boost::filesystem::path workingDir( boost::filesystem::current_path() ); // ========== PROGRAM PARAMETERS ========== std::string progName( "buildrandctree" ); std::string configFilename( "/home/raid2/moreno/Code/hClustering/config/"+progName+".cfg" ); // program parameters std::string roiFilename, inputFolder, outputFolder; float memory( 0.5 ), maxNbDist( 1 ); unsigned int nbLevel( 26 ), threads( 0 ); bool keepDiscarded( false ), niftiMode( true ), debug( false ); TC_GROWTYPE growType( TC_GROWOFF ); size_t baseSize( 0 ); // Declare a group of options that will be allowed only on command line boost::program_options::options_description genericOptions( "Generic options" ); genericOptions.add_options() ( "version", "Program version" ) ( "help,h", "Produce extended program help message" ) ( "roi,r", boost::program_options::value< std::string >(&roiFilename), "file with the seed voxels coordinates." ) ( "inputf,I", boost::program_options::value< std::string >(&inputFolder), "input data folder (seed tractograms)." ) ( "outputf,O", boost::program_options::value< std::string >(&outputFolder), "output folder" ) ( "maxnbdist,d", boost::program_options::value< float >(&maxNbDist)->implicit_value(1), "[opt] maximum dissimilarity a seed voxel tract must have to its most similar neighbor not be discarded. (0,1]." ) ( "cnbhood,c", boost::program_options::value< unsigned int >(&nbLevel)->implicit_value(26), "[opt] centroid method neighborhood level. Valid values: 6, 18, 26(default), 32, 96, 124." ) ( "basesize,S", boost::program_options::value< size_t >(&baseSize), "[opt] grow homogeneous base nodes (meta-leaves) of size S. (>=2)." ) ( "basenum,N", boost::program_options::value< size_t >(&baseSize), "[opt] grow N homogeneous base nodes (meta-leaves). (>=10)." ) ; // Declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description configOptions( "Configuration" ); configOptions.add_options() ( "verbose,v", "[opt] verbose output." ) ( "vista", "[opt] use vista file format (default is nifti)." ) ( "cache-mem,m", boost::program_options::value< float >(&memory)->implicit_value(0.5), "[opt] maximum of memory (in GBytes) to use for tractogram cache memory. Default: 0.5." ) ( "keep-disc,k", "[opt] keep discarded voxels data in a section of the tree file." ) ( "debugout", "[opt] write additional detailed outputs meant for debug." ) ( "pthreads,p", boost::program_options::value< unsigned int >(&threads), "[opt] number of processing cores to run the program in. Default: all available." ) ; // Hidden options, will be allowed both on command line and in config file, but will not be shown to the user. boost::program_options::options_description hiddenOptions( "Hidden options" ); //hiddenOptions.add_options() ; boost::program_options::options_description cmdlineOptions; cmdlineOptions.add(genericOptions).add(configOptions).add(hiddenOptions); boost::program_options::options_description configFileOptions; configFileOptions.add(configOptions).add(hiddenOptions); boost::program_options::options_description visibleOptions( "Allowed options" ); visibleOptions.add(genericOptions).add(configOptions); boost::program_options::positional_options_description posOpt; //this arguments do not need to specify the option descriptor when typed in //posOpt.add( "roi", -1); boost::program_options::variables_map variableMap; store(boost::program_options::command_line_parser(argc, argv).options(cmdlineOptions).positional(posOpt).run(), variableMap); std::ifstream ifs(configFilename.c_str() ); store(parse_config_file(ifs, configFileOptions), variableMap); notify( variableMap); if ( variableMap.count( "help" ) ) { std::cout << "---------------------------------------------------------------------------" << std::endl; std::cout << std::endl; std::cout << " Project: hClustering" << std::endl; std::cout << std::endl; std::cout << " Whole-Brain Connectivity-Based Hierarchical Parcellation Project" << std::endl; std::cout << " David Moreno-Dominguez" << std::endl; std::cout << " [email protected]" << std::endl; std::cout << " [email protected]" << std::endl; std::cout << " www.cbs.mpg.de/~moreno" << std::endl; std::cout << std::endl; std::cout << " For more reference on the underlying algorithm and research they have been used for refer to:" << std::endl; std::cout << " - Moreno-Dominguez, D., Anwander, A., & Knösche, T. R. (2014)." << std::endl; std::cout << " A hierarchical method for whole-brain connectivity-based parcellation." << std::endl; std::cout << " Human Brain Mapping, 35(10), 5000-5025. doi: http://dx.doi.org/10.1002/hbm.22528" << std::endl; std::cout << " - Moreno-Dominguez, D. (2014)." << std::endl; std::cout << " Whole-brain cortical parcellation: A hierarchical method based on dMRI tractography." << std::endl; std::cout << " PhD Thesis, Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig." << std::endl; std::cout << " ISBN 978-3-941504-45-5" << std::endl; std::cout << std::endl; std::cout << " hClustering is free software: you can redistribute it and/or modify" << std::endl; std::cout << " it under the terms of the GNU Lesser General Public License as published by" << std::endl; std::cout << " the Free Software Foundation, either version 3 of the License, or" << std::endl; std::cout << " (at your option) any later version." << std::endl; std::cout << " http://creativecommons.org/licenses/by-nc/3.0" << std::endl; std::cout << std::endl; std::cout << " hClustering is distributed in the hope that it will be useful," << std::endl; std::cout << " but WITHOUT ANY WARRANTY; without even the implied warranty of" << std::endl; std::cout << " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" << std::endl; std::cout << " GNU Lesser General Public License for more details." << std::endl; std::cout << std::endl; std::cout << "---------------------------------------------------------------------------" << std::endl << std::endl; std::cout << "buildrandctree" << std::endl << std::endl; std::cout << "Build a centroid hierarchical tree from a set of artificially pre-generated set of tractograms yoielding a uniformly random similarity matrix and a seed neighborhood information voxel list." << std::endl << std::endl; std::cout << "* Arguments:" << std::endl << std::endl; std::cout << " --version: Program version." << std::endl << std::endl; std::cout << " -h --help: Produce extended program help message." << std::endl << std::endl; std::cout << " -r --roi: A text file with the seed voxel coordinates and the corresponding tractogram index (if tractogram naming is based on index rather than coordinates)." << std::endl << std::endl; std::cout << " -I --inputf: input data folder (containing the compact tractograms)." << std::endl << std::endl; std::cout << " -O --outputf: Output folder where tree files will be written." << std::endl << std::endl; std::cout << "[-d --maxnbdist]: Maximum dissimilarity a seed voxel tract must have to its most similar neighbor not be discarded." << std::endl; std::cout << " Valid values: (0,1] Use a value of 1 (default) if no discarding is desired." << std::endl << std::endl; std::cout << "[-c --cnbhood]: Use centroid method with C neighborhood level. Valid values: 6, 18, 24(default), 32, 96, 124." << std::endl << std::endl; std::cout << "[-S --basesize]: Merge homogeneous base nodes of size S. (mutually exclusive with -N option). Default: 0 (no homogeneous merging)." << std::endl << std::endl; std::cout << "[-N --basenum]: Grow N homogeneous base nodes. (mutually exclusive with -S option). Default: 0 (no homogeneous merging)." << std::endl << std::endl; std::cout << "[-v --verbose]: Verbose output (recommended)." << std::endl << std::endl; std::cout << "[--vista]: Read/write vista (.v) files [default is nifti (.nii) and compact (.cmpct) files]." << std::endl << std::endl; std::cout << "[-m --cache-mem]: Maximum amount of RAM memory (in GBytes) to use for temporal tractogram cache storing. Valid values [0.1,50]. Default: 0.5." << std::endl << std::endl; std::cout << "[-k --keep-disc]: Keep discarded voxel information in a specialiced section of the tree." << std::endl << std::endl; std::cout << "[--debugout]: Write additional detailed outputs meant to be used for debugging." << std::endl << std::endl; std::cout << "[-p --pthreads]: Number of processing threads to run the program in parallel. Default: use all available processors." << std::endl << std::endl; std::cout << std::endl; std::cout << "* Usage example:" << std::endl << std::endl; std::cout << " buildrandctree -r roi_lh.txt -I tractograms/ -O results/ -c 26 -N 1000 -k -m 2 -v " << std::endl << std::endl; std::cout << std::endl; std::cout << "* Outputs (in output folder defined at option -O):" << std::endl << std::endl; std::cout << " - 'cX_bin_nmt.txt' - (where X is the neighborhood level defined at option -c) non-monotonic binary-branching hierarchical tree without tree processing (if desired use processtree command)." << std::endl; std::cout << " - 'baselist_nmt.txt' - meta-leaves (base nodes defined by the us of option -N or -S) list with IDs corresponding to the non-monotonic tree file." << std::endl; std::cout << " - 'success.txt' - An empty file created when the program has sucessfully exited after completion (to help for automatic re-running scripting after failure)." << std::endl; std::cout << " - 'buildrandtree_log.txt' - A text log file containing the parameter details and in-run and completion information of the program." << std::endl; std::cout << std::endl; std::cout << " [extra outputs when using --debugout option)" << std::endl << std::endl; std::cout << " - 'cX_bin_nmt_debug.txt' - version of the counterpart file without '_debug' suffix with redundant information for debugging purposes." << std::endl; std::cout << std::endl; exit(0); } if ( variableMap.count( "verbose" ) ) { std::cout << "verbose output" << std::endl; verbose=true; } if ( variableMap.count( "pthreads" ) ) { if ( threads == 1 ) { std::cout << "Using a single processor" << std::endl; } else if( threads == 0 || threads >= omp_get_num_procs() ) { threads = omp_get_num_procs(); std::cout << "Using all available processors ( " << threads << " )." << std::endl; } else { std::cout << "Using a maximum of " << threads << " processors " << std::endl; } omp_set_num_threads( threads ); } else { threads = omp_get_num_procs(); omp_set_num_threads( threads ); std::cout << "Using all available processors ( " << threads << " )." << std::endl; } if ( variableMap.count( "vista" ) ) { if( verbose ) { std::cout << "Using vista format" << std::endl; } fileManagerFactory fmf; fmf.setVista(); niftiMode = false; } else { if( verbose ) { std::cout << "Using nifti format" << std::endl; } fileManagerFactory fmf; fmf.setNifti(); niftiMode = true; } if ( variableMap.count( "debugout" ) ) { if( verbose ) { std::cout << "Debug output files activated" << std::endl; } debug = true; } if ( variableMap.count( "version" ) ) { std::cout << progName << ", version 2.0" << std::endl; exit(0); } if ( variableMap.count( "roi" ) ) { if( !boost::filesystem::is_regular_file( boost::filesystem::path( roiFilename ) ) ) { std::cerr << "ERROR: roi file \"" <<roiFilename<< "\" is not a regular file" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if( verbose ) { std::cout << "Seed voxels roi file: " << roiFilename << std::endl; } } else { std::cerr << "ERROR: no seed voxels roi file stated" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if( verbose ) { std::cout << "Maximum distance to most similar neighbor: " << maxNbDist << std::endl; } if ( maxNbDist <= 0 || maxNbDist > 1 ) { std::cerr << "ERROR: distance value used is out of bounds please use a value within (0,1]" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if ( maxNbDist == 1 && verbose ) { std::cout << "No neighbor distance restrictions will be applied" << std::endl; } else if( verbose ) { std::cout << "Seed voxels with no neighbors with tract dissimilarity lower than " << maxNbDist << " will be discarded as outliers" << std::endl; } if( verbose ) { std::cout << "Centroid neighborhood level: " << nbLevel << std::endl; } if ( ( nbLevel != 6 ) && ( nbLevel != 18 ) && ( nbLevel != 26 ) && ( nbLevel != 32 ) && ( nbLevel != 92 ) && ( nbLevel != 124 ) ) { std::cerr << "ERROR: invalid nbhood level, only (6,18,26,32,92,124) are accepted" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if ( ( variableMap.count( "basesize" ) && variableMap.count( "basenum" ) ) ) { std::cerr << "ERROR: options --basesize (-S) and --basenum (-N) are mutually exclusive" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if ( variableMap.count( "basesize" ) ) { if( baseSize <= 1 ) { std::cerr << "ERROR: base node (meta-leaf) size must be greater than 1" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else { if( verbose ) { std::cout << "Initial merging stage up to homogeneous base nodes of size: " << baseSize << std::endl; } growType = TC_GROWSIZE; } } if ( variableMap.count( "basenum" ) ) { if( baseSize < 10 ) { std::cerr << "ERROR: base node (meta-leaf) number must be equal or greater than 10" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else { if( verbose ) { std::cout << "Initial merging stage up to " << baseSize << " homogeneous base nodes (meta-leaves)" << std::endl; } growType = TC_GROWNUM; } } if( growType == TC_GROWOFF && verbose ) { std::cout << "No homogeneous merging stage" << std::endl; } if ( variableMap.count( "keep-disc" ) ) { if( verbose ) { std::cout << "Discarded voxel coordinates will be saved in an special section fo the tree file" << std::endl; } keepDiscarded = true; } else { if( verbose ) { std::cout << "Discarded voxel coordinates will not be saved" << std::endl; } keepDiscarded = false; } if ( variableMap.count( "inputf" ) ) { if( !boost::filesystem::is_directory( boost::filesystem::path( inputFolder ) ) ) { std::cerr << "ERROR: input seed tractogram folder \"" <<inputFolder<< "\" is not a directory" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if( verbose ) { std::cout << "Input seed tractogram folder: " << inputFolder << std::endl; } } else { std::cerr << "ERROR: no input seed tractogram stated" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if ( variableMap.count( "outputf" ) ) { if( !boost::filesystem::is_directory( boost::filesystem::path( outputFolder ) ) ) { std::cerr << "ERROR: output folder \"" <<outputFolder<< "\" is not a directory" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if( verbose ) { std::cout << "Output folder: " << outputFolder << std::endl; } } else { std::cerr << "ERROR: no output folder stated" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if ( memory < 0.1 || memory > 50) { std::cerr << "ERROR: cache size must be a positive float between 0.1 and 50 (GB)" << std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } else if( verbose ) { std::cout << "Tractogram cache memory: " << memory << " GBytes" << std::endl; } std::string logFilename(outputFolder+"/"+progName+"_log.txt" ); std::ofstream logFile(logFilename.c_str() ); if(!logFile) { std::cerr << "ERROR: unable to open log file: \"" <<logFilename<< "\"" << std::endl; exit(-1); } logFile << "Start Time:\t" << ctime(&programStartTime) << std::endl; logFile << "Working directory:\t" << workingDir.string() << std::endl; logFile << "Verbose:\t" << verbose << std::endl; logFile << "Processors used:\t" << threads << std::endl; if( niftiMode ) { logFile << "Using nifti file format" << std::endl; } else { logFile << "Using vista file format" << std::endl; } logFile << "Vista mode flag:\t" << verbose << std::endl; logFile << "Roi file:\t" << roiFilename << std::endl; logFile << "Max nb distance:\t" << maxNbDist << std::endl; logFile << "Nbhood restriction level:\t" <<nbLevel<< std::endl; switch(growType) { case TC_GROWOFF: logFile << "Region growing: None" << std::endl; break; case TC_GROWSIZE: logFile << "Region growing: Size: " << baseSize << std::endl; break; case TC_GROWNUM: logFile << "Region growing: Number: " << baseSize << std::endl; break; } logFile << "Input seed tract folder:\t" << inputFolder << std::endl; logFile << "Output folder:\t" << outputFolder << std::endl; logFile << "Memory cache size:\t" << memory << " GB" << std::endl; logFile << "Debug outputr:\t" << debug << std::endl; logFile << "-------------" << std::endl; ///////////////////////////////////////////////////////////////// randCnbTreeBuilder builder( roiFilename, verbose ); logFile << "Roi size:\t" << builder.roiSize() << std::endl; builder.log( &logFile ); builder.setInputFolder( inputFolder ); builder.setOutputFolder( outputFolder ); builder.setDebugOutput( debug ); builder.buildRandCentroid( nbLevel, memory, growType, baseSize, keepDiscarded ); ///////////////////////////////////////////////////////////////// // save and print total time time_t programEndTime(time(NULL) ); int totalTime( difftime(programEndTime,programStartTime) ); std::cout << "Program Finished, total time: " << totalTime/3600 << "h " << (totalTime%3600)/60 << "' " << ((totalTime%3600)%60) << "\" " << std::endl; logFile << "-------------" << std::endl; logFile << "Finish Time:\t" << ctime(&programEndTime) << std::endl; logFile << "Elapsed time : " << totalTime/3600 << "h " << (totalTime%3600)/60 << "' " << ((totalTime%3600)%60) << "\"" << std::endl; // create file that indicates process was finished successfully std::string successFilename(outputFolder+"/success.txt" ); std::ofstream successFile(successFilename.c_str() ); if(!successFile) { std::cerr << "ERROR: unable to create success file: \"" <<successFile<< "\"" << std::endl; exit(-1); } successFile << "success"; // } // catch(std::exception& e) // { // std::cout << e.what() << std::endl; // return 1; // } return 0; }
int main( int argc, char *argv[] ) { // try { time_t programStartTime(time(NULL)); boost::filesystem::path workingDir( boost::filesystem::current_path()); // ========== PROGRAM PARAMETERS ========== std::string progName("partitiontree"); std::string configFilename("../../config/"+progName+".cfg"); unsigned int threads(0), levelDepth(3), filterRadius(0); bool verbose(false), niftiMode( true ); // program parameters std::string treeFilename, outputFolder; // Declare a group of options that will be allowed only on command line boost::program_options::options_description genericOptions("Generic options"); genericOptions.add_options() ( "version", "Program version" ) ( "help,h", "Produce extended program help message" ) ( "tree,t", boost::program_options::value< std::string >(&treeFilename), "file with the tree to compute partitions from") ( "outputf,O", boost::program_options::value< std::string >(&outputFolder), "output folder where partition files will be written") ( "search-depth,d", boost::program_options::value< unsigned int >(&levelDepth)->implicit_value(3), "[opt] optimal partition search depth (default = 3)") ( "filter-radius,r", boost::program_options::value< unsigned int >(&filterRadius)->implicit_value(0), "[opt] output partition filter kernel radius (default = 0 | no filtering)") ( "hoz", "[opt] obtain horizontal cut partitions (instead of Spread-Separation ones)") ( "maxgran,m", "[opt] obtain only the maximum granularity partition") ; // Declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description configOptions("Configuration"); configOptions.add_options() ( "verbose,v", "[opt] verbose output." ) ( "vista", "[opt] use vista file format (default is nifti)." ) ( "pthreads,p", boost::program_options::value< unsigned int >(&threads), "[opt] number of processing threads to run the program in parallel, default: all available") ; // Hidden options, will be allowed both on command line and in config file, but will not be shown to the user. boost::program_options::options_description hiddenOptions("Hidden options"); //hiddenOptions.add_options() ; boost::program_options::options_description cmdlineOptions; cmdlineOptions.add(genericOptions).add(configOptions).add(hiddenOptions); boost::program_options::options_description configFileOptions; configFileOptions.add(configOptions).add(hiddenOptions); boost::program_options::options_description visibleOptions("Allowed options"); visibleOptions.add(genericOptions).add(configOptions); boost::program_options::positional_options_description posOpt; //this arguments do not need to specify the option descriptor when typed in //posOpt.add("roi-file", -1); boost::program_options::variables_map variableMap; store(boost::program_options::command_line_parser(argc, argv).options(cmdlineOptions).positional(posOpt).run(), variableMap); std::ifstream ifs(configFilename.c_str()); store(parse_config_file(ifs, configFileOptions), variableMap); notify(variableMap); if (variableMap.count("help")) { std::cout << "---------------------------------------------------------------------------" << std::endl; std::cout << std::endl; std::cout << " Project: hClustering" << std::endl; std::cout << std::endl; std::cout << " Whole-Brain Connectivity-Based Hierarchical Parcellation Project" << std::endl; std::cout << " David Moreno-Dominguez" << std::endl; std::cout << " [email protected]" << std::endl; std::cout << " [email protected]" << std::endl; std::cout << " www.cbs.mpg.de/~moreno" << std::endl; std::cout << std::endl; std::cout << " For more reference on the underlying algorithm and research they have been used for refer to:" << std::endl; std::cout << " - Moreno-Dominguez, D., Anwander, A., & Knösche, T. R. (2014)." << std::endl; std::cout << " A hierarchical method for whole-brain connectivity-based parcellation." << std::endl; std::cout << " Human Brain Mapping, 35(10), 5000-5025. doi: http://dx.doi.org/10.1002/hbm.22528" << std::endl; std::cout << " - Moreno-Dominguez, D. (2014)." << std::endl; std::cout << " Whole-brain cortical parcellation: A hierarchical method based on dMRI tractography." << std::endl; std::cout << " PhD Thesis, Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig." << std::endl; std::cout << " ISBN 978-3-941504-45-5" << std::endl; std::cout << std::endl; std::cout << " hClustering is free software: you can redistribute it and/or modify" << std::endl; std::cout << " it under the terms of the GNU Lesser General Public License as published by" << std::endl; std::cout << " the Free Software Foundation, either version 3 of the License, or" << std::endl; std::cout << " (at your option) any later version." << std::endl; std::cout << " http://creativecommons.org/licenses/by-nc/3.0" << std::endl; std::cout << std::endl; std::cout << " hClustering is distributed in the hope that it will be useful," << std::endl; std::cout << " but WITHOUT ANY WARRANTY; without even the implied warranty of" << std::endl; std::cout << " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" << std::endl; std::cout << " GNU Lesser General Public License for more details." << std::endl; std::cout << std::endl; std::cout << "---------------------------------------------------------------------------" << std::endl << std::endl; std::cout << "partitiontree" << std::endl << std::endl; std::cout << "Obtain tree partitions at all granularity levels using the Spread-Separation method (finding the the partition with highest SS index at each granularity)." << std::endl; std::cout << " Optimal SS value for each partition is searched within a defined search-depth hierarchical levels. Final partitions can be filtered with a defined kernel size." << std::endl; std::cout << " to keep local SS maxima within that kernel. For SS index refer to (Moreno-Dominguez, 2014)" << std::endl; std::cout << " For an interactive 3D partition management with more options please use the Hierarchcial Clustering module developed in OpenWalnut (www.openwalnut.org)." << std::endl << std::endl; std::cout << "* Arguments:" << std::endl << std::endl; std::cout << " --version: Program version." << std::endl << std::endl; std::cout << " -h --help: produce extended program help message." << std::endl << std::endl; std::cout << " -t --tree: File with the hierarchical tree to extract partitions from." << std::endl << std::endl; std::cout << " -O --outputf: Output folder where partition files will be written." << std::endl << std::endl; std::cout << "[-d --search-depth]: Search optimal partition for each granularity within d hierarchical levels." << std::endl; std::cout << " A higher value will produce more optimized partition but will increase computing time." << std::endl; std::cout << " Default: 3. Recommendened values: 3 for good quality and fast computation, 4 for enhanced quality." << std::endl << std::endl; std::cout << "[-r --filter-radius]: Filter output partitions to keep only local SS (partition quality) maxima" << std::endl; std::cout << " within a r-sized kernel across the granularity dimension." << std::endl << std::endl; std::cout << "[-h --hoz]: Write horizontal cut partitions instead of SS ones (optimal partition search is still based on SS index)." << std::endl << std::endl; std::cout << "[-m --maxgran]: Compute and write only the maximum granularity (meta-leaves) partition." << std::endl << std::endl; std::cout << "[-v --verbose]: verbose output (recommended)." << std::endl << std::endl; std::cout << "[--vista]: write output tree in vista coordinates (default is nifti)." << std::endl << std::endl; std::cout << "[-p --pthreads]: number of processing threads to run the program in parallel. Default: use all available processors." << std::endl << std::endl; std::cout << std::endl; std::cout << "* Usage example:" << std::endl << std::endl; std::cout << " partitiontree -t tree_lh.txt -O results/ -d 3 -r 50 -v" << std::endl << std::endl; std::cout << std::endl; std::cout << "* Outputs (in output folder defined at option -O):" << std::endl << std::endl; std::cout << " (default outputs)" << std::endl; std::cout << " - 'allSSparts_dX.txt' - (where X is the search depth level defined at parameter -d) Contains a summary of the partition information (cut value and size) for all granularities." << std::endl; std::cout << " - 'TREE_SSparts_dX.txt' - (where TREE is the filename of the input tree defined at parameter -t) contains a copy of the original tree file with the partitions at all granularities included in the relevant fields." << std::endl; std::cout << " - 'partitiontree_log.txt' - A text log file containing the parameter details and in-run and completion information of the program." << std::endl; std::cout << std::endl; std::cout << " (additional if using option -r)" << std::endl; std::cout << " - 'filtSSparts_dX_rY.txt' - (where Y is the filter radius defined at parameter -r) Contains a summary of the resulting filtered partitions." << std::endl; std::cout << " - 'TREE_SSparts_dX_rY.txt' - contains a copy of the original tree file with the resulting filtered partitions included in the relevant fields." << std::endl; std::cout << std::endl; std::cout << " (when using --hoz option, the prefix 'SS' will be replaced by 'Hoz'')" << std::endl; std::cout << std::endl; std::cout << " (alternative outputs when using option --maxgran)" << std::endl; std::cout << " - 'fmaxgranPart.txt' - Contains the size information of the resulting maximal granularity partition for that tree." << std::endl; std::cout << " - 'TREE_maxgranPart.txt' - contains a copy of the original tree file with the resulting max granularity partition included in the relevant fields." << std::endl; std::cout << std::endl; exit(0); } if (variableMap.count("version")) { std::cout << progName <<", version 2.0"<<std::endl; exit(0); } if (variableMap.count("verbose")) { std::cout << "verbose output"<<std::endl; verbose=true; } if (variableMap.count("pthreads")) { if (threads==1) { std::cout <<"Using a single processor"<< std::endl; } else if(threads==0 || threads>=omp_get_num_procs()) { threads = omp_get_num_procs(); std::cout <<"Using all available processors ("<< threads <<")." << std::endl; } else { std::cout <<"Using a maximum of "<< threads <<" processors "<< std::endl; } omp_set_num_threads( threads ); } else { threads = omp_get_num_procs(); omp_set_num_threads( threads ); std::cout <<"Using all available processors ("<< threads <<")." << std::endl; } if ( variableMap.count( "vista" ) ) { if( verbose ) { std::cout << "Using vista format" << std::endl; } fileManagerFactory fmf; fmf.setVista(); niftiMode = false; } else { if( verbose ) { std::cout << "Using nifti format" << std::endl; } fileManagerFactory fmf; fmf.setNifti(); niftiMode = true; } if (variableMap.count("tree")) { if(!boost::filesystem::is_regular_file(boost::filesystem::path(treeFilename))) { std::cerr << "ERROR: tree file \""<<treeFilename<<"\" is not a regular file"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } std::cout << "Roi voxels file: "<< treeFilename << std::endl; } else { std::cerr << "ERROR: no tree file stated"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if (variableMap.count("outputf")) { if(!boost::filesystem::is_directory(boost::filesystem::path(outputFolder))) { std::cerr << "ERROR: output folder \""<<outputFolder<<"\" is not a directory"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } std::cout << "Output folder: "<< outputFolder << std::endl; } else { std::cerr << "ERROR: no output folder stated"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if (variableMap.count("maxgran")) { std::cout<<"Obtaining only max. granularity partition..."<<std::endl; WHtree tree(treeFilename); std::cout<<tree.getReport( false )<<std::endl; if( tree.testRootBaseNodes() ) { std::vector<size_t > maxpart( tree.getRootBaseNodes() ); std::vector<std::vector<size_t > > partitionVector( 1, maxpart); std::vector<float > partitionValues(1,0); std::cout<<"maxgranpart size: "<<std::endl<<maxpart.size()<<std::endl; WHtreePartition partitioner(&tree); std::string outPartFilename( outputFolder + "/maxgranPart.txt" ); partitioner.writePartitionSet( outPartFilename, partitionValues,partitionVector); tree.insertPartitions( partitionVector, partitionValues ); std::string outTreeFilename( outputFolder + "/" + tree.getName() + "_maxgranPart" ); outTreeFilename += ( ".txt" ); tree.writeTree( outTreeFilename, niftiMode ); return 0; } else { std::cout<<"ERROR: tree does not have a maximum granularity meta-leaf partition"<<std::endl; return(-1); } } if( levelDepth > 5 ) { std::cout << "Level depth indicated: " << levelDepth << " is too high, setting to a maximum of 5" << std::endl; levelDepth = 5; } std::cout << "Using a search depth of: " << levelDepth << std::endl; if( filterRadius > 1000 ) { std::cout << "filter radius indicated: " << filterRadius << " is too high (max is 1000), setting to 100" << std::endl; filterRadius = 10; } if( filterRadius == 0 ) { std::cout << "using no filtering (radius 0)" << std::endl; } else if( filterRadius < 0 ) { std::cout << "filter radius indicated: " << filterRadius << " must be positive. using no filtering (radius 0)" << std::endl; filterRadius = 0; } else { std::cout << "Using a filter radius of: " << filterRadius << std::endl; } ///////////////////////////////////////////////////////////////// std::string logFilename(outputFolder+"/"+progName+"_log.txt"); std::ofstream logFile(logFilename.c_str()); if(!logFile) { std::cerr << "ERROR: unable to open log file: \""<<logFilename<<"\""<<std::endl; exit(-1); } logFile <<"Start Time:\t"<< ctime(&programStartTime) <<std::endl; logFile <<"Working directory:\t"<< workingDir.string() <<std::endl; logFile <<"Verbose:\t"<< verbose <<std::endl; logFile <<"Tree file:\t"<< treeFilename <<std::endl; logFile <<"Output folder:\t"<< outputFolder <<std::endl; logFile <<"Verbose:\t"<< verbose <<std::endl; if( niftiMode ) { logFile << "Using nifti file format" << std::endl; } else { logFile << "Using vista file format" << std::endl; } WHtree tree(treeFilename); logFile << tree.getReport( false ) <<std::endl; std::cout<<tree.getReport( false )<<std::endl; std::vector< float > partitionValues; std::vector< std::vector< size_t> > partitionVector; WHtreePartition treePartition(&tree); std::string prefix; if (variableMap.count("hoz")) { prefix = "Hoz"; std::cout <<"getting hoz partitions at all levels..." <<std::endl; treePartition.scanHozPartitions( &partitionValues, &partitionVector ); std::cout << partitionValues.size() << " Partitions obtained, writing to file..." <<std::endl; logFile <<"Initial partitions:\t"<< partitionValues.size() <<std::endl; std::string outPartFilename( outputFolder + "/all" + prefix + "parts.txt" ); treePartition.writePartitionSet( outPartFilename, partitionValues, partitionVector); tree.insertPartitions( partitionVector, partitionValues ); std::string outTreeFilename( outputFolder + "/" + tree.getName() + "_" + prefix + "parts_d" + boost::lexical_cast<std::string>(levelDepth) ); outTreeFilename += ( ".txt" ); tree.writeTree( outTreeFilename, niftiMode ); } else { prefix = "SS"; std::cout <<"getting SS partitions at all levels..." <<std::endl; treePartition.scanOptimalPartitions( levelDepth, &partitionValues, &partitionVector ); std::cout << partitionValues.size() << " Partitions obtained, writing to file..." <<std::endl; logFile <<"Initial partitions:\t"<< partitionValues.size() <<std::endl; std::string outPartFilename( outputFolder + "/all" + prefix + "parts_d" + boost::lexical_cast<std::string>(levelDepth) + ".txt" ); treePartition.writePartitionSet( outPartFilename, partitionValues, partitionVector); tree.insertPartitions( partitionVector, partitionValues ); std::string outTreeFilename( outputFolder + "/" + tree.getName() + "_" + prefix + "parts_d" + boost::lexical_cast<std::string>(levelDepth) ); outTreeFilename += ( ".txt" ); tree.writeTree( outTreeFilename, niftiMode ); } std::vector < unsigned int > filterRadii; //filterRadii.reserve( 6 ); // filterRadii.push_back( 1 ); // filterRadii.push_back( 2 ); // filterRadii.push_back( 5 ); // filterRadii.push_back( 10 ); // filterRadii.push_back( 15 ); // filterRadii.push_back( 20 ); filterRadii.push_back( filterRadius ); for(size_t i=0; i< filterRadii.size(); ++i) { if( filterRadii[i] <= 0 ) { continue; } std::vector< float > filtPartValues( partitionValues ); std::vector< std::vector< size_t> > filtPartVector( partitionVector ); std::cout << "Filtering with a radius of "<< filterRadii[i] << "..." <<std::endl; treePartition.filterMaxPartitions( filterRadii[i], &filtPartValues, &filtPartVector ); std::cout << filtPartValues.size() << " Filtered partitions obtained, writing to file..." <<std::endl; logFile <<"Filtered partitions:\t"<< filtPartValues.size() <<std::endl; std::string outPartFilename( outputFolder + "/filt" + prefix + "parts_d" + boost::lexical_cast<std::string>(levelDepth) ); outPartFilename += ( "_r" + boost::lexical_cast<std::string>(filterRadii[i]) + ".txt" ); treePartition.writePartitionSet(outPartFilename, filtPartValues, filtPartVector); std::cout << "Adding filtered partitions to tree and writing..." <<std::endl; std::string outTreeFilename( outputFolder + "/" + tree.getName() + "_" + prefix + "parts_d" + boost::lexical_cast<std::string>(levelDepth) ); outTreeFilename += ( "_r" + boost::lexical_cast<std::string>(filterRadii[i]) + ".txt" ); tree.insertPartitions( filtPartVector, filtPartValues ); tree.writeTree( outTreeFilename, niftiMode ); } ///////////////////////////////////////////////////////////////// // save and print total time time_t programEndTime(time(NULL)); int totalTime( difftime(programEndTime,programStartTime) ); std::cout <<"Program Finished, total time: "<< totalTime/3600 <<"h "<< (totalTime%3600)/60 <<"' "<< ((totalTime%3600)%60) <<"\" "<< std::endl; logFile <<"-------------"<<std::endl; logFile <<"Finish Time:\t"<< ctime(&programEndTime) <<std::endl; logFile <<"Elapsed time : "<< totalTime/3600 <<"h "<< (totalTime%3600)/60 <<"' "<< ((totalTime%3600)%60) <<"\""<< std::endl; // } // catch(std::exception& e) // { // std::cout << e.what() << std::endl; // return 1; // } return 0; }
void MainWindow::documentExport(void) { Canvas *currCanvas = canvas(); QString currFilename = currCanvas->filename(); currFilename.chop(4); if (currFilename.isEmpty()) { // Determine the working directory. QSettings settings; QString workingDir(QDir::homePath()); QVariant workingDirSetting = settings.value("workingDirectory"); if (workingDirSetting.isValid()) { workingDir = workingDirSetting.toString(); } currFilename = workingDir + "/untitled"; } QString filename = QFileDialog::getSaveFileName(this, tr("Export Diagram"), currFilename, tr("SVG (*.svg);;PDF (*.pdf);;Postscript (*.ps)")); if (filename.isEmpty()) { return; } QRectF pageRect = currCanvas->pageRect(); if (pageRect.size().isEmpty()) { // There is no page set, so use a page equal to diagram bounds double padding = 10; pageRect = expandRect(diagramBoundingRect(currCanvas->items()), padding); } QFileInfo file(filename); if (file.suffix() == "svg") { QSvgGenerator generator; generator.setFileName(filename); QRectF targetRect(QPointF(0, 0), currCanvas->sceneRect().size()); QPointF topLeft = pageRect.topLeft() - currCanvas->sceneRect().topLeft(); QRectF viewbox(topLeft, pageRect.size()); generator.setSize(viewbox.size().toSize()); generator.setViewBox(viewbox); generator.setTitle(QFileInfo(filename).fileName()); generator.setDescription(tr("This file was exported from Dunnart. " "http://www.dunnart.org/")); QPainter painter; if (painter.begin(&generator)) { painter.setRenderHint(QPainter::Antialiasing); currCanvas->setRenderingForPrinting(true); currCanvas->render(&painter, targetRect, currCanvas->sceneRect(), Qt::IgnoreAspectRatio); currCanvas->setRenderingForPrinting(false); painter.end(); } else { qDebug("Export SVG painter failed to begin."); } } else { // Use QPrinter for PDF and PS. QPrinter printer; printer.setOutputFileName(filename); printer.setPaperSize(pageRect.size(), QPrinter::Millimeter); QPainter painter; if (painter.begin(&printer)) { painter.setRenderHint(QPainter::Antialiasing); currCanvas->setRenderingForPrinting(true); currCanvas->render(&painter, QRectF(), expandRect(pageRect, -3), Qt::IgnoreAspectRatio); currCanvas->setRenderingForPrinting(false); } else { qDebug("Export PDF/PS painter failed to begin."); } } }
int main( int argc, char *argv[] ) { // try { time_t programStartTime(time(NULL)); boost::filesystem::path workingDir( boost::filesystem::current_path()); // ========== PROGRAM PARAMETERS ========== std::string progName("matchpartition"); std::string configFilename("../../config/"+progName+".cfg"); // program parameters std::string refTreeFilename, targetTreeFilename, matchTableFilename, outputFolder; unsigned int searchDepth(1); float lambda(0); bool signaturePart(false), colorMatching(false), overlapPart(false), exclusive(false); bool verbose(false), niftiMode( true ); // Declare a group of options that will be allowed only on command line boost::program_options::options_description genericOptions("Generic options"); genericOptions.add_options() ( "version", "Program version" ) ( "help,h", "Produce extended program help message" ) ( "reference,r", boost::program_options::value< std::string >(&refTreeFilename), "file with reference partitioned tree" ) ( "target,t", boost::program_options::value< std::string >(&targetTreeFilename), "file with target tree to be partitioned-matched" ) ( "leafmatch,m", boost::program_options::value< std::string >(&matchTableFilename), "file with meta-leaves (base-nodes) matching table" ) ( "outputf,O", boost::program_options::value< std::string >(&outputFolder), "output folder where partition-matched trees will be written" ) ( "signature,s", boost::program_options::value< float >(&lambda), "[xor with -o and -c] Signature-based partition matching, inster lambda coefficient value" ) ( "overlap,o", "[xor with -s and -c] Meta-leaf overlap-based partition matching") ( "depth,d", boost::program_options::value< unsigned int >(&searchDepth)->implicit_value(0), "[opt] partition search depth. Default: 0 (automatic partition-size based adaptive depth, recommended)") ( "justcolor,c", "[xor with -s and -o] Perform only olor matching (requires pre-computed partitions in both trees)") ( "excl,x", "[opt] color exclusively clusters that have a match, clusters without match will be white") ; // Declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description configOptions("Configuration"); configOptions.add_options() ( "verbose,v", "[opt] verbose output." ) ( "vista", "[opt] Write output tree in vista coordinates (default is nifti)." ) ; // Hidden options, will be allowed both on command line and in config file, but will not be shown to the user. boost::program_options::options_description hiddenOptions("Hidden options"); //hiddenOptions.add_options() ; boost::program_options::options_description cmdlineOptions; cmdlineOptions.add(genericOptions).add(configOptions).add(hiddenOptions); boost::program_options::options_description configFileOptions; configFileOptions.add(configOptions).add(hiddenOptions); boost::program_options::options_description visibleOptions("Allowed options"); visibleOptions.add(genericOptions).add(configOptions); boost::program_options::positional_options_description posOpt; //this arguments do not need to specify the option descriptor when typed in //posOpt.add("roi-file", -1); boost::program_options::variables_map variableMap; store(boost::program_options::command_line_parser(argc, argv).options(cmdlineOptions).positional(posOpt).run(), variableMap); std::ifstream ifs(configFilename.c_str()); store(parse_config_file(ifs, configFileOptions), variableMap); notify(variableMap); if (variableMap.count( "help" ) ) { std::cout << "---------------------------------------------------------------------------" << std::endl; std::cout << std::endl; std::cout << " Project: hClustering" << std::endl; std::cout << std::endl; std::cout << " Whole-Brain Connectivity-Based Hierarchical Parcellation Project" << std::endl; std::cout << " David Moreno-Dominguez" << std::endl; std::cout << " [email protected]" << std::endl; std::cout << " [email protected]" << std::endl; std::cout << " www.cbs.mpg.de/~moreno" << std::endl; std::cout << std::endl; std::cout << " For more reference on the underlying algorithm and research they have been used for refer to:" << std::endl; std::cout << " - Moreno-Dominguez, D., Anwander, A., & Knösche, T. R. (2014)." << std::endl; std::cout << " A hierarchical method for whole-brain connectivity-based parcellation." << std::endl; std::cout << " Human Brain Mapping, 35(10), 5000-5025. doi: http://dx.doi.org/10.1002/hbm.22528" << std::endl; std::cout << " - Moreno-Dominguez, D. (2014)." << std::endl; std::cout << " Whole-brain cortical parcellation: A hierarchical method based on dMRI tractography." << std::endl; std::cout << " PhD Thesis, Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig." << std::endl; std::cout << " ISBN 978-3-941504-45-5" << std::endl; std::cout << std::endl; std::cout << " hClustering is free software: you can redistribute it and/or modify" << std::endl; std::cout << " it under the terms of the GNU Lesser General Public License as published by" << std::endl; std::cout << " the Free Software Foundation, either version 3 of the License, or" << std::endl; std::cout << " (at your option) any later version." << std::endl; std::cout << " http://creativecommons.org/licenses/by-nc/3.0" << std::endl; std::cout << std::endl; std::cout << " hClustering is distributed in the hope that it will be useful," << std::endl; std::cout << " but WITHOUT ANY WARRANTY; without even the implied warranty of" << std::endl; std::cout << " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" << std::endl; std::cout << " GNU Lesser General Public License for more details." << std::endl; std::cout << std::endl; std::cout << "---------------------------------------------------------------------------" << std::endl << std::endl; std::cout << "matchpartition" << std::endl << std::endl; std::cout << "Finds the best matching corresponding partitions in a target tree to those present in an unrelated reference tree (meta-leaf matching across these two trees must have been precomputed using comparetrees)." << std::endl; std::cout << " Two partition matching algorithms are available: signature matching and overlap matching. Found target partitions will be color-matched as best as possible." << std::endl; std::cout << " There is also the possibility of only color-matching predefined partitions of the target tree to predefined partitions of the reference tree." << std::endl << std::endl; std::cout << "* Arguments:" << std::endl << std::endl; std::cout << " --version: Program version." << std::endl << std::endl; std::cout << " -h --help: produce extended program help message." << std::endl << std::endl; std::cout << " -r --reference: The tree file with the reference partitioned tree." << std::endl << std::endl; std::cout << " -t --target: The tree file with the target tree to find matching partitions in (or with partitions to be color-matched)." << std::endl << std::endl; std::cout << " -m --leafmatch File with the meta-leaf matching information across both trees (output of comparetrees command)." << std::endl << std::endl; std::cout << " -O --outputf: Output folder where partitioned/color matched tree files will be written." << std::endl << std::endl; std::cout << "[-s --signature]: Signature-based partition matching, instert lambda coefficient value. [xor with -o and -c]." << std::endl; std::cout << " In this method a pair signature matrices are computed for each reference-target partitions to find the quality of the match." << std::endl; std::cout << " Each signature matrix defines a value for each pair of base-nodes of the tree it belongs to: 1 the base nodes are found in the same cluster, 0 if otherwise." << std::endl; std::cout << " The higher the correlation between the reference and target-derived matrices, the best match is the target tree partition to the reference tree one." << std::endl; std::cout << " A smart hierarchical search through possible partritions is conducted to find the one with best signature matching." << std::endl; std::cout << " The lambda coefficient determines if and how a similar number of clusters in both partitions affects the matching quality value," << std::endl; std::cout << " Lambda=0 -> cluster number does not affect the quality value. Lambda=1 -> cluster value similarity has as much weight as singature correlation." << std::endl << std::endl; std::cout << "[-o --overlap]: Overlap-based partition matching. [xor with -o and -c]." << std::endl; std::cout << " A match between two partititionsis found by iteratively matching clusters with higher base-node overlap and resolving possible ambiguities." << std::endl; std::cout << " The matching quality between partitions is defined as the number of base-nodes pairs that are classified in the same way in both partitions" << std::endl; std::cout << " (both in the smae cluster r both in different clusters) against the total number of pair combinations." << std::endl; std::cout << " A smart hierarchical search through possible partritions is conducted to find the one with best signature matching." << std::endl << std::endl; std::cout << "[-d --depth]: Partition search depth (for signature and overlap matching. A higher value will mean a more exhaustive search of the possible partitions," << std::endl; std::cout << " but also a higher computation time, specially if the partition to be matched has a high number of clusters (>100)." << std::endl; std::cout << " The default value (0, recommended) will adaptively give high search depth to low-cluster partitions and lower search depth to high-cluster partittions." << std::endl << std::endl; std::cout << "[-c --justcolor]: Perform only color matching across reference and target tree parttitions (both trees need to have the same number of precompouted partitions)." << std::endl; std::cout << " In multiple-to-one matching cases clusters from the reference tree might also be recolored to better identify matching relationships across partitions." << std::endl << std::endl; std::cout << "[-x --excl]: Color exclusively clusters that have a match, clusters without match will be recolored white (on both reference and target trees)" << std::endl << std::endl; std::cout << "[-v --verbose]: Verbose output (recommended)." << std::endl << std::endl; std::cout << "[--vista]: Write output tree files in vista coordinates (default is nifti)." << std::endl << std::endl; std::cout << std::endl; std::cout << "* Usage example:" << std::endl << std::endl; std::cout << " matchpartition -r refTree.txt -t targetTree.txt -m matching.txt -O results/ -s 0.5 -v" << std::endl << std::endl; exit(0); } if (variableMap.count( "version" ) ) { std::cout << progName <<", version 2.0"<<std::endl; exit(0); } if ( variableMap.count( "verbose" ) ) { std::cout << "verbose output" << std::endl; verbose=true; } if ( variableMap.count( "vista" ) ) { if( verbose ) { std::cout << "Using vista coordinates" << std::endl; } fileManagerFactory fmf; fmf.setVista(); niftiMode = false; } else { if( verbose ) { std::cout << "Using nifti coordinates" << std::endl; } fileManagerFactory fmf; fmf.setNifti(); niftiMode = true; } if (variableMap.count("reference")) { if(!boost::filesystem::is_regular_file( boost::filesystem::path( refTreeFilename ) ) ) { std::cerr << "ERROR: reference tree file \""<<refTreeFilename<<"\" is not a regular file"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } std::cout << "Reference tree file: "<< refTreeFilename << std::endl; } else { std::cerr << "ERROR: no reference tree file stated"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if (variableMap.count( "target" ) ) { if(!boost::filesystem::is_regular_file(boost::filesystem::path( targetTreeFilename ) ) ) { std::cerr << "ERROR: target tree file \""<<targetTreeFilename<<"\" is not a regular file"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } std::cout << "Target tree file: "<< targetTreeFilename << std::endl; } else { std::cerr << "ERROR: no target tree file stated"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if (variableMap.count( "leafmatch" ) ) { if(!boost::filesystem::is_regular_file(boost::filesystem::path( matchTableFilename ) ) ) { std::cerr << "ERROR: match table file \""<<matchTableFilename<<"\" is not a regular file"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } std::cout << "Match table file: "<< matchTableFilename << std::endl; } else { std::cerr << "ERROR: no match Table file stated"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if( variableMap.count( "signature" ) + variableMap.count( "overlap" ) + variableMap.count( "justcolor" ) > 1 ) { std::cerr << "ERROR: multiple matching types selected, please use only one from -s, -o, -c."<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if (variableMap.count( "signature" ) ) { std::cout << "Performing Signature partition matching (and color matching)" << std::endl; std::cout <<" Using a lambda factor of "<< lambda << std::endl; signaturePart = true; colorMatching = true; } else if (variableMap.count( "overlap" ) ) { std::cout << "Performing Overlap partition matching (and color matching): " << std::endl; overlapPart = true; colorMatching = true; } else if (variableMap.count( "justcolor" ) ) { std::cout << "Performing only color matching: " << std::endl; colorMatching = true; } else { std::cerr << "ERROR: no matching type selected, select signature, overlap or color matching"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if (variableMap.count( "excl" ) ) { std::cout << "Color exclusively matched clusters (unmatched clusters will be white) " << std::endl; exclusive = true; } if( signaturePart || overlapPart ) { if( searchDepth > 5 ) { std::cout << "Level depth indicated: " << searchDepth << " is too high, setting to a maximum of 5" << std::endl; searchDepth = 5; } else if ( searchDepth = 0 ) { std::cout << "Using automatic parttion-size based adaptive search depth " << std::endl; } else { std::cout << "Using a search depth of: " << searchDepth << std::endl; } } if (variableMap.count( "outputf" ) ) { if(!boost::filesystem::is_directory(boost::filesystem::path( outputFolder ) ) ) { std::cerr << "ERROR: output folder \""<<outputFolder<<"\" is not a directory"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } std::cout << "Output folder: "<< outputFolder << std::endl; } else { std::cerr << "ERROR: no output folder stated"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } std::string logFilename(outputFolder+"/"+progName+"_log.txt"); std::ofstream logFile(logFilename.c_str()); if(!logFile) { std::cerr << "ERROR: unable to open log file: \""<<logFilename<<"\""<<std::endl; exit(-1); } logFile <<"Start Time:\t"<< ctime(&programStartTime) <<std::endl; logFile <<"Working directory:\t"<< workingDir.string() <<std::endl; logFile <<"Verbose:\t"<< verbose <<std::endl; logFile <<"Reference tree:\t"<< refTreeFilename <<std::endl; logFile <<"Target tree:\t"<< targetTreeFilename <<std::endl; logFile <<"Matching table:\t"<< matchTableFilename <<std::endl; logFile <<"Output folder:\t"<< outputFolder <<std::endl; if( niftiMode ) { logFile << "Using nifti coordinates" << std::endl; } else { logFile << "Using vista coordinates" << std::endl; } logFile <<"-------------"<<std::endl; ///////////////////////////////////////////////////////////////// WHtree refTree( refTreeFilename ); WHtree targetTree( targetTreeFilename ); if (!refTree.isLoaded() || !targetTree.isLoaded() ) { throw std::runtime_error ("ERROR @ compareTrees(): trees are not loaded"); } logFile <<"Reference Tree: "<< refTree.getReport(false) <<std::endl; logFile <<"Target Tree: "<< targetTree.getReport(false) <<std::endl; if (refTree.getDataSize() != targetTree.getDataSize() ) { std::cerr <<"Reference Tree: "<< refTree.getReport() <<std::endl; std::cerr <<"Target Tree: "<< targetTree.getReport() <<std::endl; throw std::runtime_error ("ERROR @ compareTrees() datasets have different dimensions"); } if (verbose) { std::cout <<"Reference Tree: "<< refTree.getReport(false) <<std::endl; std::cout <<"Target Tree: "<< targetTree.getReport(false) <<std::endl; } partitionMatcher matcher(&refTree,&targetTree,matchTableFilename, verbose); std::string depthString; if( searchDepth > 0 ) { depthString = "_d"+string_utils::toString< unsigned int >( searchDepth ) ; } std::cout <<matcher.reportBaseNodes()<<std::endl; std::string suffixPart("_pm_Signature_l" + string_utils::toString< float >( lambda ) + depthString + ".txt"); std::string suffixNew("_pm_Overlap" + depthString + ".txt"); std::string suffixColor("_colorMatch.txt"); bool refTreeColorsChanged( false ); if( signaturePart ) { logFile << "Signature Matching" << std::endl; logFile << "Lambda:\t" << lambda <<std::endl; logFile << "Search depth:\t" << searchDepth <<std::endl; matcher.findMatchingPartitions( lambda ); } else if ( overlapPart ) { logFile << "Overlap Matching" <<std::endl; logFile << "Search depth:\t" << searchDepth <<std::endl; matcher.findMatchingPartitions( -1 ); } if( colorMatching ) { logFile << "Color Matching" <<std::endl; refTreeColorsChanged = matcher.matchColors( exclusive ); } std::string refOutput; std::string targetOutput; if ( signaturePart ) { targetOutput = outputFolder + "/" + targetTree.getName() + suffixPart; } else if ( overlapPart ) { targetOutput = outputFolder + "/" + targetTree.getName() + suffixNew ; } else { targetOutput = outputFolder + "/" + targetTree.getName() + suffixColor; } if( refTreeColorsChanged ) { refOutput = outputFolder + "/" + refTree.getName() + suffixColor; } else { refOutput = outputFolder + "/" + refTree.getName() + ".txt"; } if( verbose ) { std::cout << "Writing output target tree file to " << targetOutput << std::endl; std::cout << "Writing output reference tree file to " << refOutput << std::endl; } targetTree.writeTree( targetOutput, niftiMode ); refTree.writeTree( refOutput, niftiMode ); logFile << "Written output target tree file to " << targetOutput << std::endl; logFile << "Written output reference tree file to " << refOutput << std::endl; ///////////////////////////////////////////////////////////////// // save and print total time time_t programEndTime( time( NULL ) ); int totalTime( difftime( programEndTime, programStartTime ) ); std::cout <<"Program Finished, total time: "<< totalTime/3600 <<"h "<< (totalTime%3600)/60 <<"' "<< ((totalTime%3600)%60) <<"\" "<< std::endl; logFile <<"-------------"<<std::endl; logFile <<"Finish Time:\t"<< ctime(&programEndTime) <<std::endl; logFile <<"Elapsed time : "<< totalTime/3600 <<"h "<< (totalTime%3600)/60 <<"' "<< ((totalTime%3600)%60) <<"\""<< std::endl; // } // catch(std::exception& e) // { // std::cout << e.what() << std::endl; // return 1; // } return 0; }
int main( int argc, char *argv[] ) { // try { time_t programStartTime(time(NULL)); boost::filesystem::path workingDir( boost::filesystem::current_path()); // ========== PROGRAM PARAMETERS ========== std::string progName("cpcc"); std::string configFilename("../../config/"+progName+".cfg"); // program parameters std::string treeFilename; std::string distMatrixFolder; unsigned int threads(0); bool niftiMode( true ); bool verbose(false); // Declare a group of options that will be allowed only on command line boost::program_options::options_description genericOptions("Generic options"); genericOptions.add_options() ( "version", "Program version" ) ( "help,h", "Produce extended program help message" ) ( "tree,t", boost::program_options::value< std::string >(&treeFilename), "file with the hierarchical tree to compute the cpcc value from") ( "inputf,I", boost::program_options::value< std::string >(&distMatrixFolder), "Input data folder with the distance matrix files.") ; // Declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description configOptions("Configuration"); configOptions.add_options() ( "verbose,v", "[opt] verbose output." ) ( "vista", "[opt] use vista file format (default is nifti)." ) ( "pthreads,p", boost::program_options::value< unsigned int >(&threads), "[opt] number of processing cores to run the program in. Default: all available." ) ; // Hidden options, will be allowed both on command line and in config file, but will not be shown to the user. boost::program_options::options_description hiddenOptions("Hidden options"); //hiddenOptions.add_options() ; boost::program_options::options_description cmdlineOptions; cmdlineOptions.add(genericOptions).add(configOptions).add(hiddenOptions); boost::program_options::options_description configFileOptions; configFileOptions.add(configOptions).add(hiddenOptions); boost::program_options::options_description visibleOptions("Allowed options"); visibleOptions.add(genericOptions).add(configOptions); boost::program_options::positional_options_description posOpt; //this arguments do not need to specify the option descriptor when typed in posOpt.add("tree", -1); boost::program_options::variables_map variableMap; store(boost::program_options::command_line_parser(argc, argv).options(cmdlineOptions).positional(posOpt).run(), variableMap); std::ifstream ifs(configFilename.c_str()); store(parse_config_file(ifs, configFileOptions), variableMap); notify(variableMap); if (variableMap.count("help")) { std::cout << "---------------------------------------------------------------------------" << std::endl; std::cout << std::endl; std::cout << " Project: hClustering" << std::endl; std::cout << std::endl; std::cout << " Whole-Brain Connectivity-Based Hierarchical Parcellation Project" << std::endl; std::cout << " David Moreno-Dominguez" << std::endl; std::cout << " [email protected]" << std::endl; std::cout << " [email protected]" << std::endl; std::cout << " www.cbs.mpg.de/~moreno" << std::endl; std::cout << std::endl; std::cout << " For more reference on the underlying algorithm and research they have been used for refer to:" << std::endl; std::cout << " - Moreno-Dominguez, D., Anwander, A., & Knösche, T. R. (2014)." << std::endl; std::cout << " A hierarchical method for whole-brain connectivity-based parcellation." << std::endl; std::cout << " Human Brain Mapping, 35(10), 5000-5025. doi: http://dx.doi.org/10.1002/hbm.22528" << std::endl; std::cout << " - Moreno-Dominguez, D. (2014)." << std::endl; std::cout << " Whole-brain cortical parcellation: A hierarchical method based on dMRI tractography." << std::endl; std::cout << " PhD Thesis, Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig." << std::endl; std::cout << " ISBN 978-3-941504-45-5" << std::endl; std::cout << std::endl; std::cout << " hClustering is free software: you can redistribute it and/or modify" << std::endl; std::cout << " it under the terms of the GNU Lesser General Public License as published by" << std::endl; std::cout << " the Free Software Foundation, either version 3 of the License, or" << std::endl; std::cout << " (at your option) any later version." << std::endl; std::cout << " http://creativecommons.org/licenses/by-nc/3.0" << std::endl; std::cout << std::endl; std::cout << " hClustering is distributed in the hope that it will be useful," << std::endl; std::cout << " but WITHOUT ANY WARRANTY; without even the implied warranty of" << std::endl; std::cout << " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" << std::endl; std::cout << " GNU Lesser General Public License for more details." << std::endl; std::cout << std::endl; std::cout << "---------------------------------------------------------------------------" << std::endl << std::endl; std::cout << "cpcc" << std::endl << std::endl; std::cout << "Compute the cophenetic correlation coefficient (Farris, 1969) of a hierarchical tree." << std::endl << std::endl; std::cout << "* Arguments:" << std::endl << std::endl; std::cout << " --version: Program version." << std::endl << std::endl; std::cout << " -h --help: produce extended program help message." << std::endl << std::endl; std::cout << " -t --tree: File with the hierarchical tree to compute cpcc from." << std::endl << std::endl; std::cout << " -I --inputf: Input data folder containing the blocks of the precomputed tract pairwise distance matrix." << std::endl << std::endl; std::cout << "[-v --verbose]: verbose output (recommended)." << std::endl << std::endl; std::cout << "[--vista]: read/write vista (.v) files [default is nifti (.nii) and compact (.cmpct) files]." << std::endl << std::endl; std::cout << "[-p --pthreads]: number of processing threads to run the program in parallel. Default: use all available processors." << std::endl << std::endl; std::cout << std::endl; std::cout << "* Usage example:" << std::endl << std::endl; std::cout << " cpcc -t tree_lh.txt -I distBlocks/ -v" << std::endl << std::endl; std::cout << std::endl; std::cout << "* Outputs:" << std::endl << std::endl; std::cout << " - Introduces the cpcc value in the #cpcc field of the tree file defined at option -t." << std::endl; std::cout << std::endl; exit(0); } if (variableMap.count("version")) { std::cout << progName <<", version 2.0"<<std::endl; exit(0); } if (variableMap.count("verbose")) { std::cout << "verbose output"<<std::endl; verbose=true; } if (variableMap.count("pthreads")) { if (threads==1) { std::cout <<"Using a single processor"<< std::endl; } else if(threads==0 || threads>=omp_get_max_threads()) { threads = omp_get_max_threads(); std::cout <<"Using all available processors ("<< threads <<")." << std::endl; } else { std::cout <<"Using a maximum of "<< threads <<" processors "<< std::endl; } omp_set_num_threads( threads ); } else { threads = omp_get_max_threads(); omp_set_num_threads( threads ); std::cout <<"Using all available processors ("<< threads <<")." << std::endl; } if (variableMap.count("tree")) { if(!boost::filesystem::is_regular_file(boost::filesystem::path(treeFilename))) { std::cerr << "ERROR: tree file \""<<treeFilename<<"\" is not a regular file"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } std::cout << "Input tree file: "<< treeFilename << std::endl; } else { std::cerr << "ERROR: no tree file stated"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if (variableMap.count("inputf")) { if(!boost::filesystem::is_directory(boost::filesystem::path(distMatrixFolder))) { std::cerr << "ERROR: distance matrix folder \""<<distMatrixFolder<<"\" is not a directory"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } std::cout << "Distance matrix folder: "<< distMatrixFolder << std::endl; } else { std::cerr << "ERROR: no distance matrix folder stated"<<std::endl; std::cerr << visibleOptions << std::endl; exit(-1); } if ( variableMap.count( "vista" ) ) { if( verbose ) { std::cout << "Using vista format" << std::endl; } fileManagerFactory fmf; fmf.setVista(); niftiMode = false; } else { if( verbose ) { std::cout << "Using nifti format" << std::endl; } fileManagerFactory fmf; fmf.setNifti(); niftiMode = true; } ///////////////////////////////////////////////////////////////// WHtree tree(treeFilename); if (verbose) { std::cout<<tree.getReport()<<std::endl; } if( !tree.isLoaded() ) { std::cerr << "Error while loading tree "<< std::endl; exit(-1); } treeManager treeMngr(&tree, verbose); treeMngr.setDistMatrixFolder(distMatrixFolder); float cpcc(treeMngr.doCpcc()); tree.writeTree(treeFilename,niftiMode); std::cout<<std::endl<<std::endl<<"CPCC: "<< cpcc <<std::endl<<std::endl; ///////////////////////////////////////////////////////////////// // save and print total time time_t programEndTime(time(NULL)); int totalTime( difftime(programEndTime,programStartTime) ); std::cout << "Program Finished, total time: " << totalTime/3600 <<"h "<< (totalTime%3600)/60 <<"' "<< ((totalTime%3600)%60) <<"\""<< std::endl; // } // catch(std::exception& e) // { // std::cout << e.what() << std::endl; // return 1; // } return 0; }
JobResult PythonJob::exec() { // We assume m_scriptFile to be relative to m_workingPath. QDir workingDir( m_workingPath ); if ( !workingDir.exists() || !workingDir.isReadable() ) { return JobResult::error( tr( "Bad working directory path" ), tr( "Working directory %1 for python job %2 is not readable." ) .arg( m_workingPath ) .arg( prettyName() ) ); } QFileInfo scriptFI( workingDir.absoluteFilePath( m_scriptFile ) ); if ( !scriptFI.exists() || !scriptFI.isFile() || !scriptFI.isReadable() ) { return JobResult::error( tr( "Bad main script file" ), tr( "Main script file %1 for python job %2 is not readable." ) .arg( scriptFI.absoluteFilePath() ) .arg( prettyName() ) ); } try { bp::dict scriptNamespace = helper()->createCleanNamespace(); bp::object calamaresModule = bp::import( "libcalamares" ); bp::dict calamaresNamespace = bp::extract< bp::dict >( calamaresModule.attr( "__dict__" ) ); calamaresNamespace[ "job" ] = CalamaresPython::PythonJobInterface( this ); calamaresNamespace[ "globalstorage" ] = CalamaresPython::GlobalStoragePythonWrapper( JobQueue::instance()->globalStorage() ); bp::object execResult = bp::exec_file( scriptFI.absoluteFilePath().toLocal8Bit().data(), scriptNamespace, scriptNamespace ); bp::object entryPoint = scriptNamespace[ "run" ]; bp::object prettyNameFunc = scriptNamespace.get("pretty_name", bp::object()); cDebug() << "Job file" << scriptFI.absoluteFilePath(); if ( !prettyNameFunc.is_none() ) { bp::extract< std::string > prettyNameResult( prettyNameFunc() ); if ( prettyNameResult.check() ) { m_description = QString::fromStdString( prettyNameResult() ).trimmed(); } if ( !m_description.isEmpty() ) { cDebug() << "Job description from pretty_name" << prettyName() << "=" << m_description; emit progress( 0 ); } } if ( m_description.isEmpty() ) { bp::extract< std::string > entryPoint_doc_attr(entryPoint.attr( "__doc__" ) ); if ( entryPoint_doc_attr.check() ) { m_description = QString::fromStdString( entryPoint_doc_attr() ).trimmed(); auto i_newline = m_description.indexOf('\n'); if ( i_newline > 0 ) m_description.truncate( i_newline ); cDebug() << "Job description from __doc__" << prettyName() << "=" << m_description; emit progress( 0 ); } } bp::object runResult = entryPoint(); if ( runResult.is_none() ) { return JobResult::ok(); } else // Something happened in the Python job { bp::tuple resultTuple = bp::extract< bp::tuple >( runResult ); QString message = QString::fromStdString( bp::extract< std::string >( resultTuple[ 0 ] ) ); QString description = QString::fromStdString( bp::extract< std::string >( resultTuple[ 1 ] ) ); return JobResult::error( message, description ); } } catch ( bp::error_already_set ) { QString msg; if ( PyErr_Occurred() ) { msg = helper()->handleLastError(); } bp::handle_exception(); PyErr_Clear(); return JobResult::internalError( tr( "Boost.Python error in job \"%1\"." ).arg( prettyName() ), msg, JobResult::PythonUncaughtException ); } }
void ClientApp::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) { /** N.B. this code is poor and needs tidying up **/ CefRefPtr<CefCommandLine> commandLine = AppGetCommandLine(); #if defined(OS_WIN) FilePath workingDir(commandLine->GetProgram().ToWString().c_str()); FilePath bootPath = workingDir.DirName().Append(L"webinosBoot.js"); #else FilePath workingDir(commandLine->GetProgram()); FilePath bootPath = workingDir.DirName().Append("webinosBoot.js"); #endif int64 bootDataSize; if (file_util::GetFileSize(bootPath, &bootDataSize)) { char* bootData = new char[bootDataSize+1]; file_util::ReadFile(bootPath, bootData, bootDataSize); bootData[bootDataSize] = 0; std::string widgetInterface; webinos::WidgetConfig cfg; if (cfg.LoadFromURL(frame->GetURL())) { std::string widgetArgs; AppGetWidgetArgs(cfg.GetSessionId(),widgetArgs); /* We need to expose the w3c widget interface (http://www.w3.org/TR/widgets-apis/) interface Widget { readonly attribute DOMString author; readonly attribute DOMString description; readonly attribute DOMString name; readonly attribute DOMString shortName; readonly attribute DOMString version; readonly attribute DOMString id; readonly attribute DOMString authorEmail; readonly attribute DOMString authorHref; readonly attribute WidgetStorage preferences; <!-- TBD! readonly attribute unsigned long height; readonly attribute unsigned long width; }; */ std::stringstream wifStr(std::stringstream::in | std::stringstream::out); wifStr << "\ // Widget interface\r\n\ window.widget = { \r\n\ author: \"" << cfg.author() << "\",\r\n\ description: \"" << cfg.description() << "\",\r\n\ name: \"" << cfg.name() << "\",\r\n\ shortName: \"" << cfg.shortName() << "\",\r\n\ version: \"" << cfg.version() << "\",\r\n\ id: \"" << cfg.id() << "\",\r\n\ authorEmail: \"" << cfg.authorEmail() << "\",\r\n\ authorHref: \"" << cfg.authorHref() << "\",\r\n\ preferences: {},\r\n\
bool hasRequiredProperties() const { return !project().empty() && !workingDir().empty(); }