Ejemplo n.º 1
0
void infor()
{
      int sher;
      clrscr();
      textcolor(WHITE);
      gotoxy(13,3);
      printf("\xDB\xDB\xDB\xDB\xB2  INFORMATION ABOUT PRODUCTS  \xB2\xDB\xDB\xDB\xDB");
      gotoxy(2,5);
      printf("THIS SECTION IS TO TELL WHAT KIND OF PRODUCTS ARE THERE IN STORE");
      printf("\n\nENTER THE OPTION WHICH SUITS YOU.\n");
      printf("\n\n1.EDIBLES.\n\n");
      printf("\n2.GENERAL ITEMS.\n\n");
      printf("\n\n\n\n\nOPTION:");
      sher=toupper(getch());

  switch(sher)
  {
      case '1':
      eat();
      break;

      case '2':
      general();
      break;

      default:
      gotoxy(8,21);
      cprintf("\awrong entry press any key to go main menu..");
    }
   getche();

   }
Ejemplo n.º 2
0
int main(){
    int a,n;
    int nearest;
    //clrscr();
    int choice;
    do{
        printf("\n\n* * * W E L C O M E * * *");
        printf("\n    1 .   Find Power");
        printf("\n    2 .   Exit");
        printf("\nEnter Choice: ");
        scanf("%d",&choice);
        switch (choice){
            case 1:
                printf("\nEnter a^n: ");
                scanf("%d %d",&a,&n);
                //printf("\nYou entered %d^%d.",a,n);
                //printf("\nSolution sqrCase: %d^%d = %d",a,n,sqrCase(a,n));
                printf("\nSolution General: %d^%d = %d",a,n,general(a,n));
                break;
            case 2:
                printf("\n* * * THANKS * * *");
                break;
            default:
                printf("\nWish you knew how to count ! ! !");
                break;
        }
    }while(choice!=2);

    //getch();
    return 0;
}
Ejemplo n.º 3
0
/**
 * The keyboard up function that recognizes when a key is released.
 */
