Esempio n. 1
0
StringArray
getMultiConfigItem(const ConfigMap& configItems, const String &itemName, const StringArray& defRetVal, const char* tokenizeSeparator)
{
	ConfigMap::const_iterator item = configItems.find(itemName);
	if (item != configItems.end())
	{
		StringArray rv;
		rv.reserve(item->second.size());
		for (size_t i = 0; i < item->second.size(); ++i)
		{
			if (tokenizeSeparator)
			{
				StringArray tokenizedValue(item->second[i].value.tokenize(tokenizeSeparator));
				rv.insert(rv.end(), tokenizedValue.begin(), tokenizedValue.end());
			}
			else
			{
				rv.push_back(item->second[i].value);
			}
		}
		return rv;
	}
	else
	{
		return defRetVal;
	}
}
Esempio n. 2
0
bool Settings::load()
{
#ifdef TARGET_ROBOT
  robot = NaoBody().getName();
#else
  robot = "Nao";
#endif

  bool loadedSettingsFromFile = false;
#ifdef TARGET_ROBOT
  // load settings from team.cfg
  try
  {
    ConfigMap teams;
    if(teams.read("teams.cfg", false, &ConfigMap::printOnErr) >= 0)
    {
      teams.setFlags(teams.getFlags() | ConfigMap::READONLY);

      std::vector<std::string> keys = teams.getKeys();
      for(std::vector<std::string>::const_iterator i = keys.begin(), end = keys.end(); i != end; ++i)
      {
        const ConfigValue& teamValue = teams[*i];
        if(teamValue.getType() != ConfigValue::MAP)
          continue;
        const ConfigMap& team = teamValue;
        if(!team.hasKey("players"))
          continue;
        const ConfigValue& playersValue = team["players"];
        if(playersValue.getType() != ConfigValue::LIST)
          continue;

        const ListConfigValue& players = playersValue;
        for(int i = 0, len = players.length(); i < len; ++i)
        {
          const ConfigValue& playersValue = players[i];
          if(playersValue.getType() != ConfigValue::PLAIN)
            continue;
          if(((const PlainConfigValue&)playersValue).str() == robot)
          {
            playerNumber = i + 1;
            team["number"] >> teamNumber;
            teamPort = 10001 + teamNumber * 100;
            team["location"] >> location;
            std::string entryName;
            team["color"] >> entryName;
            if(entryName == "blue")
              teamColor = TEAM_BLUE;
            else if(entryName == "red")
              teamColor = TEAM_RED;
            else
              ASSERT(false);
            loadedSettingsFromFile = true;
            goto loadedTeamsCfg;
          }
        }
      }
loadedTeamsCfg:
      ;
    }
Esempio n. 3
0
Command::ConfigList Command::selectedConfigs(MasterDevice &m)
{
    unsigned int i;
    ec_ioctl_master_t master;
    ec_ioctl_config_t config;
    ConfigList list;
    stringstream err;

    m.getMaster(&master);

    if (aliases == "-" && positions == "-") { // shortcut
        for (i = 0; i < master.config_count; i++) {
            m.getConfig(&config, i);
            list.push_back(config);
        }
    } else { // take the long way home...
        ConfigMap configs;
        uint16_t maxAlias = 0;

        // fill cascaded map structure with all configs
        for (i = 0; i < master.config_count; i++) {
            m.getConfig(&config, i);
            AliasMap &aliasMap = configs[config.alias];
            aliasMap[config.position] = config;
            if (config.alias > maxAlias) {
                maxAlias = config.alias;
            }
        }

        ConfigAliasParser ap(maxAlias);
        NumberListParser::List aliasList = ap.parse(aliases.c_str());
        NumberListParser::List::const_iterator ai;

        for (ai = aliasList.begin(); ai != aliasList.end(); ai++) {

            ConfigMap::iterator ci = configs.find(*ai);
            if (ci == configs.end()) {
                continue;
            }

            AliasMap &aliasMap = configs[*ai];
            AliasPositionParser pp(aliasMap);
            NumberListParser::List posList = pp.parse(positions.c_str());
            NumberListParser::List::const_iterator pi;

            for (pi = posList.begin(); pi != posList.end(); pi++) {
                AliasMap::const_iterator ci;

                ci = aliasMap.find(*pi);
                if (ci != aliasMap.end()) {
                    list.push_back(ci->second);
                }
            }
        }
    }

    list.sort();
    return list;
}
Esempio n. 4
0
/* getConfig: {{{ */
int getConfig(ConfigMap &config, const string &name, int def) {
    ConfigMap::iterator it=config.find(name);
    if(it!=config.end())
        return atoi(config[name].c_str());
    cerr << "[W] Key : '" << name  << "' not found, using default value : " 
        << def << endl;
    return def;
}
Esempio n. 5
0
std::string Robot::getSettingsString(const Team& team) const
{
  ConfigMap cm;
  cm["teamNumber"] << team.number;
  cm["teamPort"] << team.port;
  cm["teamColor"] << team.color;
  cm["playerNumber"] << team.getPlayerNumber(*this);
  cm["location"] << team.location;
  return cm.str();
}
Esempio n. 6
0
bool GetConfigValue(ConfigMap& configMap, std::string key, std::string& value) {
	if(configMap.find(key) != configMap.end()) {
		value = configMap[key];
		string trimmedKey = trim(value);
		if(trimmedKey == "") {
			return false;
		}
		return true;
	}
	return false;
}
Esempio n. 7
0
void TeamSelector::saveTeams(const QString& filename)
{
  std::vector<Team> _teams;
  _teams.reserve(teams.size());
  for(size_t i = 0; i < teams.size(); ++i)
    _teams.push_back(*teams[i]);
  ConfigMap cm;
  Team::writeTeams(cm, _teams);
  std::string fn = toString(filename);
  cm.write(&fn);
}
bool ColorTableCreator::saveTrainingData(string fileName) const
{
  ConfigMap cm;
  cm["handMadeClassification"] << handMadeClassification;
  ofstream of;
  of.open(fileName.c_str());
  if(!of.is_open())
    return false;
  cm.write(of);
  of.close();
  return true;
}
Esempio n. 9
0
String
getConfigItem(const ConfigMap& configItems, const String &itemName, const String& defRetVal)
{
	ConfigMap::const_iterator i = configItems.find(itemName);
	if (i != configItems.end() && i->second.size() > 0)
	{
		return i->second.back().value;
	}
	else
	{
		return defRetVal;
	}
}
Esempio n. 10
0
 static void dumpConfigMapToYaml(YAML::Emitter &emitter,
                                 const ConfigMap &configMap) {
   emitter << YAML::BeginMap;
   ConfigMap::const_iterator it;
   for(it = configMap.begin(); it != configMap.end(); ++it) {
     emitter << YAML::Key << it->first;
     if(!(emitter.good())) {
       fprintf(stderr, "problem with ConfigMap for: %s\n", it->first.c_str());
     }
     emitter << YAML::Value;
     dumpConfigVectorToYaml(emitter, it->second);
   }
   emitter << YAML::EndMap;
 }
Esempio n. 11
0
void BallPerceptor::init(const FieldDimensions& theFieldDimensions)
{
  sqrMaxBallDistance = float(Vector2<int>(theFieldDimensions.xPosOpponentFieldBorder - theFieldDimensions.xPosOwnFieldBorder,
                                          theFieldDimensions.yPosLeftFieldBorder - theFieldDimensions.yPosRightFieldBorder).squareAbs());

  /*
  cout << "theFieldDimensions.xPosOpponentFieldBorder: " << theFieldDimensions.xPosOpponentFieldBorder << endl;
  cout << "theFieldDimensions.xPosOwnFieldBorder:      " << theFieldDimensions.xPosOwnFieldBorder      << endl;
  cout << "theFieldDimensions.yPosLeftFieldBorder:     " << theFieldDimensions.yPosLeftFieldBorder     << endl;
  cout << "theFieldDimensions.yPosRightFieldBorder:    " << theFieldDimensions.yPosRightFieldBorder    << endl;
 */

  ConfigMap params;
  params["clippingApproxRadiusScale"] << 2.f;
  params["clippingApproxRadiusPixelBonus"] << 2.5f;

  params["scanMaxColorDistance"] << (unsigned int) 30;
  params["scanPixelTolerance"] << (unsigned int) 2;

  params["refineMaxPixelCount"] << (unsigned int) 2;
  params["refineMaxColorDistance"] << (unsigned int) 40;

  params["checkMaxRadiusDifference"] << 1.6f;
  params["checkMinRadiusDifference"] << 0.9f;
  params["checkMinRadiusPixelBonus"] << 6.f;

  params["checkOutlineRadiusScale"] << 1.1f;
  params["checkOutlineRadiusPixelBonus"] << 2.f;

  //params.read(Global::getSettings().expandRobotLocationFilename("ballPerceptor.cfg"));
  params.read("/home/nao/.config/naoqi/Data/Config/Locations/Default/Robots/Nao/ballPerceptor.cfg");

  params["clippingApproxRadiusScale"] >> p.clippingApproxRadiusScale;
  params["clippingApproxRadiusPixelBonus"] >> p.clippingApproxRadiusPixelBonus;

  params["scanMaxColorDistance"] >> p.scanMaxColorDistance;
  params["scanPixelTolerance"] >> p.scanPixelTolerance;

  params["refineMaxPixelCount"] >> p.refineMaxPixelCount;
  params["refineMaxColorDistance"] >> p.refineMaxColorDistance;

  params["checkMaxRadiusDifference"] >> p.checkMaxRadiusDifference;
  params["checkMinRadiusDifference"] >> p.checkMinRadiusDifference;
  params["checkMinRadiusPixelBonus"] >> p.checkMinRadiusPixelBonus;

  params["checkOutlineRadiusScale"] >> p.checkOutlineRadiusScale;
  params["checkOutlineRadiusPixelBonus"] >> p.checkOutlineRadiusPixelBonus;
}
Esempio n. 12
0
/* main method {{{ */
int main(int argc, char *argv[]) {
    ConfigMap config;
    if(!parseOptions(argc,argv,config)) {        //Parse cmd line options
        cerr << "==> Try '" << argv[0] << " --usage'" << endl;
        return -1;
    }
    if(config.find("usage")!=config.end()||config.find("help")!=config.end()) {
        usage(argv[0]);
        return -1;
    }
    if(!parseConfig(config)) {
        cerr << "==> Try 'man " << argv[0] << "'" << endl;
        return -1;
    }
    return mainFunction(config);
}
Esempio n. 13
0
void
setConfigItem(ConfigMap& configItems, const String& itemName,
	const String& value, EOverwritePreviousFlag overwritePrevious)
{
	ConfigMap::iterator it = configItems.find(itemName);
	if (it == configItems.end())
	{
		configItems[itemName].push_back(ItemData("", value));
	}
	else if (overwritePrevious == E_OVERWRITE_PREVIOUS)
	{
		ItemDataArray& values = configItems[itemName];
		values.clear();
		values.push_back(ItemData("", value));
	}
	// else overwritePrevious == E_PRESERVE_PREVIOUS, and do nothing
}
bool ColorTableCreator::loadTrainingData(string fileName)
{
  handMadeClassification.clear();
  ConfigMap cm;
  if(cm.read(fileName) < 0)
    return false;

  try
  {
    cm["handMadeClassification"] >> handMadeClassification;
  }
  catch(std::invalid_argument e)
  {
    return false;
  } //In this case the Vector was empty

  return true;
}
Esempio n. 15
0
ompl::tools::SelfConfig::SelfConfig(const base::SpaceInformationPtr &si, const std::string &context) : context_(context)
{
    typedef std::map<base::SpaceInformation*, boost::shared_ptr<SelfConfigImpl> > ConfigMap;

    static ConfigMap    SMAP;
    static boost::mutex LOCK;

    boost::mutex::scoped_lock smLock(LOCK);
    ConfigMap::const_iterator it = SMAP.find(si.get());

    if (it != SMAP.end())
        impl_ = it->second.get();
    else
    {
        impl_ = new SelfConfigImpl(si);
        SMAP[si.get()].reset(impl_);
    }
}
Esempio n. 16
0
	/*! Load a repeating group into a supplied map.
	  \param tag the tag to find
	  \param map_name the target map
	  \param is_session if true, special case for session map
	  \return the number of elements inserted */
	unsigned load_map(const std::string& tag, ConfigMap& map_name, const bool is_session=false)
	{
		XmlElement::XmlSet slist;
		if (_root->find(tag, slist))
		{
			for(XmlElement::XmlSet::const_iterator itr(slist.begin()); itr != slist.end(); ++itr)
			{
				std::string name;
				if ((*itr)->GetAttr("name", name) && is_session ? (*itr)->FindAttr("active", false) : true)
				{
					map_name.insert(ConfigMap::value_type(name, *itr));
					if (is_session)
						_allsessions.push_back(*itr);
				}
			}
		}

		return map_name.size();
	}
Esempio n. 17
0
ompl::tools::SelfConfig::SelfConfig(const base::SpaceInformationPtr &si, const std::string &context) :
    context_(context.empty() ? "" : context + ": ")
{
    typedef std::map<base::SpaceInformation*, boost::shared_ptr<SelfConfigImpl> > ConfigMap;

    static ConfigMap    SMAP;
    static boost::mutex LOCK;

    boost::mutex::scoped_lock smLock(LOCK);

    // clean expired entries from the map
    ConfigMap::iterator dit = SMAP.begin();
    while (dit != SMAP.end())
    {
        if (dit->second->expired())
            SMAP.erase(dit++);
        else
          ++dit;
    }

    ConfigMap::const_iterator it = SMAP.find(si.get());

    if (it != SMAP.end())
        impl_ = it->second.get();
    else
    {
        impl_ = new SelfConfigImpl(si);
        SMAP[si.get()].reset(impl_);
    }
}
Esempio n. 18
0
/* parseConfig: {{{ */
bool parseConfig(ConfigMap &config) {
    string appKey("");
    ifstream file(config["configFile"].c_str(),ios::in);
    if(!file.good()) {
        cerr << "[E] Error opening the configuration file : '" 
            << config["configFile"] << "' !" << endl;
        return false;
    }
    bool res=true;
    bool verbose=false;
    ConfigMap::iterator it=config.find("general::verbose");
    if(it!=config.end())
        verbose=true;
    while(file) {
        string s;
        getline(file,s);
        s=strip(s);
        res=res && readString(s,config,appKey,verbose);
    }
    file.close();
    return res;
}
Esempio n. 19
0
		/// \brief Clone an instance.
		/// \param inIntancePtr A pointer to the instance to be cloned.
		/// \param inCloneInstanceName The name of the clone.
		/// \details Clone an instance and its configuration. This function does not clone the 
		/// 	instance pins. Instance pins are handled when cloning nets, in function cloneNet.
		InstanceSharedPtr cloneInstance(InstanceSharedPtr inIntancePtr,
			const string& inCloneInstanceName) {

			// Clone inInstancePtr
			InstanceSharedPtr inInstanceClonePtr = Factory::newInstancePtr(inCloneInstanceName,
				inIntancePtr->getType(), inIntancePtr->getTile(), inIntancePtr->getSite(),
				inIntancePtr->getBonding());

			// Begin clone inIntance configuration
			// Get a begin iterator to inIntance config
			ConfigMap::const_iterator instanceConfigBegin = inIntancePtr->configBegin();
			// Get an end iterator to inIntance config
			ConfigMap::const_iterator instanceConfigEnd = inIntancePtr->configEnd();
			// Configuration map
			ConfigMap configMap;

			// Iterate over all configuration
			while(instanceConfigBegin != instanceConfigEnd) {

				// Get current setting
				const string setting = instanceConfigBegin->first;
				// Get current configuration
				const Config config = instanceConfigBegin->second;
				// Add (setting,configuration) to configuration map
				configMap.setConfig(setting, config);
				// Move to the next configuration
				instanceConfigBegin++;

			}

			// Add configurations to instance clone
			inInstanceClonePtr->addConfigs(configMap);
			// End clone inInstance configuration

			// Return cloned instance
			return inInstanceClonePtr;
		}
Esempio n. 20
0
std::vector<Robot> Robot::getRobots()
{
  std::vector<Robot> robots;
  std::string robotsDir = "Robots";
  Directory d;
  if(d.open(*File::getFullNames(robotsDir).begin() + "/*"))
  {
    std::string dir;
    bool isDir;
    while(d.read(dir, isDir))
    {
      if(isDir)
      {
        ConfigMap cm;
        std::string s = linuxToPlatformPath(dir + "/robot.cfg");
        int status = cm.read(s);
        if(status > 0)
        {
          Robot r;
          cm >> r;
          robots.push_back(r);
        }
      }
    }
Esempio n. 21
0
	void ConfigHelper::LoadConfig(ConfigMap & mapConfig, string strPath)
	{
		vector<string> vecParas;
		vector<string> vecSkip;
		vecSkip.push_back("#");
		vecSkip.push_back(";");
		Load(vecParas, strPath, vecSkip);

		vector<string> vecVariable;
		string delim = "=";
		for (auto i = vecParas.begin(); i != vecParas.end(); i++)
		{
			vecVariable.clear();
			libReactor::Utils::split(*i, delim, vecVariable);
			if (vecVariable.size() == 2)
			{
				mapConfig.insert(make_pair(libReactor::Utils::trim(vecVariable[0]),
					libReactor::Utils::trim(vecVariable[1])));
			}
		}
	}
Esempio n. 22
0
      void Text3D::init() {

        // load the mask id form file
        FILE *f = fopen("./id.txt", "r");
        if(f) {
          fscanf(f, "%d", &maskId);
          fclose(f);
          maskId = 1 << (maskId - 1);
        }

        // Register for node information:
        /*
          std::string groupName, dataName;
          control->nodes->getDataBrokerNames(id, &groupName, &dataName);
          control->dataBroker->registerTimedReceiver(this, groupName, dataName, "mars_sim/simTimer", 10, 0);
        */

        /* get or create cfg_param
           example = control->cfg->getOrCreateProperty("plugin", "example",
           0.0, this);
        */
        textFactory = libManager->getLibraryAs<osg_text::TextFactoryInterface>("osg_text_factory");
        if(textFactory) {
          ConfigMap map;
          map = ConfigMap::fromYamlFile("Text3DConfig.yml", true);
          ConfigVector::iterator it;
          osg_text::TextInterface *text;
          if(map.find("Labels") != map.end()) {
            TextData *td;
            double fixedWidth, fixedHeight;
            bool drawFrame;
            double fontsize;
            osg_text::TextAlign align;

            for(it = map["Labels"].begin(); it!=map["Labels"].end(); ++it) {
              td = new TextData;
              td->name = (std::string)it->children["name"][0];
              td->value = (std::string)it->children["value"][0];
              td->posX = it->children["posX"][0];
              td->posY = it->children["posY"][0];
              fixedWidth = fixedHeight = -1;
              drawFrame = false;
              fontsize = 30;
              align = osg_text::ALIGN_LEFT;
              osg_text::Color c, bgColor(0.0, 0.5, 0.0, 0.5);
              osg_text::Color borderColor(1.0, 1.0, 1.0, 0.5);
              if(it->children.find("fixedWidth") != it->children.end()) {
                fixedWidth = it->children["fixedWidth"][0];
              }
              if(it->children.find("fixedHeight") != it->children.end()) {
                fixedHeight = it->children["fixedHeight"][0];
              }
              if(it->children.find("frame") != it->children.end()) {
                drawFrame = it->children["frame"][0];
              }
              if(it->children.find("fontsize") != it->children.end()) {
                fontsize = it->children["fontsize"][0];
              }
              if(it->children.find("align") != it->children.end()) {
                std::string sAlign = (std::string)it->children["align"][0];
                if(sAlign == "right") align = osg_text::ALIGN_RIGHT;
                else if(sAlign == "center") align = osg_text::ALIGN_CENTER;
              }
              if(it->children.find("color") != it->children.end()) {
                c.a = it->children["color"][0]["a"][0];
                c.r = it->children["color"][0]["r"][0];
                c.g = it->children["color"][0]["g"][0];
                c.b = it->children["color"][0]["b"][0];
              }
              if(it->children.find("bgColor") != it->children.end()) {
                bgColor.a = it->children["bgColor"][0]["a"][0];
                bgColor.r = it->children["bgColor"][0]["r"][0];
                bgColor.g = it->children["bgColor"][0]["g"][0];
                bgColor.b = it->children["bgColor"][0]["b"][0];
              }
              if(it->children.find("borderColor") != it->children.end()) {
                borderColor.a = it->children["borderColor"][0]["a"][0];
                borderColor.r = it->children["borderColor"][0]["r"][0];
                borderColor.g = it->children["borderColor"][0]["g"][0];
                borderColor.b = it->children["borderColor"][0]["b"][0];
              }
              td->text = textFactory->createText(td->value, fontsize,
                                                 c, td->posX, td->posY, align);
              if(drawFrame) {
                td->text->setBackgroundColor(bgColor);
                td->text->setBorderWidth(4.0);
              }
              else {
                td->text->setBackgroundColor(osg_text::Color(0.0, 0.0, 0.0, 0.0));
                td->text->setBorderWidth(0.0);
              }
              td->text->setBorderColor(borderColor);

              td->text->setPadding(10., 10., 10., 10.);
              td->text->setFixedWidth(fixedWidth);
              td->text->setFixedHeight(fixedHeight);
              example = control->cfg->getOrCreateProperty("Text3D",
                                                          td->name+"/value",
                                                          td->value, this);
              td->vId = example.paramId;
              example = control->cfg->getOrCreateProperty("Text3D",
                                                          td->name+"/posX",
                                                          td->posX, this);
              td->pxId = example.paramId;
              example = control->cfg->getOrCreateProperty("Text3D",
                                                          td->name+"/posY",
                                                          td->posY, this);
              td->pyId = example.paramId;
              int mask = it->children["mask"][0].getInt();
              example = control->cfg->getOrCreateProperty("Text3D",
                                                          td->name+"/mask",
                                                          mask, this);
              td->maskId = example.paramId;

              td->hudID = control->graphics->addHUDOSGNode(td->text->getOSGNode());
              td->vis = mask & maskId;
              if(!td->vis) {
                control->graphics->switchHUDElementVis(td->hudID);
              }

              textMap[td->vId] = td;
              textMap[td->pxId] = td;
              textMap[td->pyId] = td;
              textMap[td->maskId] = td;
            }
          }
        }
        else {
          fprintf(stderr, "can not load osg_text_factory\n");
        }
      }
Esempio n. 23
0
void Loader::clientLoad()
{
    ifstream istr;
    istr.open(app->loadFile);
    assert(!istr.fail());
    string line;
    while (std::getline(istr, line))
    {
        ConfigMap cmap;
        cmap.clear();
        string raw = sutl::decode(line);
        cmap.unpack(raw);

        if (cmap["itemtype"] == res.itemApp || cmap["itemtype"] == res.itemPlace)
        {
            DesktopRec deskrec;

#define rec2map(name) deskrec.name=cmap[#name];
            rec2map(iconName);
            rec2map(title);
            rec2map(genname);
            rec2map(loctitle);
            rec2map(locgenname);
            rec2map(command);
            rec2map(comment);
            rec2map(loccomment);
            rec2map(fname);
            rec2map(categories);
            rec2map(category);
            rec2map(itemtype);
            rec2map(attrs);
#undef rec2map

            string dec = sutl::decode(deskrec.attrs, attrEscape);
            deskrec.attr.unpack(dec);
            vapplications.push_back(deskrec);
        }

        if (cmap["itemtype"] == res.itemCategory)
        {
            CategoryLoader::CategoryRec catrec;

#define rec2map(name) catrec.name=cmap[#name];
            rec2map(category);
            rec2map(dirFile);
            rec2map(dirFilePath);
            rec2map(loctitle);
            rec2map(comment);
            rec2map(loccomment);
            rec2map(iconName);
#undef rec2map

            vcategories[catrec.category] = catrec;
        }

        if (cmap["itemtype"] == res.itemIcon)
        {
            string key = iconKey(cmap["name"], atoi(cmap["size"].c_str()));
            auto path = cmap["path"];
            if (!path.empty())
                vicons[key] = path;
        }

    }
    istr.close();
}
Esempio n. 24
0
void Loader::loadProc()
{
    Toolkit toolkit;
    app->config->load();

    string cmd;

#define createdir(d) cmd = string("mkdir -p ") + app-> d;system(cmd.c_str());assert(toolkit.dirExists(app-> d));

    createdir(dirCache);
    createdir(dirCacheIcons);
    createdir(dirProperties);
    createdir(dirTranslation);

    std::ofstream fstr;
    fstr.open(app->loadFile, std::ios::out | std::ios::binary);
    assert(fstr.is_open());

    struct IconRec
    {
        string name;
        int size;
    };
    vector<IconRec> vicons;

    ApplicationLoader appLoader;
    appLoader.getItems(vapplications);
    CategoryLoader catLoader;
    catLoader.init(&vapplications);

    appLoader.insertPlaces(vapplications);

    //------------- load applications

    for (auto deskrec : vapplications)
    {

        //printf("\napp %s %s", deskrec.title.c_str(),deskrec.category.c_str());

        ConfigMap cmap;
        cmap["itemtype"] = res.itemApp;

        deskrec.attrs = sutl::encode(deskrec.attr.pack(), attrEscape);

#define rec2map(name) cmap[#name]=deskrec.name
        rec2map(iconName);
        rec2map(title);
        rec2map(genname);
        rec2map(loctitle);
        rec2map(locgenname);
        rec2map(command);
        rec2map(comment);
        rec2map(loccomment);
        rec2map(fname);
        rec2map(categories);
        rec2map(attrs);
#undef rec2map

        string catMoveTo = app->properties->get(deskrec, res.pkeyMoveToCategory);

        int iconSize = CFGI("app_icon_size");

        CategoryLoader::CategoryRec catrec;
        if (!catMoveTo.empty())
        {
            catrec.category = catMoveTo;
        } else if (sutl::startsWith(deskrec.fname, toolkit.desktopDir()))
        {
            catrec.category = res.categoryDesktop;
            catrec.loctitle = res.categoryDesktop_loc;
            catrec.iconName = CFG("icon_place_desktop");
        } else if (deskrec.category == res.categoryPlaces)
        {
            catrec.category = res.categoryPlaces;
            catrec.iconName = CFG("icon_category_places");
            cmap["itemtype"] = res.itemPlace;
            iconSize = CFGI("place_icon_size");
        } else
        {
            catrec = catLoader.getCategory(deskrec);
            if (catrec.category.empty())
            {
                //catrec.category = res.categoryOther;
                continue;
            }
        }
        vicons.push_back( { deskrec.iconName, iconSize });

        if (vcategories.find(catrec.category) == vcategories.end())
        {
            vcategories[catrec.category] = catrec;
        }

        cmap["category"] = catrec.category;

        string raw = cmap.pack();
        raw = sutl::encode(raw);
        fstr << raw << "\n";

    }

    //------------- load categories

    for (auto ec : vcategories)
    {
        auto & crec = ec.second;

        ConfigMap cmap;
        cmap["itemtype"] = res.itemCategory;

#define rec2map(name) cmap[#name]=crec.name;
        rec2map(category);
        rec2map(dirFile);
        rec2map(dirFilePath);
        rec2map(loctitle);
        rec2map(comment);
        rec2map(loccomment);
        rec2map(iconName);
#undef rec2map

        vicons.push_back( { crec.iconName, CFGI("category_icon_size") });

        string raw = cmap.pack();
        raw = sutl::encode(raw);
        fstr << raw << "\n";

    }

    //------------- load icons
    int iconSize = CFGI("category_icon_size");
    vicons.push_back( { CFG("icon_category_all"), iconSize });
    vicons.push_back( { CFG("icon_category_other"), iconSize });
    vicons.push_back( { CFG("icon_category_places"), iconSize });
    vicons.push_back( { CFG("icon_category_recent"), iconSize });
    vicons.push_back( { CFG("icon_category_favorites"), iconSize });

    iconSize = CFGI("toolbar_icon_size");
    vicons.push_back( { CFG("icon_toolbar_shutdown"), iconSize });
    vicons.push_back( { CFG("icon_toolbar_settings"), iconSize });
    vicons.push_back( { CFG("icon_toolbar_logout"), iconSize });
    vicons.push_back( { CFG("icon_toolbar_lockscreen"), iconSize });
    vicons.push_back( { CFG("icon_toolbar_reload"), iconSize });

    vicons.push_back( { CFG("icon_menu"), app->menuIconSize });

    vicons.push_back( { res.iconSearchBoxName, res.iconSearchBoxSize });

    vicons.push_back( { CFG("icon_category_places"), CFGI("place_icon_size") });

    for (auto iconrec : vicons)
    {
        if (iconrec.name.empty())
            continue;
        string cachePath = createCachedIcon(iconrec.name, iconrec.size);
        ConfigMap cmap;
        cmap["itemtype"] = res.itemIcon;
        cmap["name"] = iconrec.name;
        cmap["size"] = sutl::itoa(iconrec.size);
        cmap["path"] = cachePath;
        string raw = cmap.pack();
        raw = sutl::encode(raw);
        fstr << raw << "\n";
    }

    fstr.close();
    catLoader.free();
}
Esempio n. 25
0
		/// \brief Clone a net.
		/// \param inNetPtr A pointer to the net to be cloned.
		/// \param inNetCloneName The name of the clone.
		/// \param inModuleInstanceName The module instance name.
		/// \details Clone a net, its configuration, its sources, sinks and pips. For pips, the
		/// 	routethrough instances are droppped and not cloned.
		NetSharedPtr cloneNet(NetSharedPtr inNetPtr, const string& inNetCloneName,
			const string& inModuleInstanceName) {

			// Clone inNetPtr
			NetSharedPtr inNetClonePtr = Factory::newNetPtr(inNetCloneName, inNetPtr->getNetType());

			// Begin clone inNetPtr configuration
			// Get a begin iterator to net config
			ConfigMap::const_iterator netConfigBegin = inNetPtr->configBegin();
			// Get an end iterator to net config
			ConfigMap::const_iterator netConfigEnd = inNetPtr->configEnd();
			// Configuration map
			ConfigMap configMap;

			// Iterate over all configuration
			while(netConfigBegin != netConfigEnd) {

				// Get current setting
				const string setting = netConfigBegin->first;
				// Get current configuration
				const Config config = netConfigBegin->second;
				// Add (setting,configuration) to configuration map
				configMap.setConfig(setting, config);
				// Move to the next configuration
				netConfigBegin++;

			}

			// Add configurations to net clone
			inNetClonePtr->addConfigs(configMap);
			// End clone inNetPtr configuration

			// Begin clone inNetPtr sources
			// Get a begin iterator to net sources
			InstancePinSharedPtrConstIterator inNetSourcesBegin = inNetPtr->sourcesBegin();
			// Get an end iterator to net sources
			InstancePinSharedPtrConstIterator inNetSourcesEnd = inNetPtr->sourcesEnd();

			// Iterate over all source pins
			while(inNetSourcesBegin != inNetSourcesEnd) {

				// Get pointer to current net pin
				InstancePinSharedPtr instPinPtr = *inNetSourcesBegin;
				// Get net pin reference instance
				InstanceSharedPtr pinInstPtr = instPinPtr->getInstancePtr().lock();
				// Find the cloned instance that correspond to the pin reference instance
				InstanceSharedPtrIterator pinInstPtrCloneItr = mDesignPtr->findInstance(
					inModuleInstanceName + sHierarchySeparator + pinInstPtr->getName());
				// Clone source pin
				InstancePinSharedPtr instPinPtrClone 
					= Factory::newInstancePinPtr(*pinInstPtrCloneItr, instPinPtr->getPinName());
				// Add pin clone to the net clone
				inNetClonePtr->addSource(instPinPtrClone);
				// Move to next source
				inNetSourcesBegin++;

			}
			// End clone inNetPtr sources

			// Begin clone inNetPtr sinks
			// Get a begin iterator to net sinks
			InstancePinSharedPtrConstIterator inNetSinksBegin = inNetPtr->sinksBegin();
			// Get an end iterator to net sinks
			InstancePinSharedPtrConstIterator inNetSinksEnd = inNetPtr->sinksEnd();

			// Iterate over all sink pins
			while(inNetSinksBegin != inNetSinksEnd) {

				// Get pointer to current net pin
				InstancePinSharedPtr instPinPtr = *inNetSinksBegin;
				// Get net pin reference instance
				InstanceSharedPtr pinInstPtr = instPinPtr->getInstancePtr().lock();
				// Find the cloned instance that correspond to the pin reference instance
				InstanceSharedPtrIterator pinInstPtrCloneItr = mDesignPtr->findInstance(
					inModuleInstanceName + sHierarchySeparator + pinInstPtr->getName());
				// Clone sink pin
				InstancePinSharedPtr instPinPtrClone 
					= Factory::newInstancePinPtr(*pinInstPtrCloneItr, instPinPtr->getPinName());
				// Add pin clone to the net clone
				inNetClonePtr->addSink(instPinPtrClone);
				// Move to next sink
				inNetSinksBegin++;

			}
			// End clone inNetPtr sinks

			// Begin clone inNetPtr pips
			// Get a begin iterator to net pips
			PipConstIterator inNetPipsBegin = inNetPtr->pipsBegin();
			// Get an end iterator to net pips
			PipConstIterator inNetPipsEnd = inNetPtr->pipsEnd();

			// Iterate over all pips
			while(inNetPipsBegin != inNetPipsEnd) {

				// Get a pointer to the current pip
				Pip pipPtr = *inNetPipsBegin;
				/// \todo We are dropping routethrough instances.
				// Clone the pip
				Pip pipClone = Factory::newPip(pipPtr.getTileName(), pipPtr.getSourceWireName(),
					pipPtr.getSinkWireName(), pipPtr.getDirection());
				// Add pip clone to cloned net
				inNetClonePtr->addPip(pipClone);
				// Move to next pip
				inNetPipsBegin++;

			}
			// End clone inNetPtr pips

			// Return cloned net
			return inNetClonePtr;
		}
Esempio n. 26
0
void GlobalCFG::got_input(std::vector<std::string> params, std::vector<int> intparams, std::string command)
{
	if (params[0] == "help")
	{
		ng_slogout("gcfg","gcfg_list - show all global config values set");
		ng_slogout("gcfg","gcfg <name> <value> - set a global cfg value");
	}

	if (params[0] == "gcfg_list")
	{
		ng_slogout("gcfg","listing:");
		ConfigMap *cmdata = GetData();
		ConfigMap::iterator it;
		for (it=cmdata->begin(); it != cmdata->end(); it++) {
			ConfigData *entry = (*it).second;
			if (!entry) continue;

			switch (entry->GetType())
			{
				case 0:
						ng_slogout("gcfg","int %s: %d",(*it).first.c_str(),entry->GetInt());
						break;
				case 1:
						ng_slogout("gcfg","str %s: %s",(*it).first.c_str(),entry->GetStr().c_str());
						break;
				default:
						ng_slogout("gcfg","%s: <unkown type>",(*it).first.c_str());
			}
		}
	}

	if (params[0] == "gcfg")
	{
			
		if (params.size() >= 3)
		{
			if (intparams[2]!=MININT)
			{
				SetInt(params[1],intparams[2]);
			} else {
				std::string mydata;
				for( unsigned int i=2; i < params.size(); i++ )
				{
					if (i>2)
						mydata.append(" ");
					mydata.append(params[i]);
				}
				SetStr(params[1],mydata);
			}

			ConfigData *entry = GetItem(params[1]);
			if (!entry) {
				ng_slogerror("gcfg","could not set %s",params[1].c_str());
				return;
			}

			switch (entry->GetType())
			{
				case 0:
						ng_slogout("gcfg","set int %s: %d",params[1].c_str(),entry->GetInt());
						break;
				case 1:
						ng_slogout("gcfg","set str %s: %s",params[1].c_str(),entry->GetStr().c_str());
						break;
			}
		} else ng_slogout_ret("gcfg",RET_WRONG_SYNTAX,"usage: gcfg <name> <value> - set a global cfg value");
	}
}
Esempio n. 27
0
/* mainFunction method {{{ */
int mainFunction(ConfigMap &config) {
    if(config.find("general::equation")==config.end()) {
        cerr << "[E] No problem defined!" << endl;
        return -1;
    }
    cerr << "[I] Initializing problem...\n";
    Expression *eqn=parseString(config["general::equation"]);
    Expression *pot=parseString(config["general::potential"]);
    cerr << "[I] Equation: " << eqn << endl;
    cerr << "[I] Potential: " << pot << endl;
    VarDef params;
    cerr << "[I] Getting parameters:\n";
    for(ConfigMap::iterator it=config.begin();it!=config.end();it++) {
        if((it->first).find("parameters::")!=string::npos) {
            string name=(it->first).substr(12);
            params[name]=parseString(it->second);
            cerr << "[I]\t" << name << "=" << it->second << "\n";
        }
    }
    cerr.flush();
    eqn=eqn->simplify(params);
    pot=pot->simplify(params);
    GPE *gpe=0;
    if(pot->find("X")) {
        if(pot->find("Y")) {
            if(pot->find("Z")) {
                if(eqn->find("LZ"))
                    gpe=new GPE3DROT(config,eqn,pot);
                else
                    gpe=new GPE3D(config,eqn,pot);
            } else {
                if(eqn->find("LZ"))
                    gpe=new GPE2DROT(config,eqn,pot);
                else
                    gpe=new GPE2D(config,eqn,pot);
            }
        } else
            gpe=new GPE1D(config,eqn,pot);
    } else if(eqn->find("R"))
        gpe=new Polar1D(config,eqn,pot);
    if(gpe==0) {
        cerr << "[E] Unknown problem type!" << std::endl;
        return -1;
    }
    gpe->initialize(pot);
    if(config["in"].size()>0) {
        gpe->load(config["in"]);
    }
    string out="psi1.dat";
    if(config["out"].size()>0) {
        out=config["out"];
    }
    string log="";
    if(config.find("log")!=config.end()) {
        log="log.txt";
        if(config["log"].size()>0) {
            log=config["log"];
        }
    }
    if(config.find("imprint")!=config.end()) {
        int l=getConfig(config,string("imprint"),1);
        std::cerr << "[I] Imprinting a l=" << l << " circulation" << endl;
        gpe->imprint(l);
    }
    if(config.find("groundstate")!=config.end()) {
        double dt=getConfig(config,string("general::dt"),1e-3);
        double tol=getConfig(config,string("general::tol"),1e-12);
        double dttol=getConfig(config,string("general::dttol"),0.999);
        gpe->findGroundState(dt,tol,dttol,log);
        gpe->save(out);
    }
    if(config.find("spectrum")!=config.end()) {
        range<int> def={0,0,1};
        range<int> m=getConfig(config,string("spectrum"),def);
        for(int i=m.min;i<=m.max;i+=m.incr)
            gpe->spectrum(log,i);
    }
    if(config.find("evolve")!=config.end()) {
        range<double> def={0.,1.,1e-3};
        range<double> t=getConfig(config,string("evolve"),def);
        gpe->evolve(t.min,t.incr,t.max,out);
    }
    if(config.find("plot")!=config.end()) {
        int n=5; //getConfig(config,string("plot"),0);
        gpe->plot(n,config["plot"]);
    }
    if(config.find("measure")!=config.end()) {
        std::cout << gpe->measure() << std::endl;
    }
    return 0;
};
Esempio n. 28
0
/*
 * adapted from HydroRunBaseMpi::outputPnetcdf
 *
 * assumes here that localData have size nx,ny,nz (no ghostWidth)
 *
 * see : test_pnetcdf_write.cpp
 *
 * Note that if ghostIncluded is false local_data must be sized upon nx,ny,nz
 * if not size must be nx+2*ghostWidth,ny+2*ghostWidth,nz+2*ghostWidth 
 *
 */
void write_pnetcdf(const std::string &filename,
		   HostArray<double> &localData,
		   ConfigMap         &configMap)
{
  int myRank;
  MPI_Comm_rank(MPI_COMM_WORLD, &myRank);

  // read local domain sizes
  int nx=configMap.getInteger("mesh","nx",32);
  int ny=configMap.getInteger("mesh","ny",32);
  int nz=configMap.getInteger("mesh","nz",32);

  // read mpi geometry
  int mx=configMap.getInteger("mpi","mx",1);
  int my=configMap.getInteger("mpi","my",1);
  int mz=configMap.getInteger("mpi","mz",1);


  // MPI cartesian coordinates
  // myRank = mpiCoord[0] + mx*mpiCoord[1] + mx*my*mpiCoord[2]
  int mpiCoord[3];
  {
    mpiCoord[2] =  myRank/(mx*my);
    mpiCoord[1] = (myRank - mx*my*mpiCoord[2])/mx;
    mpiCoord[0] =  myRank - mx*my*mpiCoord[2] -mx*mpiCoord[1];
  }

  bool ghostIncluded = configMap.getBool("output", "ghostIncluded",false);
  int  ghostWidth    = configMap.getInteger("mesh","ghostWidth",3);

  // global size
  int NX=nx*mx, NY=ny*my, NZ=nz*mz;
  int gsizes[3];
  gsizes[IZ] = NX;
  gsizes[IY] = NY;
  gsizes[IX] = NZ;
  
  if ( ghostIncluded ) {
    gsizes[IZ] += 2*ghostWidth;
    gsizes[IY] += 2*ghostWidth;
    gsizes[IX] += 2*ghostWidth;
  }

  // netcdf file id
  int ncFileId;
  int err;

  // file creation mode
  int ncCreationMode = NC_CLOBBER;
  bool useCDF5 = configMap.getBool("output","pnetcdf_cdf5",false);
  if (useCDF5)
    ncCreationMode = NC_CLOBBER|NC_64BIT_DATA;
  else // use CDF-2 file format
    ncCreationMode = NC_CLOBBER|NC_64BIT_OFFSET;

  // verbose log ?
  bool pnetcdf_verbose = configMap.getBool("output","pnetcdf_verbose",false);
  
  int nbVar=8;
  int dimIds[3], varIds[nbVar];
  MPI_Offset write_size, sum_write_size;
  MPI_Info mpi_info_used;
  char str[512];
  
  // time measurement variables
  double write_timing, max_write_timing, write_bw;

  /*
   * writing parameter (offset and size)
   */
  MPI_Offset         starts[3] = {0};
  MPI_Offset         counts[3] = {nz, ny, nx};
  
  // take care that row-major / column major format
  starts[IZ] = mpiCoord[IX]*nx;
  starts[IY] = mpiCoord[IY]*ny;
  starts[IX] = mpiCoord[IZ]*nz;

  if ( ghostIncluded ) {

    if ( mpiCoord[IX] == 0 )
      counts[IZ] += ghostWidth;
    if ( mpiCoord[IY] == 0 )
      counts[IY] += ghostWidth;
    if ( mpiCoord[IZ] == 0 )
      counts[IX] += ghostWidth;

    if ( mpiCoord[IX] == mx-1 )
      counts[IZ] += ghostWidth;
    if ( mpiCoord[IY] == my-1 )
      counts[IY] += ghostWidth;
    if ( mpiCoord[IZ] == mz-1 )
      counts[IX] += ghostWidth;

    starts[IZ] += ghostWidth;
    starts[IY] += ghostWidth;
    starts[IX] += ghostWidth;

    if ( mpiCoord[IX] == 0 )
      starts[IZ] -= ghostWidth;
    if ( mpiCoord[IY] == 0 )
      starts[IY] -= ghostWidth;
    if ( mpiCoord[IZ] == 0 )
      starts[IX] -= ghostWidth;
  
  }

  /* 
   * Create NetCDF file
   */
  err = ncmpi_create(MPI_COMM_WORLD, filename.c_str(), 
		     ncCreationMode,
		     MPI_INFO_NULL, &ncFileId);
  if (err != NC_NOERR) {
    printf("Error: ncmpi_create() file %s (%s)\n",filename.c_str(),ncmpi_strerror(err));
    MPI_Abort(MPI_COMM_WORLD, -1);
    exit(1);
  }

  /*
   * Define dimensions
   */
  err = ncmpi_def_dim(ncFileId, "x", gsizes[0], &dimIds[0]);
  PNETCDF_HANDLE_ERROR;
  
  err = ncmpi_def_dim(ncFileId, "y", gsizes[1], &dimIds[1]);
  PNETCDF_HANDLE_ERROR;
  
  err = ncmpi_def_dim(ncFileId, "z", gsizes[2], &dimIds[2]);
  PNETCDF_HANDLE_ERROR;

  /* 
   * Define variables
   */
  nc_type       ncDataType =  NC_DOUBLE;
  MPI_Datatype mpiDataType = MPI_DOUBLE;

  err = ncmpi_def_var(ncFileId, "rho", ncDataType, 3, dimIds, &varIds[ID]);
  PNETCDF_HANDLE_ERROR;
  err = ncmpi_def_var(ncFileId, "E", ncDataType, 3, dimIds, &varIds[IP]);
  PNETCDF_HANDLE_ERROR;
  err = ncmpi_def_var(ncFileId, "rho_vx", ncDataType, 3, dimIds, &varIds[IU]);
  PNETCDF_HANDLE_ERROR;
  err = ncmpi_def_var(ncFileId, "rho_vy", ncDataType, 3, dimIds, &varIds[IV]);
  PNETCDF_HANDLE_ERROR;
  err = ncmpi_def_var(ncFileId, "rho_vz", ncDataType, 3, dimIds, &varIds[IW]);
  PNETCDF_HANDLE_ERROR;
  
  err = ncmpi_def_var(ncFileId, "Bx", ncDataType, 3, dimIds, &varIds[IA]);
  PNETCDF_HANDLE_ERROR;
  err = ncmpi_def_var(ncFileId, "By", ncDataType, 3, dimIds, &varIds[IB]);
  PNETCDF_HANDLE_ERROR;
  err = ncmpi_def_var(ncFileId, "Bz", ncDataType, 3, dimIds, &varIds[IC]);
  PNETCDF_HANDLE_ERROR;

  /*
   * global attributes
   */
  // did we use CDF-2 or CDF-5
  {
    int useCDF5_int = useCDF5 ? 1 : 0;
    err = ncmpi_put_att_int(ncFileId, NC_GLOBAL, "CDF-5 mode", NC_INT, 1, &useCDF5_int);
    PNETCDF_HANDLE_ERROR;
  }
  
  /* 
   * exit the define mode 
   */
  err = ncmpi_enddef(ncFileId);
  PNETCDF_HANDLE_ERROR;
  
  /* 
   * Get all the MPI_IO hints used
   */
  err = ncmpi_get_file_info(ncFileId, &mpi_info_used);
  PNETCDF_HANDLE_ERROR;
  
  int nItems = counts[IX]*counts[IY]*counts[IZ];
  
  for (int iVar=0; iVar<nbVar; iVar++) {
    double *data = &(localData(0,0,0,iVar));
    err = ncmpi_put_vara_all(ncFileId, varIds[iVar], starts, counts, data, nItems, mpiDataType);
    PNETCDF_HANDLE_ERROR;
  }

  /* 
   * close the file 
   */
  err = ncmpi_close(ncFileId);
  PNETCDF_HANDLE_ERROR;
  
} // write_pnetcdf
Esempio n. 29
0
void read_pnetcdf(const std::string &filename,
		  int                iVar,
		  ConfigMap         &configMap, 
		  HostArray<double> &localData)
{
  int myRank;
  MPI_Comm_rank(MPI_COMM_WORLD, &myRank);
  int nbMpiProc;
  MPI_Comm_size(MPI_COMM_WORLD, &nbMpiProc);

  // netcdf file id
  int ncFileId;
  int err;
  
  // ghostWidth
  int ghostWidth = configMap.getInteger("mesh","ghostWidth",3);

  // file creation mode
  int ncOpenMode = NC_NOWRITE;
  
  int varIds[8];
  MPI_Offset starts[3], counts[3]; // read_size, sum_read_size;
  MPI_Info mpi_info_used;
  
  // domain local size
  int nx,ny,nz;

  // sizes to read
  //int nx_r,  ny_r,  nz_r;  // logical sizes / per sub-domain
  //int nx_g, ny_g, nz_g; // sizes with ghost zones included / per sub-domain

  /* read domain sizes */
  nx=configMap.getInteger("mesh","nx",32);
  ny=configMap.getInteger("mesh","ny",32);
  nz=configMap.getInteger("mesh","nz",32);

  // nx_g = nx+2*ghostWidth;
  // ny_g = ny+2*ghostWidth;
  // nz_g = nz+2*ghostWidth;

  // get input filename from configMap
  //std::string filename = configMap.getString("input", "filename", "");

  /* 
   * Open NetCDF file
   */
  err = ncmpi_open(MPI_COMM_WORLD, filename.c_str(), 
		   ncOpenMode,
		   MPI_INFO_NULL, &ncFileId);
  if (err != NC_NOERR) {
    printf("Error: ncmpi_open() file %s (%s)\n",filename.c_str(),ncmpi_strerror(err));
    MPI_Abort(MPI_COMM_WORLD, -1);
    exit(1);
  }

  /*
   * Query NetCDF mode
   */
  int NC_mode;
  err = ncmpi_inq_version(ncFileId, &NC_mode);
  if (myRank==0) {
    if (NC_mode == NC_64BIT_DATA)
      std::cout << "Pnetcdf Input mode : NC_64BIT_DATA (CDF-5)\n";
    else if (NC_mode == NC_64BIT_OFFSET)
      std::cout << "Pnetcdf Input mode : NC_64BIT_OFFSET (CDF-2)\n";
    else
      std::cout << "Pnetcdf Input mode : unknown\n";
  }

  /*
   * Query information about variables
   */
  {
    int ndims, nvars, ngatts, unlimited;
    err = ncmpi_inq(ncFileId, &ndims, &nvars, &ngatts, &unlimited);
    PNETCDF_HANDLE_ERROR;

    err = ncmpi_inq_varid(ncFileId, "rho", &varIds[ID]);
    PNETCDF_HANDLE_ERROR;
    err = ncmpi_inq_varid(ncFileId, "E", &varIds[IP]);
    PNETCDF_HANDLE_ERROR;
    err = ncmpi_inq_varid(ncFileId, "rho_vx", &varIds[IU]);
    PNETCDF_HANDLE_ERROR;
    err = ncmpi_inq_varid(ncFileId, "rho_vy", &varIds[IV]);
    PNETCDF_HANDLE_ERROR;
    err = ncmpi_inq_varid(ncFileId, "rho_vz", &varIds[IW]);
    PNETCDF_HANDLE_ERROR;    
    err = ncmpi_inq_varid(ncFileId, "Bx", &varIds[IA]);
    PNETCDF_HANDLE_ERROR;
    err = ncmpi_inq_varid(ncFileId, "By", &varIds[IB]);
    PNETCDF_HANDLE_ERROR;
    err = ncmpi_inq_varid(ncFileId, "Bz", &varIds[IC]);
    PNETCDF_HANDLE_ERROR;	
  } // end query information

  /* 
   * Define expected data types (no conversion done here)
   */
  //nc_type ncDataType;
  MPI_Datatype mpiDataType;
  
  //ncDataType  = NC_DOUBLE;
  mpiDataType = MPI_DOUBLE;

  /* 
   * Get all the MPI_IO hints used (just in case, we want to print it after 
   * reading data...
   */
  err = ncmpi_get_file_info(ncFileId, &mpi_info_used);
  PNETCDF_HANDLE_ERROR;

  /*
   * Read heavy data (take care of row-major / column major format !)
   */
  // use overlapping domains
  // counts[IZ] = nx_rg;
  // counts[IY] = ny_rg;
  // counts[IX] = nz_rg;
  
  // starts[IZ] = 0;
  // starts[IY] = 0;
  // starts[IX] = myRank*nz_r;

  counts[IZ] = nx;
  counts[IY] = ny;
  counts[IX] = nz;
  
  starts[IZ] = ghostWidth;
  starts[IY] = ghostWidth;
  starts[IX] = ghostWidth+myRank*nz;

  int nItems = counts[IX]*counts[IY]*counts[IZ];

  /*
   * Actual reading
   */
  {
    double* data;
    //data = &(localData(0,0,0,0));
    data = localData.data();
    
    err = ncmpi_get_vara_all(ncFileId, varIds[iVar], 
			     starts, counts, data, nItems, mpiDataType);
    PNETCDF_HANDLE_ERROR;

  } // end for loop reading heavy data

  /* 
   * close the file 
   */
  err = ncmpi_close(ncFileId);
  PNETCDF_HANDLE_ERROR;

} // read_pnetcdf
Esempio n. 30
0
void CmdInterpreter::visit(ProxyCmdOpenDatabase &cmd)
{
    ConfigMap configMap;

    SharedProxyDatabaseParam pParam = cmd.getParams();
    for (; pParam; ++pParam) {
        configMap.setStringParam(pParam->getName(), pParam->getValue());
    }

    CacheParams cacheParams;
    cacheParams.readConfig(configMap);
    SharedCache pCache = Cache::newCache(cacheParams);

    JniUtilParams jniUtilParams;
    jniUtilParams.readConfig(configMap);
    JniUtil::configure(jniUtilParams);

    DeviceMode openMode = cmd.isCreateDatabase()
        ? DeviceMode::createNew
        : DeviceMode::load;

    std::auto_ptr<DbHandle> pDbHandle(newDbHandle());
    JniUtil::incrementHandleCount(DBHANDLE_TRACE_TYPE_STR, pDbHandle.get());

    JavaTraceTarget *pJavaTraceTarget = newTraceTarget();
    pDbHandle->pTraceTarget.reset(pJavaTraceTarget);
    // on a fatal error, echo the backtrace to the log file:
    AutoBacktrace::setTraceTarget(pDbHandle->pTraceTarget);

    SharedDatabase pDb;
    try {
        pDb = Database::newDatabase(
            pCache,
            configMap,
            openMode,
            pDbHandle->pTraceTarget,
            SharedPseudoUuidGenerator(new JniPseudoUuidGenerator()));
    } catch (...) {
        AutoBacktrace::setTraceTarget();
        throw;
    }

    pDbHandle->pDb = pDb;

    ExecStreamResourceKnobs knobSettings;
    knobSettings.cacheReservePercentage =
        configMap.getIntParam("cacheReservePercentage");
    knobSettings.expectedConcurrentStatements =
        configMap.getIntParam("expectedConcurrentStatements");

    ExecStreamResourceQuantity resourcesAvailable;
    resourcesAvailable.nCachePages = pCache->getMaxLockedPages();

    pDbHandle->pResourceGovernor =
        SharedExecStreamGovernor(
            new SimpleExecStreamGovernor(
                knobSettings, resourcesAvailable,
                pDbHandle->pTraceTarget,
                "xo.resourceGovernor"));

    if (pDb->isRecoveryRequired()) {
        SegmentAccessor scratchAccessor =
            pDb->getSegmentFactory()->newScratchSegment(pDb->getCache());
        FtrsTableWriterFactory recoveryFactory(
            pDb,
            pDb->getCache(),
            pDb->getTypeFactory(),
            scratchAccessor);
        pDb->recover(recoveryFactory);
        cmd.setResultRecoveryRequired(true);
    } else {
        cmd.setResultRecoveryRequired(false);
    }
    pDbHandle->statsTimer.setTarget(*pJavaTraceTarget);
    pDbHandle->statsTimer.addSource(pDb);
    pDbHandle->statsTimer.addSource(pDbHandle->pResourceGovernor);
    pDbHandle->statsTimer.start();

    // Cache initialization may have been unable to allocate the requested
    // number of pages -- check for this case and report it in the log.
    if (pCache->getMaxAllocatedPageCount() != cacheParams.nMemPagesMax
        || pCache->getAllocatedPageCount() != cacheParams.nMemPagesInit)
    {
        FENNEL_DELEGATE_TRACE(
            TRACE_WARNING,
            pDb,
            "Unable to allocate "
            << cacheParams.nMemPagesInit
            << " (of "
            << cacheParams.nMemPagesMax
            << " max) cache pages; allocated "
            << pCache->getAllocatedPageCount()
            << " cache pages.");
    }

    setDbHandle(cmd.getResultHandle(), pDbHandle.release());
}