STLoaderConfiguration::STLoaderConfiguration()
        : WdbConfiguration("")
{
        configOptions().add( getOutput( output_ ) );
        configOptions().add( getStinfosys( stinfosys_ ) );
        configOptions().add( getLoading( loading_) );

        shownOptions().add( getOutput( output_ ) );
        shownOptions().add( getStinfosys( stinfosys_ ) );
        shownOptions().add( getLoading( loading_ ) );
}
void ServicesDbWriter::setConfiguration(const Settings &conf)
{
  ConfigOptions configOptions(conf);
  setUserEmail(configOptions.getServicesDbWriterEmail());
  setCreateUser(configOptions.getServicesDbWriterCreateUser());
  setOverwriteMap(configOptions.getServicesDbWriterOverwriteMap());
}
void ServicesDbReader::setConfiguration(const Settings& conf)
{
  ConfigOptions configOptions(conf);
  setMaxElementsPerMap(configOptions.getMaxElementsPerPartialMap());
  setUserEmail(configOptions.getServicesDbReaderEmail());
  setBoundingBox(configOptions.getConvertBoundingBox());
}
示例#4
0
void TagValueNumericRangeCriterion::setConfiguration(const Settings& conf)
{
  ConfigOptions configOptions(conf);
  _tagKeys = configOptions.getTagValueNumericRangeCriterionKeys();
  _rangeMin = configOptions.getTagValueNumericRangeCriterionMin();
  _rangeMax = configOptions.getTagValueNumericRangeCriterionMax();
}
示例#5
0
void OgrWriter::setConfiguration(const Settings& conf)
{
  ConfigOptions configOptions(conf);
  setCreateAllLayers(configOptions.getOgrWriterCreateAllLayers());
  setScriptPath(configOptions.getOgrWriterScript());
  setPrependLayerName(configOptions.getOgrWriterPreLayerName());

  _appendData = configOptions.getOgrAppendData();

  QString strictStr = configOptions.getOgrStrictChecking();
  if (strictStr == "on")
  {
    _strictChecking = StrictOn;
  }
  else if (strictStr == "off")
  {
    _strictChecking = StrictOff;
  }
  else if (strictStr == "warn")
  {
    _strictChecking = StrictWarn;
  }
  else
  {
    throw HootException("Error setting strict checking. Expected on/off/warn. got: " + strictStr);
  }
}
void TagRenameKeyVisitor::setConfiguration(const Settings& conf)
{
  ConfigOptions configOptions(conf);
  _oldKey = configOptions.getTagRenameVisitorOldKey();
  _newKey = configOptions.getTagRenameVisitorNewKey();
  if (_oldKey.trimmed() == "" || _newKey.trimmed() == "")
  {
    throw HootException("Invalid configuration value(s) for the TagRenameKeyVisitor.");
  }
}
示例#7
0
void PertyOp::_configure()
{
  ConfigOptions configOptions(_settings);
  setRandomError(configOptions.getPertyRandomErrorX(), configOptions.getPertyRandomErrorY());
  setSystematicError(
    configOptions.getPertySystematicErrorX(), configOptions.getPertySystematicErrorY());
  setGridSpacing(configOptions.getPertyGridSpacing());
  setCsmParameters(configOptions.getPertyCsmBeta(), configOptions.getPertyCsmD());
  setPermuteAlgorithm(configOptions.getPertyAlgorithm());
  setSeed(configOptions.getPertySeed());
  setNamedOps(configOptions.getPertyOps());
}
void PertyRemoveRandomElementVisitor::setConfiguration(const Settings& conf)
{
  ConfigOptions configOptions(conf);
  setProbability(configOptions.getPertyRemoveRandomP());
  const int seed = configOptions.getPertySeed();
  LOG_VARD(seed);
  if (seed == -1)
  {
    _rng->seed(RandomNumberUtils::generateSeed());
  }
  else
  {
    _rng->seed(seed);
  }
}
示例#9
0
void StatusUpdateVisitor::setConfiguration(const Settings& conf)
{
  ConfigOptions configOptions(conf);
  _onlyUpdateIfStatusInvalid = configOptions.getStatusUpdateVisitorOnlyUpdateInvalidStatus();
  if (configOptions.getStatusUpdateVisitorStatus().trimmed().isEmpty())
  {
    _status = Status::Invalid;
  }
  else
  {
    _status = Status::fromString(configOptions.getStatusUpdateVisitorStatus());
  }
  LOG_VART(_status);
  LOG_VART(_onlyUpdateIfStatusInvalid);
}
void PertyWaySplitVisitor::setConfiguration(const Settings& conf)
{
  ConfigOptions configOptions(conf);
  setWaySplitProbability(configOptions.getPertyWaySplitProbability());
  setMinNodeSpacing(configOptions.getPertyWaySplitMinNodeSpacing());
  const int seed = configOptions.getPertySeed();
  LOG_VARD(seed);
  if (seed == -1)
  {
    _rng->seed(RandomNumberUtils::generateSeed());
  }
  else
  {
    _rng->seed(seed);
  }
}
示例#11
0
void PertyDuplicatePoiOp::setConfiguration(const Settings& conf)
{
  ConfigOptions configOptions(conf);
  setDuplicateSigma(configOptions.getPertyDuplicatePoiDuplicateSigma());
  setProbability(configOptions.getPertyDuplicatePoiP());
  setMoveMultiplier(configOptions.getPertyDuplicatePoiMoveMultiplier());
  const int seed = configOptions.getPertySeed();
  LOG_VARD(seed);
  if (seed == -1)
  {
    _rng->seed(RandomNumberUtils::generateSeed());
  }
  else
  {
    _rng->seed(seed);
  }
}
示例#12
0
void PertyRemoveTagVisitor::setConfiguration(const Settings& conf)
{
  setProbability(conf.getDouble(pKey(), 0.05));
  ConfigOptions configOptions(conf);
  const int seed = configOptions.getPertySeed();
  LOG_VARD(seed);
  if (seed == -1)
  {
    _rng->seed(RandomNumberUtils::generateSeed());
  }
  else
  {
    _rng->seed(seed);
  }
  _exemptTagKeys = configOptions.getPertyRemoveTagVisitorExemptTagKeys();
  _replacementTagKeys = configOptions.getPertyRemoveTagVisitorSubstitutionKeys();
  _replacementTagValues = configOptions.getPertyRemoveTagVisitorSubstitutionValues();
}
示例#13
0
文件: main.cpp 项目: ezuce/sipXsbc
static void initDataStore(OSS::SIP::B2BUA::SBController& sbc)
{
  OSS::SIP::B2BUA::SBController::DataStoreConfig datastore;
  try
  {
    std::ostringstream sqaconfig;
    sqaconfig << SIPX_CONFDIR << "/" << "redis-client.ini";
    ServiceOptions configOptions(sqaconfig.str());
    if (configOptions.parseOptions())
    {
      configOptions.getOption("tcp-address", datastore.redisHost, datastore.redisHost);
      configOptions.getOption("tcp-port", datastore.redisPort, datastore.redisPort);
    }
  }
  catch(...)
  {
  }
  sbc.initDataStore(datastore);
}
示例#14
0
shared_ptr<MatchComparator> PertyMatchScorer::_conflateAndScoreMatches(
    shared_ptr<OsmMap> combinedDataToConflate, const QString conflatedMapOutputPath)
{
  LOG_DEBUG("Conflating the reference data with the perturbed data, scoring the matches, and " <<
            "saving the conflated output to: " << conflatedMapOutputPath);

  shared_ptr<MatchComparator> comparator(new MatchComparator());
  //shared_ptr<MatchThreshold> matchThreshold;
  OsmMapPtr conflationCopy(new OsmMap(combinedDataToConflate));

  ConfigOptions configOptions(_settings);
  if (configOptions.getConflateEnableOldRoads())
  {
    // call the old road conflation routine
    Conflator conflator;
    conflator.loadSource(conflationCopy);
    conflator.conflate();
    conflationCopy.reset(new OsmMap(conflator.getBestMap()));
  }

  UnifyingConflator conflator/*(matchThreshold)*/;
  conflator.setConfiguration(_settings);
  conflator.apply(conflationCopy);

  try
  {
    comparator->evaluateMatches(combinedDataToConflate, conflationCopy);
  }
  catch (const HootException& e)
  {
    // save map modifies the map so we want to make sure comparator runs first. 'finally' would be
    // nice.
    _saveMap(conflationCopy, conflatedMapOutputPath);
    throw e;
  }

  _saveMap(conflationCopy, conflatedMapOutputPath);

  return comparator;
}
示例#15
0
文件: main.cpp 项目: ezuce/sipXsbc
static void initHandler(OSS::SIP::B2BUA::SBController& sbc, ServiceOptions& service)
{
  OSS::SIP::B2BUA::SBController::HandlerConfig handlers;
  try
  {
    std::ostringstream config;
    if (!service.hasOption("config-file", false))
    {
      config << SIPX_CONFDIR << "/" << "sipxsbc.ini";
    }
    else
    {
      std::string configFile;
      service.getOption("config-file", configFile);
      config << configFile;
    }

    ServiceOptions configOptions(config.str());
    if (configOptions.parseOptions())
    {
      configOptions.getOption("globalScriptsDirectory", handlers.globalScriptsDirectory, handlers.globalScriptsDirectory);
      configOptions.getOption("inboundRequestScript", handlers.inboundRequestScript, handlers.inboundRequestScript);
      configOptions.getOption("outboundRequestScript", handlers.outboundRequestScript, handlers.outboundRequestScript);
      configOptions.getOption("outboundResponseScript", handlers.outboundResponseScript, handlers.outboundResponseScript);
      configOptions.getOption("routeRequestScript", handlers.routeRequestScript, handlers.routeRequestScript);

      std::string targetDomain;
      configOptions.getOption("target-domain", targetDomain);
      sbc.setDefaultTargetDomain(targetDomain);
    }
  }
  catch(...)
  {
  }

  sbc.initHandler(handlers);
}
示例#16
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( "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;
}
示例#17
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;
}
示例#18
0
void OsmApiDbReader::setConfiguration(const Settings& conf)
{
  ConfigOptions configOptions(conf);
  setUserEmail(configOptions.getOsmapiDbReaderEmail());
  setBoundingBox(configOptions.getConvertBoundingBox());
}
示例#19
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("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;
}
示例#20
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;
}
示例#21
0
文件: main.cpp 项目: ezuce/sipXsbc
static void initListeners(OSS::SIP::B2BUA::SBController& sbc, ServiceOptions& service)
{
  OSS::SIP::B2BUA::SBController::ListenerConfig transport;
  OSS::SIP::B2BUA::SBController::ListenerInfo tcp, udp;

  std::string listenerAddress;
  std::string externalAddress;
  int listenerPort = 5060;
  transport.tcpPortBase = 30000;
  transport.tcpPortMax = 40000;
  try
  {
    std::ostringstream config;
    if (!service.hasOption("config-file", false))
    {
      config << SIPX_CONFDIR << "/" << "sipxsbc.ini";
    }
    else
    {
      std::string configFile;
      service.getOption("config-file", configFile);
      config << configFile;
    }

    ServiceOptions configOptions(config.str());
    if (configOptions.parseOptions())
    {
      int portBase = transport.tcpPortBase;
      int portMax = transport.tcpPortMax;
      configOptions.getOption("external-address", externalAddress);
      configOptions.getOption("listener-address", listenerAddress);
      configOptions.getOption("listener-port", listenerPort, listenerPort);
      configOptions.getOption("tcp-port-base", portBase, portBase);
      configOptions.getOption("tcp-port-max", portMax, portMax);
      transport.tcpPortBase = portBase;
      transport.tcpPortMax = portMax;
    }
  }
  catch(...)
  {
    OSS_LOG_ERROR("Unable to configure SIP transports.");
    _exit(-1);
  }

  if (listenerAddress.empty())
  {
    OSS_LOG_ERROR("Unable to configure SIP transports.");
    _exit(-1);
  }

  udp.address = listenerAddress;
  udp.externalAddress = externalAddress;
  udp.port = listenerPort;
  udp.proto = "udp";
  tcp.address = listenerAddress;
  tcp.externalAddress = externalAddress;
  tcp.port = listenerPort;
  tcp.proto = "tcp";
  transport.listeners.push_back(udp);
  transport.listeners.push_back(tcp);

  sbc.initListeners(transport);
}
int main()
{
    try {
        Options options;

        Opt::options_description configOptions("Options");
        configOptions.add_options()
            ("account-name,a", Opt::wvalue<std::wstring>(&options.accountName), "Azure storage account name")
            ("primary-key,p", Opt::wvalue<std::wstring>(&options.primaryAccessKey), "The primary access key")
            ("secondary-key,s", Opt::wvalue<std::wstring>(&options.secondaryAccessKey), "The secondary access key")
#if 0
            ("end-point,e", Opt::wvalue<std::wstring>(&options.endPoint)->default_value(L"core.windows.net"), "Endpoint suffix")
#else
            ("end-point,e", Opt::wvalue<std::wstring>(&options.endPoint)->default_value(L"core.windows.net", "core.windows.net"), "Endpoint suffix")
#endif

#if defined(PARSE_USE_HTTPS_OPTION_MYSELF) && PARSE_USE_HTTPS_OPTION_MYSELF
            ("use-https", "Use \"HTTPS\" rather than \"HTTP\"")
            ("use-dev-storage", "Use development storage account")
#else
            ("use-https", Opt::value<bool>(&options.useHttps)->implicit_value(true), "Use \"HTTPS\" rather than \"HTTP\"")
            ("use-dev-storage", Opt::value<bool>(&options.useDevStorage)->implicit_value(true), "Use development storage account")
#endif
            ;

        Opt::variables_map optionsMap;
        std::ifstream configFileStream("example.configuration");
        if (configFileStream) {
            Opt::store(Opt::parse_config_file(configFileStream, configOptions, true), optionsMap);
            Opt::notify(optionsMap);

            // For boolean value, we had better not parse them like this:
            //
            //options.useHttps = optionsMap.count("use-https") > 0;
            //options.useDevStorage = optionsMap.count("use-dev-storage") > 0;
            //
            // since those lines in configuration file:
            //   use-https = false
            //   use-dev-storage = 0
            // will always be wrongly parsed in this way.
            //
            // If you really want to parse them yourself, then do it like this:
#if defined(PARSE_USE_HTTPS_OPTION_MYSELF) && PARSE_USE_HTTPS_OPTION_MYSELF
# if 0
            // Oops! boost::bad_any_cast.
            // We CANNOT cast a string "false" to a boolean false directly.
            // We should convert "false" to "0", and then call boost::any_cast/boost::lexical_cast.
            options.useHttps = optionsMap.count("use-https") > 0 ?
                optionsMap["use-https"].as<bool>() : false;
            options.useDevStorage = optionsMap.count("use-dev-storage") > 0 ?
                optionsMap["use-dev-storage"].as<bool>() : false;
# else
            // Boost.Property_tree.ini_parser will treat "true", "1", "yes" as true, and "false", "0", "no" as false.
            // 
            // Internally, Boost.program_options calls boost::program_options::validate to
            // validate boolean values. That is:
            //   1. Any of "1", "true", "yes", "on" will be converted to "1".
            //   2. Any of "0", "false", "no", "off" will be converted to "0".
            // Please read libs/program_options/src/value_semantic.cpp for more details.
            if (optionsMap.count("use-https") > 0) {
                boost::any v;
                std::vector<std::string> xs {optionsMap["use-https"].as<std::string>()};
                Opt::validate(v, xs, reinterpret_cast<bool *>(NULL), 0);
                options.useHttps = boost::any_cast<bool>(v);
            } else {
                options.useHttps = false;
            }

            if (optionsMap.count("use-dev-storage") > 0) {
                boost::any v;
                std::vector<std::string> xs {optionsMap["use-dev-storage"].as<std::string>()};
                Opt::validate(v, xs, reinterpret_cast<bool *>(NULL), 0);
                options.useDevStorage = boost::any_cast<bool>(v);
            } else {
                options.useDevStorage = false;
            }
# endif
#endif

            std::cout << configOptions;

            std::wcout << L"\n\n" << options;
        } else {
            std::cerr << "Open configuration file failed.\n";
            return EXIT_FAILURE;
        }
    } catch (const std::exception &e) {
        RETURN_ON_FAILURE_MSG("exception");
    }

    PAUSE();
    return 0;
}