void keyboardUp(unsigned char key, int x, int y) {
   if (key == 'm' || key == 'M' || key == ',' || key == '<' ||
         key == '.' || key == '>') {
      key_states['m'] = false; key_states['M'] = false;
      key_states[','] = false; key_states['<'] = false;
      key_states['.'] = false; key_states['>'] = false;
      general((char*)"is_moving");
   }
   else if (key >= 65 && key <= 90) {
      key_states[key + 32] = false;
   }
   else if (key >= 97 && key <= 122) {
      key_states[key - 32] = false;
   }
   else if (key == '[' || key == '{') {
      key_states['['] = false;
      key_states['{'] = false;
   }
   else if (key == ']' || key == '}') {
      key_states[']'] = false;
      key_states['}'] = false;
   }
   else if (key == ';' || key == ':') {
      key_states[';'] = false;
      key_states[':'] = false;
   }
   key_states[key] = false;
}
void CppHelperPluginConfigPage::storeSet()
{
    auto set_name = m_favorite_sets->setsList->currentText();
    kDebug(DEBUG_AREA) << "Current set name:" << set_name;

    auto cfg = KSharedConfigPtr{};
    {
        auto it = m_include_sets.find(set_name);
        if (it == end(m_include_sets))
        {
            auto filename = QString{QUrl::toPercentEncoding(set_name)};
            auto incset_file = KStandardDirs::locateLocal(
                "appdata"
              , QString{INCSET_FILE_TPL}.arg(filename)
              , true
              );
            kDebug(DEBUG_AREA) << "Going to make a new incset file for it:" << incset_file;
            cfg = KSharedConfig::openConfig(incset_file, KConfig::SimpleConfig);
        }
        else cfg = it->second.m_config;
    }

    auto dirs = QStringList{};
    for (auto i = 0, last = m_session_list->pathsList->count(); i < last; ++i)
        dirs << m_session_list->pathsList->item(i)->text();
    kDebug(DEBUG_AREA) << "Collected current paths:" << dirs;

    // Write Name and Dirs entries to the config
    KConfigGroup general(cfg, INCSET_GROUP_NAME);
    general.writeEntry(INCSET_NAME_KEY, set_name);
    general.writePathEntry(INCSET_DIRS_KEY, dirs);
    /// \todo I wonder is it always successed? ORLY?!
    cfg->sync();
    updateSets(set_name);
}
void validate(boost::any& v, const std::vector<std::string>& values, DBPTM* target_type, int) {
	std::string name;
	std::string abbreviation;
	std::string residues;
	std::string formula;
	bool is_static;

	typedef boost::escaped_list_separator<char> separator_type;
	separator_type separator("\\",    // The escape characters.
							 "\t ",    // The separator characters.
							 "\"\'"); // The quote characters.

	boost::program_options::options_description general("PTMs");
	general.add_options()
			("name,n", boost::program_options::value<std::string>(&name), "")
			("abbreviation,b", boost::program_options::value<std::string>(&abbreviation), "")
			("residues,r", boost::program_options::value<std::string>(&residues), "")
			("formula,m", boost::program_options::value<std::string>(&formula), "" )
			("is_static,s", boost::program_options::value<bool>(&is_static), "" )
			;

	boost::tokenizer<separator_type> tokens(values[0], separator);
	std::vector<std::string> result;

	std::copy(tokens.begin(), tokens.end(), std::back_inserter(result));

	boost::program_options::variables_map vm;
	boost::program_options::store(boost::program_options::command_line_parser(result).options(general).run(), vm);
	boost::program_options::notify(vm);

	std::cout << "PTM registered: " << name << " " << residues << " " << formula << std::endl;

	v = DBPTM(name, abbreviation, residues, formula, is_static);
}
void validate(boost::any& v, const std::vector<std::string>& values, DBEnzyme* target_type, int) {
	std::string name;
	std::string residues;
	std::string blocking_residues;
	TERMINUS terminus;

	typedef boost::escaped_list_separator<char> separator_type;
	separator_type separator("\\",    // The escape characters.
							 "\t ",    // The separator characters.
							 "\"\'"); // The quote characters.

	boost::program_options::options_description general("Enzymes");
	general.add_options()
			("name,n", boost::program_options::value<std::string>(&name), "")
			("residues,r", boost::program_options::value<std::string>(&residues), "")
			("blocking_residues,b", boost::program_options::value<std::string>(&blocking_residues), "")
			("terminus,t", boost::program_options::value<TERMINUS>(&terminus), "")
			;

	boost::tokenizer<separator_type> tokens(values[0], separator);
	std::vector<std::string> result;

	std::copy(tokens.begin(), tokens.end(), std::back_inserter(result));

	boost::program_options::variables_map vm;
	boost::program_options::store(boost::program_options::command_line_parser(result).options(general).run(), vm);
	boost::program_options::notify(vm);

	std::cout << "Enzyme registered: " << name << " " << residues << " " << blocking_residues  << std::endl;

	v = DBEnzyme(name, residues, blocking_residues, terminus);
}
Ejemplo n.º 7
0
o3d3xx::CmdLineOpts::CmdLineOpts(const std::string& description)
  : visible(description)
{
  // generic options
  po::options_description general("General");
  general.add_options()
    ("version,v", "Print version string and exit")
    ("help,h", "Produce help message");

  // options for connecting to the camera
  po::options_description connection_opts("Connection Information");
  connection_opts.add_options()
    ("ip",
     po::value<std::string>()->default_value(o3d3xx::DEFAULT_IP),
     "IP address of the camera")

    ("xmlrpc-port",
     po::value<std::uint32_t>()->default_value(o3d3xx::DEFAULT_XMLRPC_PORT),
     "XMLRPC port of the camera")

    ("password",
     po::value<std::string>()->default_value(o3d3xx::DEFAULT_PASSWORD),
     "Password for configuring the camera");

  this->visible.add(general).add(connection_opts);
}
Ejemplo n.º 8
0
bool MaterialEditDialog::writeMaterial()
{
    if (lstProperties->currentItem())
        m_properties.replace(lstProperties->currentRow(), writeProperty());

    QFileInfo fileInfo(m_fileName);
    if (fileInfo.baseName() != txtName->text())
    {
        bool move = true;

        // rename file
        QString newFilename = fileInfo.absolutePath() + "/" + txtName->text() + ".mat";
        if (QFile::exists(newFilename))
            move = (QMessageBox::question(this, tr("File exists"), tr("Material '%1' already exists. Do you wish replace this file?").arg(newFilename)) == 0);

        if (move)
        {
            QFile::remove(m_fileName);
            m_fileName = newFilename;
        }
    }

    try
    {
        // general
        XMLMaterial::general general(txtName->text().toStdString());
        general.description().set(txtDescription->text().toStdString());

        // properties
        XMLMaterial::properties properties;
        foreach(XMLMaterial::property prop, m_properties)
        {
            // add property
            properties.property().push_back(prop);
        }

        // material
        XMLMaterial::material material(general, properties);

        std::string mesh_schema_location("");

        // TODO: set path more general
        mesh_schema_location.append(QString("%1/material_xml.xsd").arg(QFileInfo(datadir() + XSDROOT).absoluteFilePath()).toStdString());
        ::xml_schema::namespace_info namespace_info_mesh("XMLMaterial", mesh_schema_location);

        ::xml_schema::namespace_infomap namespace_info_map;
        namespace_info_map.insert(std::pair<std::basic_string<char>, xml_schema::namespace_info>("material", namespace_info_mesh));

        std::ofstream out(compatibleFilename(m_fileName).toStdString().c_str());
        XMLMaterial::material_(out, material, namespace_info_map);

        return true;
    }
Ejemplo n.º 9
0
int general(int a,int n){
    //int out=0;
    int near;
    near=nearestMul(n);  //nearestMul(n) returns nearest 2^k multiple of n.
    if(near==1){
        return (a);   //Base Case: 2^1
    }
    else if(near==n){
        return(sqrCase(a,near));
    }
    else{
        a=sqrCase(a,near)*general(a,n-near);
    }
}
Ejemplo n.º 10
0
int main(int argc, char **argv)
{
	struct test test;
	enum target t;

	test_init(&test, argc, argv);

	for (t = TARGET_FIRST; t <= TARGET_LAST; t++) {
		hv0(&test, t);
		general(&test, t);
	}

	return 0;
}
Ejemplo n.º 11
0
CmdLine::CmdLine(int argc,char**argv) : should_exit_(false) {
      po::options_description general("General options");

      general.add_options()
          ("directories,d", po::value< std::vector<std::string> >(&dirs_),"directories to display on video")
          ("captions,c", po::value< std::vector<std::string> >(&captions_),"captions to display on videos (in the same order as directories)")
          ("output-directory,o", po::value<std::string>(&output_dir_),"output directory where the concatenated images are stored")
          ("verbose,v", "verbose mode")
          ("debug,D", "debug mode")

          ("help", "produce help message")
          ;

      prog_args.add(general);
      po::store(po::parse_command_line(argc, argv, prog_args), vm_);
      po::notify(vm_);

      if (vm_.count("help")) {
          std::cout << prog_args << std::endl;
          should_exit_ = true;
      }
      DEBUG_WRITE("Debug mode active.");

      unsigned int nbvid=0;
      std::string cur_caption("");
      for(std::vector< std::string >::iterator i=dirs_.begin(), cap_iter=captions_.begin();
          i!=dirs_.end();
          i++,nbvid++){
        if(cap_iter==captions_.end())
          cur_caption = "";
        else{
          cur_caption = *cap_iter;
          cap_iter++;
        }
        boost::shared_ptr<VideoWithCaption> el(new VideoWithCaption());
        el->caption=cur_caption;
        el->path = i->c_str();
        el->reader.setFileName( i->c_str() );
        el->reader.setFirstFrameIndex(0);
        el->reader.open(el->I);
        videos_.push_back(el);
        if(get_verbose()){
          std::cout << "Adding video with path " << el->path << " and caption " << el->caption << std::endl;
        }
      }
      DEBUG_WRITE("Done adding videos.");

      if(get_verbose())
        std::cout << nbvid << " videos added." << std::endl;
}
Ejemplo n.º 12
0
void TagActionManager::initActions(QWidget* parent)
{
    Q_ASSERT(parent);
    
    m_actionCollection = new KActionCollection(parent);
    
    TagActionSet* general(new TagActionSet());
    general->initActions(parent);
    m_tagActionSets.append(general);
        
    TableTagActionSet* table(new TableTagActionSet());
    table->initActions(parent);
    m_tagActionSets.append(table);
}
Ejemplo n.º 13
0
DataItem JInfoRequest::createDataItem() const
{
	Q_D(const JInfoRequest);
	DataItem item;
	const bool isAccount = qobject_cast<Account*>(object());
	{
		DataItem general(QT_TRANSLATE_NOOP("ContactInfo", "General"));
		// General page
		{
			//// Avatar
			{
				QString photoPath;
				JVCardManager::ensurePhoto(d->vcard->photo(), &photoPath);
				DataItem avatarItem(QLatin1String("avatar"),
									QT_TRANSLATE_NOOP("ContactInfo", "Avatar"),
									QPixmap(photoPath));
				avatarItem.setProperty("imagePath", photoPath);
				avatarItem.setProperty("hideTitle", true);
				avatarItem.setProperty("imageSize", QSize(64, 64));
				avatarItem.setProperty("defaultImage", Icon(QLatin1String("qutim")).pixmap(64));
				general.addSubitem(avatarItem);
			}
			// name
//			QString name = d->vcard->nickname().isEmpty() ? d->vcard->formattedName() : d->vcard->nickname();
			addItemList(Nick, general, d->vcard->nickname());
			addItemList(FirstName, general, d->vcard->name().given());
			addItemList(MiddleName, general, d->vcard->name().middle());
			addItemList(LastName, general, d->vcard->name().family());
			// birthday
			addItem(Birthday, general, d->vcard->birthday().date());
			//// homepage
			addItem(Homepage, general, QVariant::fromValue(d->vcard->url()));
		}
		if (!isAccount) {
		//// telephone
			if (!d->vcard->telephones().empty()) {
				foreach (Jreen::VCard::Telephone phone, d->vcard->telephones())
					addItem(getPhoneType(phone), general, phone.number());
			} else {
				addItem(Phone, general, QString());
			}
		//// email
			if (!d->vcard->emails().empty()) {
				foreach (const Jreen::VCard::EMail &email, d->vcard->emails())
					addItem(getEmailType(email), general,email.userId());
			} else {
				addItem(Email, general, QString());
			}
		}
Ejemplo n.º 14
0
int
processCommandLineArgs(InputOptions & in, const int argc, char * argv[])
{
  namespace po = ::boost::program_options;

  const ::std::string exeName(argv[0]);

  try
  {
    po::options_description general(
        "slock\nUsage: " + exeName + " file_to_lock...\nOptions");
    general.add_options()
        ("help", "Show help message")
        ("try,t", po::value< bool>(&in.tryLock)->default_value(false),
        "Try locking the file, return immediately if unsuccessful")
        ("lock-file", po::value< ::std::string>(&in.lockFile)_ADD_REQUIRED_,
                "The file to lock")
        ;

    po::positional_options_description p;
    p.add("lock-file", 1);

    po::options_description cmdLineOptions;
    cmdLineOptions.add(general);

    po::variables_map vm;
    po::store(
        po::command_line_parser(argc, argv).options(cmdLineOptions).positional(
            p).run(), vm);

    // Deal with help first, otherwise missing required parameters will cause exception on vm.notify
    if(vm.count("help"))
    {
      ::std::cout << cmdLineOptions << ::std::endl;
      return 1;
    }

    po::notify(vm);
  }
  catch(std::exception& e)
  {
    ::std::cout << e.what() << "\n";
    return 1;
  }

  // Everything went fine
  return 0;
}
Ejemplo n.º 15
0
bool CommandLine::Parse(int argc, char* argv[])
{
    namespace po = boost::program_options;
    // Declare the supported options.
    std::wcout << std::boolalpha;
    try
    {
        po::options_description general("General options");
        general.add_options()
            ("help,h", "produce help message")
            ("no-pinger", "Dont be a pinger (default is to be a pinger and a ponger)")
            ("no-ponger", "Dont be a ponger (default is to be a pinger and a ponger)")
            ;

        po::options_description pinger("Pinger options");
        pinger.add_options()
            ("num-instances,i", po::value<int>(&m_numInstances)->default_value(1), "The number of instances to use")
            ("payload,p", "Add payload of random size to Ping")
            ("timeout,t", po::value<int>(&m_timeout)->default_value(20),"Timeout before missing pongs should generate error report")
            ;


        //merge options into one.
        po::options_description all ("Allowed options");
        all.add(general).add(pinger);

        po::store(po::parse_command_line(argc,argv,all),m_variablesMap);
        po::notify(m_variablesMap);

        if (m_variablesMap.count("help"))
        {
            std::wcout << all << std::endl;
            return false;
        }

        m_noPinger = 0 != m_variablesMap.count("no-pinger");
        m_noPonger = 0 != m_variablesMap.count("no-ponger");
        m_payload = 0 != m_variablesMap.count("payload");
    }
    catch (const std::exception & e)
    {
        std::wcerr << "Parse of command line failed: " << std::endl
            << e.what() << std::endl;
        return false;
    }
    return true;
}
Ejemplo n.º 16
0
void EventApplet::setupCategoryColors(int opacity)
{
    m_categoryColors.clear();

    KConfig *koConfig = new KConfig("korganizerrc");

    KConfigGroup general(koConfig, "General");
    QStringList categories = general.readEntry("Custom Categories", QStringList());

    KConfigGroup categoryColors(koConfig, "Category Colors2");
    foreach(const QString &category, categories) {
        QColor cColor = categoryColors.readEntry(category, QColor());
        if (cColor.isValid()) {
            cColor.setAlphaF(opacity/100.0);
            m_categoryColors.insert(category, cColor);
        }
    }
Ejemplo n.º 17
0
bool CommandLine::Parse(int argc, char* argv[])
{
    namespace po = boost::program_options;
    // Declare the supported options.
    std::wcout << std::boolalpha;
    try
    {
        po::options_description general("General options");
        general.add_options()
            ("help,h", "produce help message")
            ("requestor,s", "Be a requestor (default is to be a receiver)")
            ;

        po::options_description requestor("Requestor options");
        requestor.add_options()
            ("large,l", "Use a large message (default is small)")
            ;

        po::options_description receiver("Receiver options");
        receiver.add_options()
            ;

        //merge options into one.
        po::options_description all ("Allowed options");
        all.add(general).add(requestor).add(receiver);

        po::store(po::parse_command_line(argc,argv,all),m_variablesMap);

        if (m_variablesMap.count("help"))
        {
            std::wcout << all << std::endl;
            return false;
        }

        m_requestor = 0 != m_variablesMap.count("requestor");
        m_large = 0 != m_variablesMap.count("large");
    }
    catch (const std::exception & e)
    {
        std::wcerr << "Parse of command line failed: " << std::endl
            << e.what() << std::endl;
        return false;
    }
    return true;
}
Ejemplo n.º 18
0
po::options_description getGeneralConfigFileOptions()
{
    po::options_description general("General options");
    general.add_options()
        ("video-filename,v", po::value<std::string>(), "Path to the video file to process")
        ("framelist-filename", po::value<std::string>(), "Path to a text file with a framelist to process")
        ("homography-filename,h", po::value<std::string>()->default_value("\"\""), "Path to the homography matrix")
        ("scaleratio-filename", po::value<std::string>(), "Path to the pixel/meter ratio file")
        ("aerialview-filename,a", po::value<std::string>()->default_value("\"\""), "Path to the aerial view screenshot")
        ("mask-filename,m", po::value<std::string>()->default_value("\"\""), "Path to the mask image (where features are detected)")
        ("display-trajectories,d", po::value<bool>()->default_value(true), "Display trajectories on the video")
        ("draw-aerial", po::value<bool>()->default_value(true), "show the aerial view")
        ("draw-bgs", po::value<bool>()->default_value(true), "show the background substraction")
        ("draw-perspective", po::value<bool>()->default_value(true), "show the perspective view")
        ("draw-bounding-box", po::value<bool>()->default_value(false), "Draw the bounding box of all the points at the current time of the objects")
        ("draw-trajectories", po::value<bool>()->default_value(true), "Draw the trajectories")
        ("draw-centroid", po::value<bool>()->default_value(false), "Draw cluster centroid")
        ("draw-inactive-cluster", po::value<bool>()->default_value(false), "Draw inactive cluster")
        ("draw-tracker-stats", po::value<bool>()->default_value(false), "Draw tracker stats")
        ("draw-fps", po::value<bool>()->default_value(true), "Display FPS")
        ("draw-keypoints", po::value<bool>()->default_value(false), "Display Keypoints")
        ("draw-matches", po::value<bool>()->default_value(false), "Display matches")
        ("draw-memory", po::value<bool>()->default_value(false), "Draw memory consumption")
        ("draw-nbobject-nbtrajectories", po::value<bool>()->default_value(false), "Display number of object and trajectories")
        ("seek-ms", po::value<unsigned int>(), "The number of ms to seek to...")
        ("seek-frame", po::value<unsigned int>(), "The number of frame to seek to...")
        ("video-start-time", po::value<std::string>(), "The start time displayed by the video in the format HH:MM::SS")
        ("video-end-frame", po::value<unsigned int>(), "The last frame we want to process")
        ("video-seek-time", po::value<std::string>(), "The position you want to seek to in the video in the format HH:MM::SS")
        ("bgs-type", po::value<std::string>()->default_value("LBMixtureOfGaussians"), "Name of the background substraction technic to use.")
        ("record-bgs", po::value<bool>()->default_value(false), "If we should record the BGS for further playback or not")
        ("tracker-filename",  po::value<std::string>(), "Name of the file that contains the tracker specific information")
        ("filepath-filename",  po::value<std::string>(), "Name of the file that contains the filepath specific information")
        ("bgs-filepath",  po::value<std::string>()->default_value(""), "Path to the directory containing the background substraction. To be used with PlaybackBGS")
        ("logging-level", po::value<unsigned int>(), "The current logging level (0 debug, 1 info, 2 warning, 3 error, 4 none)")


        ("total-number-frame", po::value<unsigned int>(), "Total number of frame in file")
        ("object-sqlite-filename",  po::value<std::string>(), "Name of the file that contains the object database")
        ("run-time-verification", po::value<bool>()->default_value(false), "The system does runtime verification to verify of the integrity of the structure. This is for debugging only as it takes a lot of CPU");

    return general;
}
/**
 * Find all \c *.inset files in \c ${APPDATA}/plugins/katecpphelperplugin.
 * Open found file (as ordinal KDE config), read a set \c Name and fill the
 * \c m_include_sets map w/ \e Name to \c KSharedConfigPtr entry.
 * After all found files forcessed, fill the combobox w/ found entries.
 * 
 * \param current if not empty string, preselect this item
 */
void CppHelperPluginConfigPage::updateSets(const QString& current)
{
    // Remove everything collected before
    m_favorite_sets->setsList->clear();
    m_include_sets.clear();

    // Find *.incset files
    auto sets = KGlobal::dirs()->findAllResources(
        "appdata"
      , QString{INCSET_FILE_TPL}.arg("*")
      , KStandardDirs::NoSearchOptions
      );
    kDebug(DEBUG_AREA) << "sets:" << sets;

    // Form a map of set names to shared configs
    for (const auto& filename : sets)
    {
        KSharedConfigPtr incset = KSharedConfig::openConfig(filename, KConfig::SimpleConfig);
        KConfigGroup general(incset, INCSET_GROUP_NAME);
        auto set_name = general.readEntry(INCSET_NAME_KEY, QString{});
        auto dirs = general.readPathEntry(INCSET_DIRS_KEY, QStringList{});
        kDebug(DEBUG_AREA) << "set name: " << set_name;
        kDebug(DEBUG_AREA) << "dirs: " << dirs;
        m_include_sets[set_name] = IncludeSetInfo{incset, filename};
    }

    // Fill the `sets` combobox w/ names
    kDebug() << "current set name" << current;
    for (const auto& p : m_include_sets)
    {
        kDebug() << "adding set name" << p.first;
        m_favorite_sets->setsList->addItem(p.first);
    }
    // Try to preset a set name
    if (!current.isEmpty())
        m_favorite_sets->setsList->setCurrentItem(current, false);
}
Ejemplo n.º 20
0
frontend::frontend(int argc, char** argv)
{
    boost::program_options::options_description general("General options");
    general.add_options()
        ("help,h", "print this message")
        ("version,v", "print version information");

    boost::program_options::options_description config("Configuration");
    config.add_options()
        ("output,o", boost::program_options::value<std::string>(), "specify output file")
        ("recursive,r", "let the create action be recursive")
        ("create,c", "create the output from inputs")
        ("unpack,u", "unpack the inputs into the output");

    boost::program_options::options_description hidden("Hidden");
    hidden.add_options()
        ("input", boost::program_options::value<std::vector<std::string>>()->composing(), "specify input file");

    boost::program_options::positional_options_description pod;
    pod.add("input", -1);

    boost::program_options::options_description options;
    options.add(general).add(config).add(hidden);

    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).positional(pod)
        .style(boost::program_options::command_line_style::allow_short
            | boost::program_options::command_line_style::allow_long
            | boost::program_options::command_line_style::allow_sticky
            | boost::program_options::command_line_style::allow_dash_for_short
            | boost::program_options::command_line_style::long_allow_next
            | boost::program_options::command_line_style::short_allow_next
            | boost::program_options::command_line_style::allow_long_disguise).run(), _variables);

    if (_variables.count("help"))
    {
        std::cout << version_string << '\n';

        std::cout << "Usage:\n";
        std::cout << "  raf [options] inputs [options]\n\n";

        std::cout << general << std::endl << config << std::endl;

        std::exit(0);
    }

    if (_variables.count("version"))
    {
        std::cout << version_string;
        std::cout << "Distributed under modified zlib license.\n\n";

        std::cout << "RAF, or Reaver Archive Format utility, is part of the Reaver Project - http://reaver-project.org/.\n";

        std::exit(0);
    }

    if (_variables.count("output"))
    {
        _output = _variables["output"].as<std::string>();
    }

    if (_variables.count("input"))
    {
        _inputs = _variables["input"].as<std::vector<std::string>>();
    }

    if (_variables.count("recursive"))
    {
        _recursive = true;
    }

    if (_variables.count("create"))
    {
        _create = true;
    }

    if (_variables.count("unpack"))
    {
        _unpack = true;
    }
}
Ejemplo n.º 21
0
int main(int argc, char *argv[]) {
    namespace po = boost::program_options;

    std::string privateKeyFile;
    std::string publicKeyFile;

    po::options_description general("General options");
    general.add_options()
        ("help", "produce help message")
        ("generate-rsa,g",
            "generate RSA keys and save to public.key and private.key")
        ("publickey",
            po::value<std::string>(&publicKeyFile)
                ->default_value("public.key"),
            "path to publickey (default \"public.key\"")
        ("privatekey",
            po::value<std::string>(&privateKeyFile)
                ->default_value("private.key"),
            "path to private key (default \"private.key\"");

    po::options_description openContainer("Open existing container");
    openContainer.add_options()
        ("open,o", po::value<std::string>(), "open existing container")
        ("unpack,u", po::value<std::string>(),
            "unpack selected files to directory")
        ("unpackAll,U", po::value<std::string>(),
            "unpack all files to directory")
        ("add,a", "add selected files");

    po::options_description createContainer("Create new container");
    createContainer.add_options()
        ("create,c", po::value<std::string>(), "create new container");

    po::options_description hidden("Hidden options");
    hidden.add_options()
        ("input-file", po::value<std::vector<std::string>>(),
            "input container file");


    po::options_description cmdlineOptions;
    cmdlineOptions
        .add(general)
        .add(openContainer)
        .add(createContainer)
        .add(hidden);

    po::positional_options_description p;
    p.add("input-file", -1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).
        options(cmdlineOptions).positional(p).run(), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout
            << "Usage: CryptoContainer [options] <input or output files>"
            << std::endl;
        std::cout << general << "\n";
        std::cout << openContainer << "\n";
        std::cout << createContainer << "\n";
        return 1;
    }

    if (vm.count("generate-rsa")) {
        std::cout << "Generating RSA keys" << std::endl;
        auto RSAKeys = cc::generateRSAKeys();

        // Save public key
        std::cout << "Public key... ";
        cc::saveKeyToFile<CryptoPP::RSA::PublicKey>("public.key",
                                                     RSAKeys.second);
        std::cout << "OK" << std::endl;

        // Save private key
        std::cout << "Private key... ";
        cc::saveKeyToFile<CryptoPP::RSA::PrivateKey>("private.key",
                                                     RSAKeys.first);
        std::cout << "OK" << std::endl;

        return 1;
    }

    if (vm.count("create")) {
        std::cout << "Create container" << std::endl;

        if (!vm.count("input-file")) {
            std::cout << "Error: Need select input files" << std::endl;
            return -1;
        }

        if (!boost::filesystem::exists(publicKeyFile)) {
            std::cout << "Error: Public key doesn't exists" << std::endl;
            return -1;
        }

        if (boost::filesystem::is_directory(vm["create"].as<std::string>())) {
            std::cout << "Error: Path direct to directory" << std::endl;
            return -1;
        }

        auto publicKey =
            cc::loadKeyFromFile<CryptoPP::RSA::PublicKey>(publicKeyFile);

        auto container =
            cc::Container::openNewContainer(vm["create"].as<std::string>(),
                                            publicKey);

        if (!container) {
            std::cout << "invalid key or can't open file" << std::endl;
            return -1;
        }

        const auto pathsToPack =
            vm["input-file"].as<std::vector<std::string>>();
        for (auto &input : pathsToPack) {
            container->addFileOrFolder(input);
        }

        std::cout << "Wait a while..." << std::endl;
        container->save();
        std::cout << "Created " << vm["create"].as<std::string>()
            << " container" << std::endl;

        return 0;
    }

    if (vm.count("open")) {
        std::cout << "Open existed container" << std::endl;

        if (!boost::filesystem::exists(publicKeyFile)) {
            std::cout << "Error: Public key doesn't exists" << std::endl;
            return -1;
        }

        if (!boost::filesystem::exists(privateKeyFile)) {
            std::cout << "Error: Private key doesn't exists" << std::endl;
            return -1;
        }

        auto privateKey =
            cc::loadKeyFromFile<CryptoPP::RSA::PrivateKey>(privateKeyFile);

        auto publicKey =
            cc::loadKeyFromFile<CryptoPP::RSA::PublicKey>(publicKeyFile);

        auto container = cc::Container::openExistedContainer(
            vm["open"].as<std::string>(), publicKey, privateKey);

        if (!container) {
            std::cout << "Can't open container" << std::endl;
            return -1;
        }

        std::cout << "Wait a while..." << std::endl;

        if (vm.count("unpackAll")) {
            const std::string path = vm["unpackAll"].as<std::string>();
            container->unpackAll(path);
            std::cout << "Unpacked all data to: " << path << std::endl;
            return 0;
        } else if (vm.count("unpack")) {
            const std::string targetPath = vm["unpack"].as<std::string>();

            const auto pathsToUnpack =
                vm["input-file"].as<std::vector<std::string>>();

            for (auto& path : pathsToUnpack) {
                std::cout << "Unpack: " << path << std::endl;
                container->unpack(path, targetPath);
            }

            std::cout << "Unpacked all data to: " << targetPath << std::endl;

            return 0;
        } else if (vm.count("add")) {
            const auto pathsToPack =
                vm["input-file"].as<std::vector<std::string>>();

            for (auto &input : pathsToPack) {
                container->addFileOrFolder(input);
            }

            container->save();
            std::cout << "Added" << std::endl;
        } else {
            std::cout << "Invalid command!" << std::endl;
        }
    }

    return 0;
}
Ejemplo n.º 22
0
void Parameters::parse_options(int argc, char* argv[])
{
    unsigned log_level = 2;

    po::options_description general("General options");
    auto general_add = general.add_options();
    general_add("version,V", "print version string");
    general_add("help,h", "produce help message");
    general_add("log-level,l", po::value<unsigned>(&log_level),
                "set the log level (default:2, all:0)");
    general_add("maximum-number,n", po::value<uint64_t>(&maximum_number),
                "set the maximum number of microslices to process (default: "
                "unlimited)");

    po::options_description source("Source options");
    auto source_add = source.add_options();
    source_add("pattern-generator,p", po::value<uint32_t>(&pattern_generator),
               "use pattern generator to produce timeslices");
    source_add("shm-channel,c", po::value<size_t>(&shm_channel),
               "use given shared memory channel as data source");
    source_add("input-shm,I", po::value<std::string>(&input_shm),
               "name of a shared memory to use as data source");
    source_add("input-archive,i", po::value<std::string>(&input_archive),
               "name of an input file archive to read");

    po::options_description sink("Sink options");
    auto sink_add = sink.add_options();
    sink_add("analyze,a", po::value<bool>(&analyze)->implicit_value(true),
             "enable/disable pattern check");
    sink_add("dump_verbosity,v", po::value<size_t>(&dump_verbosity),
             "set output debug dump verbosity");
    sink_add("output-shm,O", po::value<std::string>(&output_shm),
             "name of a shared memory to write to");
    sink_add("output-archive,o", po::value<std::string>(&output_archive),
             "name of an output file archive to write");

    po::options_description desc;
    desc.add(general).add(source).add(sink);

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help") != 0u) {
        std::cout << "mstool, git revision " << g_GIT_REVISION << std::endl;
        std::cout << desc << std::endl;
        exit(EXIT_SUCCESS);
    }

    if (vm.count("version") != 0u) {
        std::cout << "mstool, git revision " << g_GIT_REVISION << std::endl;
        exit(EXIT_SUCCESS);
    }

    logging::add_console(static_cast<severity_level>(log_level));

    use_pattern_generator = vm.count("pattern-generator") != 0;

    size_t input_sources = vm.count("pattern-generator") +
                           vm.count("input-archive") + vm.count("input-shm");
    if (input_sources == 0) {
        throw ParametersException("no input source specified");
    }
    if (input_sources > 1) {
        throw ParametersException("more than one input source specified");
    }
}
Ejemplo n.º 23
0
void    FsStat::disp(SuperBlock * SB, VFile * vfile)
{
  general(SB);
  features(SB);
  groupInformations(SB, vfile);
}
Ejemplo n.º 24
0
int main(int argc, char **argv) {
	ParametersVectorType initialParameters;
	std::string outPrefix, bmImageName, initFile, initMeansFile, mrfModelFile;
	std::string s_minimization = DEFAULT_MRF_ALG;
	float lambda1, lambda2;
	ProbabilityPixelType atlas_th, mask_th;
	unsigned int nClasses, emIterations, mrfIterations;
	std::vector<std::string> channels, priors, geometricTerm;
	std::string s_mode = "km+em";
	std::string outExt = "nii.gz";

	std::vector<double> dataOffsets;
	std::vector<double> dataFactors;

	bool useFile = false;
	bool skipMRF = false;
	bool usePVE = false;
	bool doOutputStats,doSegmentsOutput, doOutputMRFMaps, doOutputMRFIterations,
	     doOutputSteps, useExplicitPVE, skipNormalization, skipBias, doBiasOutput, doCorrectedOutput,
	     channelsAreMasked = false;
	unsigned int userBucketSize = 0;

	boost::unordered_map<std::string, INIT_MODES> modes_map;

	modes_map["none"] = NONE;
	modes_map["km"] = KMEANS;
	modes_map["em"] = EM;
	modes_map["km+em"] = KMEANS_EM;

	boost::unordered_map<std::string, typename MRFFilter::GCOptimizerType::MINIMIZATION_MODES > minimiz_map;
	minimiz_map["expansion"] = MRFFilter::GCOptimizerType::EXPANSION;
	minimiz_map["swap"] = MRFFilter::GCOptimizerType::SWAP;


	bpo::options_description general("General options");
	general.add_options()
		("help", "show help message")
		("out,o",bpo::value < std::string > (&outPrefix), "prefix for output files")
		("out-ext", bpo::value< std::string >( &outExt ), "output format, if supported by ITK")
		("brain-mask,x",bpo::value < std::string > (&bmImageName),"brain extracted mask")
		("channels-masked,M", bpo::bool_switch(&channelsAreMasked), "set this flag if channels are already masked")
		("channels,C", bpo::value< std::vector< std::string > >(&channels)->multitoken()->required(),"list of channels for multivariate segmentation")
		("class,n",	bpo::value<unsigned int>(&nClasses)->default_value(DEFAULT_NCLASSES), "number of tissue-type classes")
		("init,I", bpo::value< std::string >(&s_mode), "operation mode for initialization [none,km,em,km+em]")
		("init-file,f",bpo::value < std::string > (&initFile),"use file for initialization of tissue-type means & variances")
		("init-means",bpo::value < std::string > (&initMeansFile),"use file for initialization of tissue-type means")
		("segments,g", bpo::bool_switch(&doSegmentsOutput),"Output a posteriori probability for each class")
		//("pv", bpo::bool_switch(&useExplicitPVE), "Use explicit PVE Gaussian Model between tissues")
		("output-stats", bpo::bool_switch(&doOutputStats),"output classes statistics to CSV file")
		("output-steps", bpo::bool_switch(&doOutputSteps), "Output intermediate segmentation steps")
		("normalize-off,N", bpo::bool_switch(&skipNormalization), "Do not normalize input's intensity range")
		("brain-mask-th,t",bpo::value < ProbabilityPixelType > (&mask_th)->default_value(0.0), "mask probability threshold")
		("version,v", "show tool version");

	bpo::options_description kmeans_desc("Kmeans options");
	kmeans_desc.add_options()
		("bucket-size", bpo::value< unsigned int >(&userBucketSize), "bucket size for K-means operation");

	bpo::options_description em_desc("Expectation-Maximization options");
	em_desc.add_options()
		("priors,P", bpo::value< std::vector< std::string > >(&priors)->multitoken(),"add prior to list of atlases for initializing segmentation")
		("atlas-threshold",bpo::value < ProbabilityPixelType > (&atlas_th)->default_value(DEFAULT_ATLAS_TH), "threshold for atlases")
		("em-iterations", bpo::value<unsigned int>(&emIterations)->default_value(DEFAULT_MAX_ITER), "maximum number of iterations");

	bpo::options_description bias_desc("Bias estimator options");
	bias_desc.add_options()
		("bias-skip", bpo::bool_switch(&skipBias), "Do not estimate Bias field")
		("bias-output", bpo::bool_switch(&doBiasOutput), "Output estimated Bias field")
		("bias-corrected-output", bpo::bool_switch(&doCorrectedOutput), "Output corrected input images with estimated Bias field");

	bpo::options_description mrf_desc( "MRF Segmentation options" );
	mrf_desc.add_options()
		("mrf-lambda,l", bpo::value<float>(&lambda1)->default_value(DEFAULT_LAMBDA),"Regularization weighting. The higher this value is, the higher smoothing. You may use a value around 0.3-1.0 for typical brain images")
		("mrf-minimization,m", bpo::value < std::string > (&s_minimization)->default_value(DEFAULT_MRF_ALG), "Minimization algorithm")
		("mrf-energy-model,e",bpo::value < std::string > (&mrfModelFile), "Energy Model matrix, basic Pott's Model used if missing" )
		("mrf-iterations", bpo::value<unsigned int>(&mrfIterations)->default_value(DEFAULT_MRF_ITERATIONS),"MRF re-estimation iterations")
		("mrf-skip,S", bpo::bool_switch(&skipMRF),"Skip MRF step")
		("mrf-pve", bpo::bool_switch(&usePVE), "Compute PVE classes")
		("mrf-external-lambda", bpo::value<float>(&lambda2)->default_value(1.0),"External field energy weighting. The higher this value is, the higher impact from the external field")
		("mrf-external-field,E", bpo::value< std::vector< std::string > >(&geometricTerm)->multitoken(),"External field maps that manipulate the dataterm in MRF energy function")
		("mrf-output-maps", bpo::bool_switch(&doOutputMRFMaps), "Output GC probabilities and energy maps")
		("mrf-output-it", bpo::bool_switch(&doOutputMRFIterations), "Output intermediate segmentation steps");


	bpo::options_description all("Usage");
	all.add(general).add(kmeans_desc).add(bias_desc).add(em_desc).add(mrf_desc);

	bpo::variables_map vmap;
	bpo::store(bpo::command_line_parser(argc, argv).options(all).run(), vmap);


	if ( vmap.count("version")) {
			std::cout << "MBIS Segmentation tool. Version " << MBIS_VERSION_MAJOR << "." << MBIS_VERSION_MINOR << "-" << MBIS_RELEASE << "." << std::endl;
			std::cout << "--------------------------------------------------------"<< std::endl;
			std::cout << "Copyright (c) 2012, [email protected] (Oscar Esteban)"<< std::endl; 
			std::cout << "with Signal Processing Lab 5, EPFL (LTS5-EPFL)"<< std::endl;
			std::cout << "and Biomedical Image Technology, UPM (BIT-UPM)"<< std::endl;
			std::cout << "All rights reserved."<< std::endl;

			return 0;
	}

	if ( vmap.empty() || vmap.count("help")) {
		std::cout << all << std::endl;
		return 0;
	}

	try {
		bpo::notify(vmap);
	} catch (boost::exception_detail::clone_impl<
			boost::exception_detail::error_info_injector<
					boost::program_options::required_option> > &err) {
		std::cout << "Error parsing options:" << err.what()
				<< std::endl;
		std::cout << std::endl << all << std::endl;
		return EXIT_FAILURE;
	}

	std::cout << std::endl << "Set-up step --------------------------------------------" << std::endl;

	ProbabilityImagePointer bm;
	InputVector input;
	PriorsVector atlas;
	ClassifiedImageType::Pointer solution;
	bool useFileMask = vmap.count("brain-mask") && bfs::exists(bmImageName);
	bool useImplicitMasks = channelsAreMasked && !useFileMask;

	if( useFileMask ) {
		ProbabilityImageReader::Pointer r = ProbabilityImageReader::New();
		r->SetFileName(bmImageName);
		r->Update();

		try {
			bm = r->GetOutput();
		} catch (...) {
			std::cout << "Error reading brain mask" << std::endl;
			return EXIT_FAILURE;
		}

		StatisticsImageFilterType::Pointer calc = StatisticsImageFilterType::New();
		calc->SetInput(bm);
		calc->Update();
		ProbabilityPixelType max = calc->GetMaximum();

		if (max > 1.0 ){
			ProbabilityPixelType min = calc->GetMinimum();

			IntensityWindowingImageFilterType::Pointer intensityFilter = IntensityWindowingImageFilterType::New();
			intensityFilter->SetInput( bm );
			intensityFilter->SetWindowMaximum( max );
			intensityFilter->SetWindowMinimum( min );
			intensityFilter->SetOutputMaximum( 1.0 );
			intensityFilter->SetOutputMinimum( 0.0 );
			intensityFilter->Update();
			bm = intensityFilter->GetOutput();
		}

		std::cout << "\t* Mask: read from file " << bmImageName << ".";

		if ( mask_th != 0.0 ) {
			ThresholdImageFilterType::Pointer th = ThresholdImageFilterType::New();
			th->SetInput( bm );
			th->ThresholdBelow( mask_th );
			th->Update();
			bm = th->GetOutput();
			std::cout << " Mask Threshold = " << mask_th << ".";
		}

		std::cout << std::endl;

	} else {
		if ( useImplicitMasks ) {
			std::cout << "\t* Mask: channels are masked." << std::endl;
		} else {
			std::cout << "\t* Mask: not requested." << std::endl;
		}
	}

	std::cout << "\t* Inputs normalization is " << ((!skipNormalization)?"ON":"OFF") << std::endl;

	for (vector<string>::iterator it = channels.begin(); it != channels.end(); it++) {
		ChannelReader::Pointer r = ChannelReader::New();
		r->SetFileName( *it );
		ChannelPointer p = r->GetOutput();
		r->Update();

		ChannelPixelType max = itk::NumericTraits< ChannelPixelType >::max();
		ChannelPixelType min = 0.0;
		ChannelPixelType absMin = 0.0;

		if ( bm.IsNotNull() ) {
			ProbabilityPixelType* mBuff = bm->GetBufferPointer();
			ChannelPixelType* cBuff = r->GetOutput()->GetBufferPointer();
			size_t nPix = bm->GetLargestPossibleRegion().GetNumberOfPixels();
			std::vector< ChannelPixelType > sample;

			for( size_t i = 0; i<nPix; i++ ) {
				if ( *(mBuff+i) > 0 ) {
					sample.push_back( *(cBuff+i) );
				}
			}
			std::sort( sample.begin(), sample.end() );
			max = sample[ (size_t) ((sample.size()-1)*0.98) ];
			min = sample[ (size_t) ((sample.size()-1)*0.02) ];
			absMin = sample[0];
		} else {
			StatisticsChannelFilterType::Pointer calc = StatisticsChannelFilterType::New();
			calc->SetInput(p);
			calc->Update();
			max = calc->GetMaximum();
			min = calc->GetMinimum();
			absMin = min;
		}

		if( !skipNormalization ) {
			double factor = NORM_MAX_INTENSITY / (max - min);
			double constant = - factor * absMin;

			if ( factor!= 1 ) {
				typename MultiplyFilter::Pointer multiplier = MultiplyFilter::New();
				multiplier->SetInput( p );
				multiplier->SetConstant( factor );
				multiplier->Update();
				p = multiplier->GetOutput();
			}

			if ( constant!= 0 ) {
				typename AddConstantFilter::Pointer adder = AddConstantFilter::New();
				adder->SetInput( p );
				adder->SetConstant( - constant );
				adder->Update();
				p = adder->GetOutput();
			}

			dataOffsets.push_back( constant );
			dataFactors.push_back( factor );

			if ( bm.IsNotNull() ) {
				ChannelImageType::DirectionType dir = bm->GetDirection();
				p->SetDirection( dir );
				p->SetOrigin( bm->GetOrigin() );

				MaskChannelFilterType::Pointer m = MaskChannelFilterType::New();
				m->SetInput( p );
				m->SetMaskImage( bm );
				m->Update();
				p = m->GetOutput();
			}


			if( doOutputSteps ) {
				itk::ImageFileWriter< ChannelImageType >::Pointer wc = itk::ImageFileWriter< ChannelImageType >::New();
				wc->SetInput( p );
				std::stringstream ss;
				ss << outPrefix << "_normin_" << input.size() << "." << outExt;
				wc->SetFileName( ss.str() );
				wc->Update();
			}
		}

		InputComponentConstPointer im;

		typename ChannelToComponentCaster::Pointer c = ChannelToComponentCaster::New();
		c->SetInput(p);
		c->Update();
		im = c->GetOutput();

		input.push_back( im );

		std::cout << "\t* Channel [" << std::setw(2) << input.size() << "] read: " << (*it) << std::endl;
	}

	if ( useImplicitMasks ) {
		bm = ProbabilityImageType::New();
		bm->SetRegions( input[0]->GetLargestPossibleRegion() );
		bm->CopyInformation( input[0] );
		bm->Allocate();
		bm->FillBuffer( 1.0 );
		bm->Update();

		ProbabilityPixelType* buffer = bm->GetBufferPointer();
		size_t numberOfPixels = bm->GetLargestPossibleRegion().GetNumberOfPixels();

		for ( size_t i = 0; i < input.size(); i++) {
			const PixelType* buffer2 = input[i]->GetBufferPointer();

			for( size_t offset = 0; offset < numberOfPixels; offset++ ) {
				if( *( buffer + offset ) > 0.0 ) {
					*( buffer + offset ) = PixelType ( *( buffer2 + offset ) > 1e-5);
				}
			}
		}


		if( doOutputSteps ) {
			itk::ImageFileWriter< ProbabilityImageType >::Pointer wc = itk::ImageFileWriter< ProbabilityImageType >::New();
			wc->SetInput( bm );
			std::stringstream ss;
			ss << outPrefix << "_mask." << outExt;
			wc->SetFileName( ss.str() );
			wc->Update();
		}
	}


	unsigned int init_mode = modes_map[s_mode];
	unsigned int nComponents = input.size();
	unsigned int nElements = nComponents * (1+nComponents);

	if( priors.size() > 0 ) {
		if (init_mode== KMEANS ) init_mode = MANUAL;
		if (init_mode == KMEANS_EM ) init_mode = EM;

		for (vector<string>::iterator it = priors.begin(); it != priors.end(); it++) {
			ProbabilityImageReader::Pointer r = ProbabilityImageReader::New();
			r->SetFileName( *it );
			ProbabilityImageType::ConstPointer p = r->GetOutput();
			r->Update();

			StatisticsImageFilterType::Pointer calc = StatisticsImageFilterType::New();
			calc->SetInput(p);
			calc->Update();
			ProbabilityPixelType max = calc->GetMaximum();

			if (max > 1.0 ){
				ProbabilityPixelType min = calc->GetMinimum();

				IntensityWindowingImageFilterType::Pointer intensityFilter = IntensityWindowingImageFilterType::New();
				intensityFilter->SetInput( p );
				intensityFilter->SetWindowMaximum( max );
				intensityFilter->SetWindowMinimum( min );
				intensityFilter->SetOutputMaximum( 1.0 );
				intensityFilter->SetOutputMinimum( 0.0 );
				intensityFilter->Update();
				p = intensityFilter->GetOutput();
			}
			atlas.push_back(p);

			std::cout << "\t* Prior [" << std::setw(2) << atlas.size() << "] read: " << (*it) << std::endl;

			ParameterEstimator::Pointer est = ParameterEstimator::New();
			est->SetInputVector( input );
			est->SetPrior( p );
			if ( bm.IsNotNull() ) {
				est->SetMaskImage( bm );
			}

			est->Update();
			initialParameters.push_back( est->GetOutputParameters() );
		}
	}

	if ( bfs::exists(initFile)) {
		if (init_mode== KMEANS ) init_mode = MANUAL;
		if (init_mode == KMEANS_EM ) init_mode = EM;

		std::cout << "\t* Parsing tissue parameters file: " << initFile << std::endl;
		initialParameters = ReadParametersFile(initFile);

		for ( ParametersVectorType::iterator it = initialParameters.begin(); it!=initialParameters.end(); it++) {
			size_t n = (*it).size();
			if ( n != nElements ) {
				std::cerr << "Parameters file is incorrect or badly interpreted" << std::endl;
			}

			if ( !skipNormalization ) {
				for( size_t i = 0; i<nComponents; i++ ) {
					(*it)[i] *= dataFactors[i];
					(*it)[i] += dataOffsets[i];
				}

				for( size_t i = nComponents; i<n; i++ ) {
					(*it)[i] = dataFactors[i%nComponents] * (*it)[i];
				}
			}
		}

		useFile = true;

		std::cout << "\t* Manual Parameters: " << std::endl;
		for (size_t i = 0; i<initialParameters.size(); i++)
			std::cout << "\t\t" << initialParameters[i] << std::endl;
	}

	if ( bfs::exists(initMeansFile)) {
		std::cout << "\t* Parsing tissue means file: " << initMeansFile << std::endl;

		initialParameters = ReadParametersFile( initMeansFile );

		for ( ParametersVectorType::iterator it = initialParameters.begin(); it!=initialParameters.end(); it++) {
			size_t n = (*it).size();

			if ( n != nComponents ) {
				std::cerr << "Means file is incorrect or badly interpreted" << std::endl;
			}


			if ( !skipNormalization ) {
				for( size_t i = 0; i<n; i++ ) {
					(*it)[i] *= dataFactors[i];
					(*it)[i] += dataOffsets[i];
				}
			}
		}

		useFile = true;

		std::cout << "\t* Manual Parameters: " << std::endl;
		for (size_t i = 0; i<initialParameters.size(); i++)
			std::cout << "\t\t" << initialParameters[i] << std::endl;
	}

	EMFilter::Pointer em_filter;
	KMeansFilter::Pointer kmeans;


	if (init_mode == KMEANS || init_mode == KMEANS_EM ) {
		std::cout << std::endl << "Kmeans step --------------------------------------------" << std::endl;
		kmeans = KMeansFilter::New();
		kmeans->SetInputVector( input );
		if ( bm.IsNotNull() ) kmeans->SetMaskImage( bm );
		kmeans->SetNumberOfClasses(nClasses);
		if(vmap.count("bucket-size")) {
			kmeans->SetUserBucketSize(userBucketSize);
		}

		if( useFile ) {
			kmeans->SetInitialParameters( initialParameters );
		}

		kmeans->Compute();
		initialParameters = kmeans->GetOutputParameters();

		if (doOutputStats) {
			stringstream s;
			s << outPrefix << "_stats_kmeans.csv";
			std::ofstream outputCSVfile ( s.str().c_str() );
			for ( unsigned int i = 0; i < initialParameters.size(); i++)
				outputCSVfile << initialParameters[i] << "\n";
			outputCSVfile.close();
		}
		kmeans->Update();
	}

	// Check for sanity initial parameters
	if( initialParameters.size()!=nClasses ) {
		std::cerr << "Error: initial parameters size (" << initialParameters.size() << ") doesn't match number of classes (" << (int) nClasses << std::endl;
	} else if ( initialParameters[0].size() != nElements ) {
		typename MLClassifierFilter::Pointer ml_classifier = MLClassifierFilter::New();
		ml_classifier->SetInputVector( input );
		if ( bm.IsNotNull() ) ml_classifier->SetMaskImage(bm);
		ml_classifier->SetParameters( initialParameters );
		ml_classifier->Update();
		solution = ml_classifier->GetOutput();

		if ( doOutputSteps ) {
			ClassifiedImageWriter::Pointer w = ClassifiedImageWriter::New();
			w->SetInput( solution );
			w->SetFileName(outPrefix + "_means." + outExt );
			w->Update();
		}

		ProbabilityImagePointer unoImage = ProbabilityImageType::New();
		unoImage->SetRegions( input[0]->GetLargestPossibleRegion() );
		unoImage->CopyInformation( input[0] );
		unoImage->Allocate();
		unoImage->FillBuffer( 1.0 );
		unoImage->Update();

		// Initialize Covariance matrix --------------------------------------
		ParameterEstimator::Pointer est = ParameterEstimator::New();
		est->SetInputVector( input );

		typedef itk::LabelImageToLabelMapFilter< ClassifiedImageType > ClassifiedToLabelMapFilter;
		typedef typename ClassifiedToLabelMapFilter::OutputImageType LabelMap;
		typedef itk::LabelMapMaskImageFilter< LabelMap, ProbabilityImageType > LabelMapMaskFilter;

		unsigned int maskOffset = (unsigned int) bm.IsNotNull();

	    for ( typename ClassifiedImageType::PixelType i = 0 ; i < nClasses ; i++ ) {
			typename ClassifiedToLabelMapFilter::Pointer lfilter = ClassifiedToLabelMapFilter::New();
			lfilter->SetInput( solution );
			lfilter->Update();

			typename LabelMapMaskFilter::Pointer lmask = LabelMapMaskFilter::New();
			lmask->SetInput1( lfilter->GetOutput() );
			lmask->SetInput2( unoImage );
			lmask->SetLabel( i + maskOffset );
			lmask->Update();

			est->SetPrior( lmask->GetOutput());
			est->Update();
			initialParameters[i] = est->GetOutputParameters();
	    }
		// End initialize covariance matrix -------------------------------------------
	}

	if (init_mode == EM  || init_mode == KMEANS_EM ) {
		std::cout << std::endl << "E-M Step -----------------------------------------------" << std::endl;
		em_filter = EMFilter::New();
		em_filter->SetMaskImage( bm );
		em_filter->SetNumberOfClasses( nClasses );
		em_filter->SetMaximumIteration( emIterations );
		em_filter->SetMaxBiasEstimationIterations( 5 );
		em_filter->SetInputVector( input );
		em_filter->SetInitialParameters( initialParameters );
		em_filter->SetUseExplicitPVModel( useExplicitPVE );
		em_filter->SetUseBiasCorrection( !skipBias );

		if ( atlas.size() != 0 ) {
			em_filter->SetPriors( atlas );
			em_filter->SetUsePriorProbabilityImages( true );
		}

		em_filter->Update();

		// TODO change to GetModelParameters()
		initialParameters = em_filter->GetInitialParameters();
		solution = em_filter->GetOutput();

		if ( doOutputSteps || skipMRF ) {
			ClassifiedImageWriter::Pointer w = ClassifiedImageWriter::New();
			w->SetInput( solution );
			w->SetFileName(outPrefix + "_em." + outExt );
			w->Update();
		}

		//
		// Output file with initial stats if switch is true
		//
		if (doOutputStats) {
			stringstream s;
			s << outPrefix << "_stats_em.csv";
			std::ofstream outputCSVfile ( s.str().c_str() );
			for ( unsigned int i = 0; i < initialParameters.size(); i++)
				outputCSVfile << initialParameters[i] << "\n";
			outputCSVfile.close();
		}

		if( em_filter->GetUseBiasCorrection() ) {
			typedef typename EMFilter::EstimatorType::InputVectorImageType  VectorImage;
			typedef typename itk::ImageFileWriter< ChannelImageType > ChannelWriter;
			typedef itk::VectorIndexSelectionCastImageFilter< VectorImage, ChannelImageType> SelectorType;
			typename VectorImage::ConstPointer vec = em_filter->GetEstimator()->GetCorrectedInput();
			for( int channel = 0; channel< input.size(); channel++ ) {
				typename SelectorType::Pointer channelSelector = SelectorType::New();
				channelSelector->SetInput( vec );
				channelSelector->SetIndex( channel );
				channelSelector->Update();
				channelSelector->GetOutput()->SetRegions( vec->GetRequestedRegion() );
				input[channel] = channelSelector->GetOutput();

				if ( doCorrectedOutput ) {
					char name[50];
					sprintf(name, "_corrected_ch%02d.%s" , channel, outExt.c_str() );
					typename ChannelWriter::Pointer chW = ChannelWriter::New();
					chW->SetInput(input[channel]);
					chW->SetFileName( outPrefix + name );
					chW->Update();
				}
			}

			if( doBiasOutput ) {
				typedef typename EMFilter::EstimatorType::InputVectorImageType  VectorImage;
				typedef typename itk::ImageFileWriter< ChannelImageType > ChannelWriter;
				typename VectorImage::ConstPointer bias = em_filter->GetEstimator()->GetCurrentBias();
				for( int channel = 0; channel< input.size(); channel++ ) {
					typename SelectorType::Pointer channelSelector = SelectorType::New();
					channelSelector->SetInput( bias );
					channelSelector->SetIndex( channel );
					channelSelector->Update();
					channelSelector->GetOutput()->SetRegions( bias->GetRequestedRegion() );

					char name[50];
					sprintf(name, "_bias_ch%02d.%s" , channel, outExt.c_str() );
					typename ChannelWriter::Pointer chW = ChannelWriter::New();
					chW->SetInput(channelSelector->GetOutput());
					chW->SetFileName( outPrefix + name );
					chW->Update();
				}
			}

		}
	}

	//
	// MRF Segmentation
	//

	if( !skipMRF ) {
		std::cout << std::endl << "MRF Step -----------------------------------------------" << std::endl;
		MRFFilter::Pointer mrf = MRFFilter::New();
		mrf->SetUseExplicitPVModel( useExplicitPVE );
		mrf->SetNumberOfClasses( nClasses );
		mrf->SetMaskImage( bm );
		mrf->SetInputVector( input );
		mrf->SetLambda( lambda1 );
		mrf->SetExternalLambda( lambda2 );
		mrf->SetUseOutputPriors( doSegmentsOutput );
		mrf->SetInitialParameters( initialParameters );
		mrf->SetMRFIterations( mrfIterations );
		mrf->SetMinimizationMode( minimiz_map[s_minimization] );
		mrf->SetOutputPrefix( outPrefix );

		if( doOutputMRFIterations ) {
			typedef itk::SimpleMemberCommand< MRFFilter >  ObserverType;
			ObserverType::Pointer obs = ObserverType::New();
			obs->SetCallbackFunction( mrf, &MRFFilter::WriteIteration );
			mrf->AddObserver( itk::IterationEvent(), obs );
		}


		if( doOutputMRFMaps ) {
			typedef itk::SimpleMemberCommand< MRFFilter >  ObserverType;
			ObserverType::Pointer obs = ObserverType::New();
			obs->SetCallbackFunction( mrf, &MRFFilter::WriteMaps );
			mrf->AddObserver( itk::IterationEvent(), obs );
		}

		if ( doOutputSteps && init_mode == NONE ) {
			EMFilter::Pointer em_classifier = EMFilter::New();
			em_classifier->SetMaskImage( bm );
			em_classifier->SetNumberOfClasses( nClasses );
			em_classifier->SetInputVector( input );
			em_classifier->SetInitialParameters( initialParameters );
			em_classifier->SetUseExplicitPVModel( useExplicitPVE );
			em_classifier->SetUseOnlyClassify(true);
			em_classifier->Update();
			ClassifiedImageWriter::Pointer w = ClassifiedImageWriter::New();
			w->SetInput( em_classifier->GetOutput() );
			w->SetFileName(outPrefix + "_mrf_initialization." + outExt );
			w->Update();

		}

		if( bfs::exists( mrfModelFile ) ) {
			std::cout << "\t* Loading Energy Model Matrix: " << mrfModelFile << std::endl;
			mrf->SetMatrixFile( mrfModelFile );
		}

		for (vector<string>::iterator it = geometricTerm.begin(); it != geometricTerm.end(); it++) {
			if( bfs::exists(*it) ) {
				size_t label = (it - geometricTerm.begin()) + 1;

				ProbabilityImageReader::Pointer r = ProbabilityImageReader::New();
				r->SetFileName( *it );
				ProbabilityImageType::Pointer p = r->GetOutput();
				r->Update();

				mrf->SetSpatialEnergyMap(label, p );


				std::cout << "\t* Geometrical constraint [" << std::setw(2) << label << "] read: " << (*it) << std::endl;
			}
		}

		mrf->Update();
		solution = mrf->GetOutput();

		ClassifiedImageWriter::Pointer w2 = ClassifiedImageWriter::New();
		w2->SetInput( solution );
		w2->SetFileName(outPrefix + "_mrf." + outExt );
		w2->Update();

		if ( doSegmentsOutput ) {
			for ( unsigned int i = 1; i<=nClasses; i++ ) {
				ProbabilityImageWriter::Pointer wProb = ProbabilityImageWriter::New();
				wProb->SetInput( mrf->GetPosteriorProbabilityImage(i) );
				char name[50];
				sprintf(name, "_mrf_seg%02d.%s" , i, outExt.c_str() );
				wProb->SetFileName( outPrefix + name );
				wProb->Update();
			}

		}

		if (doOutputStats) {
			initialParameters = mrf->GetInitialParameters();
			stringstream s;
			s << outPrefix << "_stats_final.csv";
			std::ofstream outputCSVfile ( s.str().c_str() );
			for ( unsigned int i = 0; i < initialParameters.size(); i++)
				outputCSVfile << initialParameters[i] << "\n";
			outputCSVfile.close();
		}
	}


	return EXIT_SUCCESS;
}
Ejemplo n.º 25
0
void Parameters::parse_options(int argc, char* argv[])
{
    unsigned log_level = 2;
    std::string log_file;

    po::options_description general("General options");
    auto general_add = general.add_options();
    general_add("version,V", "print version string");
    general_add("help,h", "produce help message");
    general_add("log-level,l", po::value<unsigned>(&log_level),
                "set the log level (default:2, all:0)");
    general_add("log-file,L", po::value<std::string>(&log_file),
                "name of target log file");
    general_add("maximum-number,n", po::value<uint64_t>(&maximum_number),
                "set the maximum number of microslices to process (default: "
                "unlimited)");

    po::options_description source("Source options");
    auto source_add = source.add_options();
    source_add("shm-channel,c", po::value<size_t>(&shm_channel),
               "use given shared memory channel as data source");
    source_add("input-shm,I", po::value<std::string>(&input_shm),
               "name of a shared memory to use as data source");
    source_add("input-archive,i", po::value<std::string>(&input_archive),
               "name of an input file archive to read");

    po::options_description opmode("Operation mode options");
    auto opmode_add = opmode.add_options();
    opmode_add("debugger,d", po::value<bool>(&debugger)->implicit_value(true),
             "enable/disable debugger (raw message unpacking and printout)");
    opmode_add("sorter,s", po::value<bool>(&sorter)->implicit_value(true),
             "enable/disable sorting by epoch in epoch buffer for sink(s) (build output ms from epochs)");
    opmode_add("ep_in_ms,N", po::value<uint32_t>(&epoch_per_ms),
             "Number of epochs stored in each output MS in case sorter is used (default:1)");
    opmode_add("sortmesg", po::value<bool>(&sortmesg)->implicit_value(true),
             "enable/disable message sorting inside epoch buffer before creation of new ms");

    po::options_description sink("Sink options");
    auto sink_add = sink.add_options();
    sink_add("dump_verbosity,v", po::value<size_t>(&dump_verbosity),
             "set output debug dump verbosity");
    sink_add("output-shm,O", po::value<std::string>(&output_shm),
             "name of a shared memory to write to");
    sink_add("output-archive,o", po::value<std::string>(&output_archive),
             "name of an output file archive to write");

    po::options_description desc;
    desc.add(general).add(source).add(opmode).add(sink);

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help") != 0u) {
        std::cout << "ngdpbtool, git revision " << g_GIT_REVISION << std::endl;
        std::cout << desc << std::endl;
        exit(EXIT_SUCCESS);
    }

    if (vm.count("version") != 0u) {
        std::cout << "ngdpbtool, git revision " << g_GIT_REVISION << std::endl;
        exit(EXIT_SUCCESS);
    }

    logging::add_console(static_cast<severity_level>(log_level));
    if (vm.count("log-file")) {
        L_(info) << "Logging output to " << log_file;
        logging::add_file(log_file, static_cast<severity_level>(log_level));
    }

    size_t input_sources = vm.count("input-archive") + vm.count("input-shm");
    if (input_sources == 0) {
        throw ParametersException("no input source specified");
    }
    if (input_sources > 1) {
        throw ParametersException("more than one input source specified");
    }
}
Ejemplo n.º 26
0
/*
 * main thread/process (parent)
 * @param structure with parsed arguments
 * @return 0 if OK, otherwise some error
 */
int general(const t_arg *args)
{
  t_err err = ERR_OK;
  FILE *fw = NULL;
  pid_t *pid = NULL;      /* array with PIDs */
  struct st_shmid shmid;  /* struct with shared memory segments */

  /* get mem for array of PIDs */
  if ((pid = calloc((args->n + 1), sizeof(pid_t))) == NULL)
  {
    printErr(ERR_OUT_OF_MEM, "");
    return ERR_OUT_OF_MEM;
  }

  /* get shared memory and save IDs to the structure */
  if ((err = getshm(&shmid, args)) != ERR_OK)
  {
    free(pid);
    return err;
  }

  /* we use NULL as idicator of stdout */
  if (args->file != NULL)
  {
    /* open file for writing */
    if ((fw = fopen(args->file, "w")) == NULL)
    {
      ungetshm(&shmid);
      free(pid);
      printErr(ERR_FILE_WRITE, args->file);
      return ERR_FILE_WRITE;
    }
  }

  /* reset errno */
  errno = 0;

  /* mount shm segment */
  struct st_queue *record = (struct st_queue *)shmat(shmid.record, NULL, 0);

  if (errno)
  {
    if (fw != NULL) fclose(fw);
    shmdt((void *)record);
    ungetshm(&shmid);
    free(pid);
    printErr(ERR_SHM_ATTACH, "shmid.record");
    return ERR_SHM_ATTACH;
  }

  record->max     = args->q; /* chairs in waiting room */
  record->pos_st  = -1;      /* reserved value */
  record->pos_ret = -1;      /* reserved value */

  /* unmount shm segment */
  shmdt((void *)record);

  /* create 1 semaphore with rw rights for the creator */
  if ((semid = semget(ftok(args->path, 'z'), 1,
                      IPC_CREAT | IPC_EXCL | 0600)) == -1)
  {
    if (fw != NULL) fclose(fw);
    shmdt((void *)record);
    ungetshm(&shmid);
    free(pid);
    printErr(ERR_SEM_INIT, "");
    return ERR_SEM_INIT;
  }

  /* semaphore initialization */
  unsigned short int semset[1];  /* use 1 semaphore in set */
  semset[0] = 1;                 /* semaphore "index" number (not ID) */

  union semuni arg =
  {
    .array = semset,
  };

  /* set semaphore options in the whole semset */
  semctl(semid, 0, SETALL, arg);

  /* reset user signals (childs "inherit") */
  sigset_t block_mask;      /* create new mask */
  sigfillset(&block_mask);  /* fulfill with every signal */

  struct sigaction sigact =
  {
    .sa_handler = void_fn,  /* do nothing */
    .sa_mask    = block_mask,
    .sa_flags   = 0,
  };

  sigaction(SIGUSR1, &sigact, NULL);  /* apply the new structure */
  sigaction(SIGUSR2, &sigact, NULL);  /* apply the new structure */

  /* generate pseudo-random sequence */
  srand(getpid());

  int i = 0;
  int j = args->n;

  /* give birth to the barber and all customers */
  for (i = 0; i <= args->n; i++)
  {
    /* sleep for a few miliseconds */
    if (i != 0 && args->genc > 0) msleep(rand()%args->genc);

    /* child */
    if ((pid[i] = fork()) == 0)
    {
      if (i == 0)
        process_barber(fw, &shmid, args);
      else
        process_customer(fw, &shmid, pid[0], i);
    }
    /* something bad happened */
    else if (pid[i] == -1)
    {
      err = ERR_FORK;

      for (j = 1; j < i; j++)
        kill(pid[j], SIGKILL);  /* no more interest in the return value */

      break;
    }
  } /* for(;;) */

  /* wait until all customers are gone */
  for (i = 1; i <= j; i++)
  {
    if (pid[i] != 0) waitpid(pid[i], NULL, 0);
  }

  /* close the barbershop forever and kill the barber */
  kill(pid[0], SIGKILL);

  /* wait until barber definitely dies */
  waitpid(pid[0], NULL, 0);

  /* remove semaphore */
  semctl(semid, 1, IPC_RMID, arg);

  /* deallocate shm segments */
  ungetshm(&shmid);

  /* deallocate pid array */
  free(pid);

  /* close file if any */
  if (fw != NULL)
    if (fclose(fw) == EOF) printErr(err = ERR_FILE_CLOSE, args->file);

  return err;  /* exit parent */
}

int main(int argc, char *argv[])
{
  t_err errnum = ERR_OK;

  /* init the argument structure */
  t_arg args =
  {
    .q    = 0,
    .genc = 0,
    .genb = 0,
    .n    = 0,
    .path = NULL,
    .file = NULL,  /* NULL means output to stdout (instead of file) */
  };

  /* transform arguments into structure in memory
     and check them for compatibility */
  if ((errnum = parseArgs(&args, argc, argv)) != ERR_OK)
    return errnum;

  if ((errnum = general(&args)) != ERR_OK)
    return errnum;

  return EXIT_SUCCESS;
} // main()
Ejemplo n.º 27
0
/**
 * Functionality for keys that are held down.
 */
void keyActions() {
   /* GENERAL */
   if (key_states['K']) {
      (d_time < 30) ? d_time += MEDIUM_CHANGE : 0;
   }
   else if (key_states['k']) {
      if (d_time > 20) { d_time -= MEDIUM_CHANGE * 3; }
      else if (d_time > 3) { d_time -= MEDIUM_CHANGE; }
   }

   /* CAMERA */
   if (key_states['='] || key_states['+']) {
      cam.spin_speed += 0.03;
   }
   if (key_states['-'] || key_states['_']) {
      cam.spin_speed -= 0.03;
   }

   /* PARTICLES */
   if (key_states['|'] || key_states['\\']) { general((char*)"reset"); }
   if (key_states['m']) { up((char*)"source_x"); }
   if (key_states['M']) { down((char*)"source_x"); }
   if (key_states[',']) { up((char*)"source_y"); }
   if (key_states['<']) { down((char*)"source_y"); }
   if (key_states['.']) { up((char*)"source_z"); }
   if (key_states['>']) { down((char*)"source_z"); }
   if (key_states['a']) { up((char*)"freq"); }
   if (key_states['A']) { down((char*)"freq"); }
   if (key_states['s']) { up((char*)"size_variance"); }
   if (key_states['S']) { down((char*)"size_variance"); }
   if (key_states['c']) { up((char*)"color_variance"); }
   if (key_states['C']) { down((char*)"color_variance"); }
   if (key_states['l']) { up((char*)"lifetime_variance"); }
   if (key_states['L']) { down((char*)"lifetime_variance"); }
   if (key_states['v']) { up((char*)"velocity_variance"); }
   if (key_states['V']) { down((char*)"velocity_variance"); }
   if (key_states['u']) { up((char*)"position_x_variance"); }
   if (key_states['U']) { down((char*)"position_x_variance"); }
   if (key_states['i']) { up((char*)"position_y_variance"); }
   if (key_states['I']) { down((char*)"position_y_variance"); }
   if (key_states['o']) { up((char*)"position_z_variance"); }
   if (key_states['O']) { down((char*)"position_z_variance"); }
   if (key_states['x']) { up((char*)"velocity_x"); }
   if (key_states['X']) { down((char*)"velocity_x"); }
   if (key_states['y']) { up((char*)"velocity_y"); }
   if (key_states['Y']) { down((char*)"velocity_y"); }
   if (key_states['z']) { up((char*)"velocity_z"); }
   if (key_states['Z']) { down((char*)"velocity_z"); }
   if (key_states['p']) { up((char*)"force_x"); }
   if (key_states['P']) { down((char*)"force_x"); }
   if (key_states['[']) { up((char*)"force_y"); }
   if (key_states['{']) { down((char*)"force_y"); }
   if (key_states[']']) { up((char*)"force_z"); }
   if (key_states['}']) { down((char*)"force_z"); }
   if (key_states['j']) { up((char*)"gravity"); }
   if (key_states['J']) { down((char*)"gravity"); }
   if (key_states['q']) { up((char*)"mass"); }
   if (key_states['Q']) { down((char*)"mass"); }
   if (key_states['w']) { up((char*)"lifetime"); }
   if (key_states['W']) { down((char*)"lifetime"); }
   if (key_states['e']) { up((char*)"end_size"); }
   if (key_states['E']) { down((char*)"end_size"); }
   if (key_states['d']) { up((char*)"size"); }
   if (key_states['D']) { down((char*)"size"); }
   if (key_states['r']) { up((char*)"red"); }
   if (key_states['R']) { down((char*)"red"); }
   if (key_states['g']) { up((char*)"green"); }
   if (key_states['G']) { down((char*)"green"); }
   if (key_states['b']) { up((char*)"blue"); }
   if (key_states['B']) { down((char*)"blue"); }
   if (key_states['t']) { up((char*)"end_red"); }
   if (key_states['T']) { down((char*)"end_red"); }
   if (key_states['h']) { up((char*)"end_green"); }
   if (key_states['H']) { down((char*)"end_green"); }
   if (key_states['n']) { up((char*)"end_blue"); }
   if (key_states['N']) { down((char*)"end_blue"); }
   if (key_states[';']) { up((char*)"mesh_size"); }
   if (key_states[':']) { down((char*)"mesh_size"); }
}
Ejemplo n.º 28
0
int main(int argc, char **argv)
{


    int rank = 0;
    int process_count = 1;
    int reader_count = 1;
    int buffer_size = 10000;
    int is_mpi = 0;
    mpi_times *timer = NULL;
    // end, mpi variables
    clock_t t0, t1;

    // parameters
    char inputName[1024] = {0};
    char inputURL[2048] = {0};
    char outputName[1024] = {0};

    int input_format = INPUT_LAS;
    int interpolation_mode = INTERP_AUTO;
    int output_format = 0;
    unsigned int type = 0x00000000;
    double GRID_DIST_X = 6.0;
    double GRID_DIST_Y = 6.0;
    double searchRadius = (double) sqrt(2.0) * GRID_DIST_X;
    int window_size = 0;

    // argument processing..
    po::options_description general("General options"),
    df("Data file"),
    ot("Output Type"),
    res("Resolution"),
    nf("Null Filling"),
    desc;

    general.add_options()
    ("help", "produce a help message")
    ("output_file_name,o", po::value<std::string>(), "required. name of output file without extension, i.e. if you want the output file to be test.asc, this parameter shoud be \"test\"")
    ("search_radius,r", po::value<float>(), "specifies the search radius. The default value is square root 2 of horizontal distance in a grid cell")
    ("output_format", po::value<std::string>(), "'all' generates every possible format,\n"
     "'arc' for ArcGIS format,\n"
     "'grid' for Ascii GRID format,\n"
     "the default value is --all")
    ("input_format", po::value<std::string>(), "'ascii' expects input point cloud in ASCII format\n"
     "'las' expects input point cloud in LAS format (default)")
    ("interpolation_mode,m", po::value<std::string>()->default_value("auto"), "'incore' stores working data in memory\n"
     "'outcore' stores working data on the filesystem, 'parallel' uses number of processes specified by mpirun -n\n"
     "'auto' (default) guesses based on the size of the data file")
    ("reader_count,c", po::value<int>(), "when interpolation mode is 'parallel', arg is number of reader processes, default is 1")
    ("buffer_size,b", po::value<int>(), "when interpolation mode is 'parallel', arg is write buffer size in bytes, default is 10000 bytes")
    ("mpi_times,t", "time mpi run");

    df.add_options()
#ifdef CURL_FOUND
    ("data_file_name,i", po::value<std::string>(), "path to unzipped plain text data file")
    ("data_file_url,l", po::value<std::string>(), "URL of unzipped plain text data file"
     "You must specify either a data_file_name or data_file_url.");
#else
    ("data_file_name,i", po::value<std::string>(), "required. path to unzipped plain text data file");
#endif

    ot.add_options()
    ("min", "the Zmin values are stored")
    ("max", "the Zmax values are stored")
    ("mean", "the Zmean values are stored")
    ("idw", "the Zidw values are stored")
    ("std", "the Zstd values are stored")
    ("den", "the density values are stored")
    ("all", "all the values are stored (default)");

    res.add_options()
    ("resolution", po::value<float>(), "The resolution is set to the specified value. Use square grids.\n"
     "If no resolution options are specified, a 6 unit square grid is used")
    ("resolution-x", po::value<float>(), "The X side of grid cells is set to the specified value")
    ("resolution-y", po::value<float>(), "The Y side of grid cells is set to the specified value");

    nf.add_options()
    ("fill", "fills nulls in the DEM. Default window size is 3.")
    ("fill_window_size", po::value<int>(), "The fill window is set to value. Permissible values are 3, 5 and 7.");

    desc.add(general).add(df).add(ot).add(res).add(nf);

    po::variables_map vm;

    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);

        if (vm.count("help")) {
            cout << "------------------------------------------------------------------------" << endl;
            cout << "   " << appName << " (development version )" << endl;
            cout << "------------------------------------------------------------------------" << endl;
            cout << "Usage: " << appName << " [options]" << endl;
            cout << desc << endl;
            exit(0);
        }

        po::notify(vm);


        if (vm.count("output_format")) {
            std::string of = vm["output_format"].as<std::string>();
            if(of.compare("all") == 0) {
                output_format = OUTPUT_FORMAT_ALL;
            }
            else if(of.compare("arc") == 0)
                output_format = OUTPUT_FORMAT_ARC_ASCII;
            else if(of.compare("grid") == 0)
                output_format = OUTPUT_FORMAT_GRID_ASCII;
            else {
                throw std::logic_error("'" + of + "' is not a recognized output_format");
            }
        }
        // resolution
        if(vm.count("resolution")) {
            float res = vm["resolution"].as<float>();
            GRID_DIST_X = res;
            GRID_DIST_Y = res;
            if(searchRadius == sqrt(2.0) * 6.0)
                searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

            if(GRID_DIST_X == 0) {
                throw std::logic_error("resolution must not be 0");
            }
        }

        if(vm.count("resolution-x")) {
            GRID_DIST_X = vm["resolution-x"].as<float>();
            if(searchRadius == sqrt(2.0) * 6.0)
                searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

            if(GRID_DIST_X == 0) {
                throw std::logic_error("resolution-x must not be 0");
            }
        }

        if(vm.count("resolution-y")) {
            GRID_DIST_Y = vm["resolution-y"].as<float>();
            if(GRID_DIST_Y == 0) {
                throw std::logic_error("resolution-y must not be 0");
            }
        }

        if(vm.count("min")) {
            type |= OUTPUT_TYPE_MIN;
        }

        if(vm.count("max")) {
            type |= OUTPUT_TYPE_MAX;
        }

        if(vm.count("mean")) {
            type |= OUTPUT_TYPE_MEAN;
        }

        if(vm.count("idw")) {
            type |= OUTPUT_TYPE_IDW;
        }

        if(vm.count("std")) {
            type |= OUTPUT_TYPE_STD;
        }

        if(vm.count("den")) {
            type |= OUTPUT_TYPE_DEN;
        }

        if(vm.count("all")) {
            type = OUTPUT_TYPE_ALL;
        }

        if(vm.count("fill")) {
            window_size = 3;
        }

        if(vm.count("fill_window_size")) {
            window_size = vm["fill_window_size"].as<int>();
            if(!((window_size == 3) || (window_size == 5) || (window_size == 7))) {
                throw std::logic_error("window-size must be either 3, 5, or 7");
            }
        }

        if(vm.count("input_format")) {
            std::string inf = vm["input_format"].as<std::string>();

            if(inf.compare("ascii") == 0)
                input_format = INPUT_ASCII;
            else if(inf.compare("las") == 0)
                input_format = INPUT_LAS;
            else {
                throw std::logic_error("'" + inf + "' is not a recognized input_format");
            }
        }


#ifdef CURL_FOUND
        if(vm.count("data_file_name")) {
            strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
        }
        if(vm.count("data_file_url")) {
            strncpy(inputURL, vm["data_file_url"].as<std::string>().c_str(), sizeof(inputURL));
        }

        if((inputName == NULL || !strcmp(inputName, "")) &&
                (inputURL == NULL || !strcmp(inputURL, "")))
        {
            throw std::logic_error("you must specify a valid data file");
        }
#else
        if(!vm.count("data_file_name")) {
            throw std::logic_error("data_file_name  must be specified");
        }
        else {
            strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
            if (!strcmp(inputName, "")) {
                throw std::logic_error("data_file_name must not be an empty string");
            }
        }
#endif

        if (!vm.count("output_file_name")) {
            throw std::logic_error("output_file_name must be specified");
        }
        else {
            strncpy(outputName, vm["output_file_name"].as<std::string>().c_str(), sizeof(outputName));
        }

        if(vm.count("search_radius")) {
            searchRadius = vm["search_radius"].as<float>();
        }

        if(vm.count("interpolation_mode")) {
            std::string im(vm["interpolation_mode"].as<std::string>());
            if (im.compare("auto") == 0) {
                interpolation_mode = INTERP_AUTO;
            }
            else if (im.compare("incore") == 0) {
                interpolation_mode = INTERP_INCORE;
            }
            else if (im.compare("outcore") == 0) {
                interpolation_mode = INTERP_OUTCORE;
            }
            else if (im.compare("parallel") == 0) {
                interpolation_mode = INTERP_MPI;
            }
            else {
                throw std::logic_error("'" + im + "' is not a recognized interpolation_mode");
            }
        }

        if(type == 0)
            type = OUTPUT_TYPE_ALL;

        if(vm.count("reader_count")) {
            reader_count = vm["reader_count"].as<int>();
        }
        if(vm.count("buffer_size")) {
            buffer_size = vm["buffer_size"].as<int>();
        }
        if(vm.count("mpi_times")) {
            timer = (mpi_times *)malloc(sizeof(mpi_times));
        }

#ifdef CURL_FOUND
        // download file from URL, and set input name
        if (!((inputURL == NULL || !strcmp(inputURL, "")))) {

            CURL *curl;
            CURLcode res;

            /* get the file name from the URL */
            int i = 0;
            for(i = sizeof(inputURL); i>= 0; i--) {
                if(inputURL[i] == '/')
                    break;
            }
            strncpy(inputName, inputURL+i+1, sizeof(inputName));

            curl = curl_easy_init();
            if (!curl) {
                cout << "Can't initialize curl object to download input from: "
                     << inputURL << endl;
                exit(1);
            }

            /* set URL */
            curl_easy_setopt(curl, CURLOPT_URL, inputURL);
            curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);

            /* and write to file */
            FILE *fp;
            fp = fopen(inputName, "w");
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

            /* perform the curl request and clean up */
            res = curl_easy_perform(curl);
            curl_easy_cleanup(curl);
            fclose(fp);

            if (res != 0) {
                cout << "Error while downloading input from: " << inputURL << endl;
                exit(1);
            }
        }
#endif

        if (interpolation_mode == INTERP_MPI)
        {
            if(timer)timer->start = time(NULL);
            MPI_Init (&argc, &argv);
            MPI_Comm_size (MPI_COMM_WORLD, &process_count);
            MPI_Comm_rank (MPI_COMM_WORLD, &rank);
            if (reader_count >= process_count)
            {
                if (rank == 0)
                {
                    printf ("process count = %i is not greater than reader process count = %i.\n",
                            process_count, reader_count);
                    printf ("decrease --parallel(-p) parameter value or add processes.\n");
                }

                MPI_Finalize ();
                return 0;
            }
            MPI_Barrier(MPI_COMM_WORLD);

        }

        if (rank == 0)
        {
            cout << "Parameters ************************" << endl;
            cout << "inputName: '" << inputName << "'" << endl;
            cout << "input_format: " << input_format << endl;
            cout << "outputName: '" << outputName << "'" << endl;
            cout << "GRID_DIST_X: " << GRID_DIST_X << endl;
            cout << "GRID_DIST_Y: " << GRID_DIST_Y << endl;
            cout << "searchRadius: " << searchRadius << endl;
            cout << "output_format: " << output_format << endl;
            cout << "type: " << type << endl;
            cout << "fill window size: " << window_size << endl;
            cout << "parallel interp, reader process count: " << reader_count
                 << endl;
            cout << "parallel interp, writer buffer size: " << buffer_size
                 << endl;
            cout << "************************************" << endl;
        }
        if (interpolation_mode == INTERP_MPI)
        {
            MPI_Barrier (MPI_COMM_WORLD);
        }

    }
    catch (std::exception& e) {
        cerr << "error: " << e.what() << endl;
        cerr << "execute `" << appName << " --help` to see usage information" << endl;
        exit(1);
    }

    t0 = clock();

    if(timer)
    {
        if(rank == reader_count)printf("Allocating memory...\n");
        timer->init_start = time(NULL);
    }
    Interpolation *ip = new Interpolation(GRID_DIST_X, GRID_DIST_Y, searchRadius,
                                          window_size, interpolation_mode, rank, process_count, reader_count, buffer_size, timer);

    if(ip->init(inputName, input_format) < 0)
    {
        fprintf(stderr, "Interpolation::init() error\n");
        return -1;
    }
    if(timer)
    {
        timer->init_end = time(NULL);
    }
    t1 = clock();
    if(rank == 0)
    {
        //printf("Init + Min/Max time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);
    }
    t0 = clock();
    if(ip->interpolation(inputName, outputName, input_format, output_format, type) < 0)
    {
        fprintf(stderr, "Interpolation::interpolation() error\n");
        return -1;
    }

    t1 = clock();
    if (rank == 0 && !timer)
    {
        printf ("DEM generation + Output time: %10.2f\n",
                (double) (t1 - t0) / CLOCKS_PER_SEC);
        printf ("# of data: %d\n", ip->getDataCount ());
        printf ("dimension: %d x %d\n", ip->getGridSizeX (),
                ip->getGridSizeY ());
    }



    if ((interpolation_mode == INTERP_MPI && timer))
    {
        MPI_Barrier (MPI_COMM_WORLD);
        //int first_writer_rank = ip->getInterp ()->getReaderCount ();
        if (timer)
            timer->end = time(NULL);
        /*
         long *interp_start = (long *) malloc(sizeof(long)*process_count);

         MPI_Gather(&(timer->interp_start), 1, MPI_LONG,
         interp_start, 1, MPI_LONG, 0, MPI_COMM_WORLD);
         */
        //int i;
        //if (rank == 0)
        //{
        //for (i = 0; i < process_count; i++)
        //{
        //    printf ("interp_start %li, rank %i\n", interp_start[i], i);
        //}
        //}
        //printf("reader count %i, writer count %i\n",ip->getInterp()->getReaderCount(), ip->getInterp()->getWriterCount());
        //for(i=0; i<process_count; i++){
        //    printf("reader ranks %i writer ranks %i\n",ip->getInterp()->getReaders()[i], ip->getInterp()->getWriters()[i]);
        // }


        if (rank == reader_count)
        {
            printf("Finished, first writer process times...\n");
            printf("Total time %li seconds.\n", timer->end - timer->start);

            printf ("  Allocation: %li seconds.\n",
                    timer->init_end - timer->init_start);
            printf ("  Read and send: %li seconds.\n",
                    timer->interp_end - timer->interp_start);
            printf ("  Process cells: %li seconds.\n",
                    timer->process_end - timer->process_start);
            printf ("  Write cells: %li seconds.\n",
                    timer->output_end -   timer->output_start);

        }


    }

    if (interpolation_mode == INTERP_MPI)
    {
        MPI_Finalize ();
    }
    else
    {
        delete ip;
    }

    return 0;
}
Ejemplo n.º 29
0
/**
 * The keyboard function that defines keys to be used.
 */
void keyboard(unsigned char key, int x, int y) {
   switch(key) {
      /* GENERAL */
      case 27:
         exit(EXIT_SUCCESS);
         break;
      case 'f': case 'F':
         full_screen_flag = !full_screen_flag;
         if (full_screen_flag) {
            glutFullScreen();
         }
         else {
            GW = 1080; GH = 720;
            glutReshapeWindow(GW, GH);
         }
         break;
      case '2': case '@':
         draw_arrows = !draw_arrows;
         break;
      case '3': case '#':
         draw_bounding_box = !draw_bounding_box;
         break;
      case '4': case '$':
         follow = !follow;
         if (!follow) { cam.setFocus(pnt3d(0, 0, 0)); }
         break;
      case '9':
         load();
         break;
      case '(': 
         save();
         break;


      /* CAMERA */
      case ' ':
         cam.cam_spin_flag = !cam.cam_spin_flag;
         break;

      /* PARTICLES */
      case '/': case '?':
         general((char*)"cif");
         break;
      case '\'': case '\"':
         general((char*)"retract_flag");
         break;
      case '1': 
         objs.push_back(new particleSystem(pnt3d(rand() % 10 - 5,
                                                 rand() % 10 - 5,
                                                 rand() % 10 - 5)));
         break;
      case '!':
         objs.pop_back();
         break;
      case '5': case '%':
         general((char*)"points_flag");
         break;
      case '6': case '^':
         general((char*)"switch_mesh");
         break;
      case '7': case '&':
         general((char*)"type");
         break;
      case '0': case ')':
         general((char*)"screen_saver");
         break;

      default:
         key_states[key] = true;
         break;
   }
}
Ejemplo n.º 30
0
number_format::number_format()
    : number_format(general())
{
}