void dfs(int id,int depth,const map<int,string>&id2name,const map<int,deque<int> >&children){
	cout<<string(depth,'.')<<id2name.at(id)<<endl;
	if(children.find(id)!=children.end())for(auto &e:children.at(id)){
		dfs(e,depth+1,id2name,children);
	}
}
Exemple #2
0
namespace hg
{
	AssetManager assetManager;
	map<string, MusicData> musicDataMap;
	map<string, StyleData> styleDataMap;
	map<string, LevelData> levelDataMap;
	map<string, ProfileData> profileDataMap;
	map<string, EventData> eventDataMap;
	map<string, PackData> packDataMap;
	ProfileData* currentProfilePtr{nullptr};
	map<string, vector<string>> levelIdsByPackMap;
	vector<string> packPaths;

	void initAssetManager() { assetManager.loadFolder("Assets/"); }
	AssetManager& getAssetManager() { return assetManager; }

	void loadAssets()
	{
		log("loading profiles", "LoadAssets"); 	loadProfiles();

		for(string packPath : getScan<Mode::Single, Type::Folder>("Packs/"))
		{
			string packName{packPath.substr(6, packPath.length() - 6)};

			string packLua{""};
			for(const auto& path : getScan<Mode::Recurse, Type::File, Pick::ByExt>(packPath, ".lua")) packLua.append(getFileContents(path));
			string packHash{Online::getMD5Hash(packLua + HG_SKEY1 + HG_SKEY2 + HG_SKEY3)};

			Json::Value packRoot{getRootFromFile(packPath + "/pack.json")};
			PackData packData(packName, packRoot["name"].asString(), packRoot["priority"].asFloat(), packHash);
			packDataMap.insert(make_pair(packName, packData));
		}

		vector<PackData> packDatasToQuery;
		for(pair<string, PackData> packDataPair : packDataMap) packDatasToQuery.push_back(packDataPair.second);
		sort(begin(packDatasToQuery), end(packDatasToQuery), [](PackData a, PackData b) { return a.getPriority() < b.getPriority(); });

		for(PackData packData : packDatasToQuery)
		{
			string packName{packData.getId()}, packPath{"Packs/" + packName + "/"};
			packPaths.push_back("Packs/" + packName + "/");
			log("loading " + packName + " music", "LoadAssets");			loadMusic(packPath);
			log("loading " + packName + " music data", "LoadAssets");		loadMusicData(packPath);
			log("loading " + packName + " style data", "LoadAssets");		loadStyleData(packPath);
			log("loading " + packName + " level data", "LoadAssets");		loadLevelData(packPath);
			log("loading " + packName + " events", "LoadAssets");			loadEvents(packPath);
			log("loading " + packName + " custom sounds", "LoadAssets");	loadCustomSounds(packName, packPath);
		}
	}

	void loadCustomSounds(const string& mPackName, const string& mPath)
	{
		for(auto filePath : getScan<Mode::Single, Type::File, Pick::ByExt>(mPath + "Sounds/", ".ogg"))
		{
			string fileName{getNameFromPath(filePath, mPath + "Sounds/", "")};
			assetManager.loadSound(mPackName + "_" + fileName, filePath);
			assetManager.getSound(mPackName + "_" + fileName).setVolume(getSoundVolume());
		}
	}
	void loadMusic(const string& mPath)
	{
		for(auto filePath : getScan<Mode::Single, Type::File, Pick::ByExt>(mPath + "Music/", ".ogg"))
		{
			string fileName{getNameFromPath(filePath, mPath + "Music/", ".ogg")};

			auto& music(assetManager.loadMusic(fileName, filePath));
			music.openFromFile(filePath);
			music.setVolume(getMusicVolume());
			music.setLoop(true);
		}
	}
	void loadMusicData(const string& mPath)
	{
		for(auto filePath : getScan<Mode::Single, Type::File, Pick::ByExt>(mPath + "Music/", ".json"))
		{
			MusicData musicData{loadMusicFromJson(getRootFromFile(filePath))};
			musicDataMap.insert(make_pair(musicData.getId(), musicData));
		}
	}
	void loadStyleData(const string& mPath)
	{
		for(auto filePath : getScan<Mode::Single, Type::File, Pick::ByExt>(mPath + "Styles/", ".json"))
		{
			StyleData styleData{loadStyleFromJson(getRootFromFile(filePath))};
			styleData.setRootPath(filePath);
			styleDataMap.insert(make_pair(styleData.getId(), styleData));
		}
	}
	void loadLevelData(const string& mPath)
	{
		for(auto filePath : getScan<Mode::Single, Type::File, Pick::ByExt>(mPath + "Levels/", ".json"))
		{
			Json::Value root{getRootFromFile(filePath)};
			string luaScriptPath{mPath + "Scripts/" + root["lua_file"].asString()};

			LevelData levelData{loadLevelFromJson(root)};
			levelData.setPackPath(mPath);
			levelData.setLevelRootPath(filePath);
			levelData.setStyleRootPath(getStyleData(levelData.getStyleId()).getRootPath());
			levelData.setLuaScriptPath(luaScriptPath);
			levelDataMap.insert(make_pair(levelData.getId(), levelData));
			levelIdsByPackMap[levelData.getPackPath()].push_back(levelData.getId());
		}
	}
	void loadProfiles()
	{
		for(auto filePath : getScan<Mode::Single, Type::File, Pick::ByExt>("Profiles/", ".json"))
		{
			string fileName{getNameFromPath(filePath, "Profiles/", ".json")};

			ProfileData profileData{loadProfileFromJson(getRootFromFile(filePath))};
			profileDataMap.insert(make_pair(profileData.getName(), profileData));
		}
	}
	void loadEvents(const string& mPath)
	{
		for(auto filePath : getScan<Mode::Single, Type::File, Pick::ByExt>(mPath + "Events/", ".json"))
		{
			EventData eventData{getRootFromFile(filePath)};
			eventDataMap.insert(make_pair(eventData.getId(), eventData));
		}
	}

	void saveCurrentProfile()
	{
		if(currentProfilePtr == nullptr) return;

		Json::StyledStreamWriter writer;
		ofstream o{getCurrentProfileFilePath(), std::ifstream::binary};

		Json::Value profileRoot;
		profileRoot["version"] = getVersion();
		profileRoot["name"] = getCurrentProfile().getName();
		profileRoot["scores"] = getCurrentProfile().getScores();
		for(const auto& n : getCurrentProfile().getTrackedNames()) profileRoot["trackedNames"].append(n);

		writer.write(o, profileRoot); o.flush(); o.close();
	}

	vector<LevelData> getAllLevelData()
	{
		vector<LevelData> result;
		for(auto pair : levelDataMap) result.push_back(pair.second);
		return result;
	}
	vector<string> getAllLevelIds()
	{
		vector<LevelData> levelDataVector{getAllLevelData()};
		sort(begin(levelDataVector), end(levelDataVector),
		[](LevelData a, LevelData b)
		{
			if(a.getPackPath() == b.getPackPath()) return a.getMenuPriority() < b.getMenuPriority();
			return a.getPackPath() < b.getPackPath();
		});

		vector<string> result;
		for(auto levelData : levelDataVector) if(levelData.getSelectable()) result.push_back(levelData.getId());
		return result;
	}
	vector<string> getLevelIdsByPack(string mPackPath)
	{
		vector<LevelData> levelDataVector;
		for(string id : levelIdsByPackMap[mPackPath]) levelDataVector.push_back(getLevelData(id));

		sort(begin(levelDataVector), end(levelDataVector),
		[](LevelData a, LevelData b)
		{
			return a.getMenuPriority() < b.getMenuPriority();
		});

		vector<string> result;
		for(auto levelData : levelDataVector) if(levelData.getSelectable()) result.push_back(levelData.getId());
		return result;
	}
	vector<string> getPackPaths() { return packPaths; }
	vector<string> getPackNames()
	{
		vector<string> result;
		for(const auto& packPair : packDataMap) result.push_back(packPair.first);
		return result;
	}

	void refreshVolumes()
	{
		for(const auto& pair : assetManager.getSounds()) pair.second->setVolume(getSoundVolume());
		for(const auto& pair : assetManager.getMusics()) pair.second->setVolume(getMusicVolume());
	}
	void stopAllMusic() { assetManager.stopMusics(); }
	void stopAllSounds() { assetManager.stopSounds(); }
	void playSound(const string& mId)
	{
		if(getNoSound()) return;
		auto soundPtr(getSoundPtr(mId));
		if(soundPtr == nullptr) return;
		soundPtr->play();
	}

	Font& getFont(const string& mId) 				{ return assetManager.getFont(mId); }
	Sound* getSoundPtr(const string& mId) 			{ return assetManager.hasSound(mId) ? &assetManager.getSound(mId) : nullptr; }
	Music* getMusicPtr(const string& mId) 			{ return assetManager.hasMusic(mId) ? &assetManager.getMusic(mId) : nullptr; }
	MusicData getMusicData(const string& mId) 		{ return musicDataMap.find(mId)->second; }
	StyleData getStyleData(const string& mId) 		{ return styleDataMap.find(mId)->second; }
	LevelData getLevelData(const string& mId) 		{ return levelDataMap.find(mId)->second; }
	PackData getPackData(const string& mId) 		{ return packDataMap.find(mId)->second; }

	float getScore(const string& mId) 				{ return getCurrentProfile().getScore(mId); }
	void setScore(const string& mId, float mScore)	{ getCurrentProfile().setScore(mId, mScore); }

	void setCurrentProfile(const string& mName) { currentProfilePtr = &profileDataMap.find(mName)->second; }
	ProfileData& getCurrentProfile() { return *currentProfilePtr; }
	string getCurrentProfileFilePath() { return "Profiles/" + currentProfilePtr->getName() + ".json"; }
	void createProfile(const string& mName)
	{
		ofstream o{"Profiles/" + mName + ".json"};
		Json::Value root;
		Json::StyledStreamWriter writer;

		root["name"] = mName;
		root["scores"] = Json::objectValue;
		writer.write(o, root);
		o.flush(); o.close();

		profileDataMap.clear();
		loadProfiles();
	}
	int getProfilesSize() { return profileDataMap.size(); }
	vector<string> getProfileNames()
	{
		vector<string> result;
		for(auto pair : profileDataMap) result.push_back(pair.second.getName());
		return result;
	}
	string getFirstProfileName() { return profileDataMap.begin()->second.getName(); }

	EventData* getEventData(const string& mId, HexagonGame* mHgPtr)
	{
		EventData* result = new EventData(eventDataMap.find(mId)->second);
		result->setHexagonGamePtr(mHgPtr);
		return result;
	}
}
void react(EjectResMsg ePacket) {
	map<int, InjectReqMsg>::iterator it = inTransitPackets.find(ePacket.id);
	if(it == inTransitPackets.end()) {
		cerr << "Error: couldn't find in transit packet " << ePacket.id << endl;
		exit(-1);
	}

	InjectReqMsg request = it->second;
	InjectReqMsg response;
	inTransitPackets.erase(it);

	map<int, transaction_t>::iterator trans = inTransitTransactions.find(request.address);

	trans->second.total_time += ePacket.elapsed;

	if(request.msgType == REQUEST &&
			(request.coType == WRITE || request.coType == READ)) {
		//Handle Read/Write Requests
		if((int) request.address == request.id) {
			//This is an initiating request. Should we forward it or go to
			//memory?
			bool isForwarded = g_toForward[g_hierClass][request.dest][request.coType].Generate() == 0;

			if(isForwarded) {
				int destination = g_forwardDest[g_hierClass][state][request.dest].Generate();
				destination = destination*2;
				if(destination % 2 != 0) {
					cerr << "Error: Invalid destination for forwarded request." << endl;
					exit();
				}

				QueuePacket(request.dest, destination, REQUEST, request.coType,
						CONTROL_SIZE, cycle + 1, request.address);

				if(request.coType == WRITE) {
					//How many invalidates to send
					int numInv = g_numInv[g_hierClass][state][request.dest].Generate();
					int s = state;

					if(numInv <= 0) {
						return;
					}

					//Ensure invalidate destinations are unique (i.e. no two
					//invalidate messages to the same destination)
					set<int> destinations;
					destinations.insert(destination); //Request already forwarded here
					while(destinations.size() != (unsigned int) numInv) {
						int dest = g_invDest[g_hierClass][s][request.dest].Generate();
						dest = dest*2;
						destinations.insert(dest);
					}

					for(set<int>::iterator it = destinations.begin();
							it != destinations.end(); ++it) {
						QueuePacket(request.dest, *it, REQUEST, INV,
								CONTROL_SIZE, cycle + 1, request.address);
						trans->second.invs_sent++;
					}
				}

			} else {
				//Access memory, queue up a data response for the future
				QueuePacket(request.dest, request.source, RESPONSE, DATA,
						DATA_SIZE, cycle + 80, request.address);
			}

			return;
		} else {
			//This is not an initiating request, so it's a forwarded request

			//Respond with Data
			QueuePacket(request.dest,
					trans->second.source, RESPONSE,
					DATA, DATA_SIZE, cycle + 1, request.address);
		}
	} else if(request.msgType == REQUEST &&
			(request.coType == PUTC || request.coType == PUTD)) {
		//Respond with WB_ACK
		QueuePacket(request.dest, request.source, RESPONSE, WB_ACK,
				CONTROL_SIZE, cycle + 1, request.address);
	} else if(request.msgType == REQUEST && request.coType == INV) {
		//Respond with Ack
		QueuePacket(request.dest, trans->second.source,
				RESPONSE, ACK, CONTROL_SIZE, cycle + 1, request.address);
	} else if(request.msgType == RESPONSE && request.coType == DATA) {
		trans->second.data_received = true;
		//Send unblock
		QueuePacket(inTransitTransactions[request.address].source,
				inTransitTransactions[request.address].dest, RESPONSE, UNBLOCK,
				CONTROL_SIZE, cycle + 1, request.address);
	} else if(request.msgType == RESPONSE && request.coType == ACK) {
		trans->second.acks_received++;
	} else if(request.msgType == RESPONSE && request.coType == UNBLOCK) {
                trans->second.unblock_received = true;
        }

	if(trans->second.Completed()) {
		inTransitTransactions.erase(trans);
	}
}
Exemple #4
0
	PackData getPackData(const string& mId) 		{ return packDataMap.find(mId)->second; }
Exemple #5
0
	int getProfilesSize() { return profileDataMap.size(); }
Exemple #6
0
        double PointSensor::getDistance(map<uint32_t, hesperia::data::environment::Polygon> &mapOfPolygons) {
            Point3 nearest;
            double distanceToSensor = -1;

            map<uint32_t, hesperia::data::environment::Polygon>::const_iterator it = mapOfPolygons.begin();
            while (it != mapOfPolygons.end()) {
                Polygon p = it->second;

                // Get overlapping parts of polygon...
                Polygon contour = m_FOV.intersectIgnoreZ(p);

                if (contour.getSize() > 0) {
                    // Get nearest point from contour.
                    const vector<Point3> listOfPoints = contour.getVertices();
                    vector<Point3>::const_iterator jt = listOfPoints.begin();

                    while (jt != listOfPoints.end()) {
                        Point3 pt = (*jt++);
                        double d = (pt - m_sensorPosition).lengthXY();

                        if (isInFOV(pt)) {
                            if ((distanceToSensor < 0) || (d < distanceToSensor)) {
                                nearest = pt;
                                distanceToSensor = d;
                            }
                        }
                    }
                }

                it++;
            }

            if (distanceToSensor > m_clampDistance) {
                distanceToSensor = -1;
            }

            // Apply fault model.

            // Firstly, calculate the noise data if required.
            double fault = 0;
            if (!(distanceToSensor < 0)) {
                // Determine the random data from the range -1.0 .. 1.0 multiplied by the defined m_faultModelNoise.
                fault = ((100-(1 + (rand()%200)))/100.0) * m_faultModelNoise;

                distanceToSensor += fault;

                // If the distanceToSensor is less than zero, set the returned value to -1.
                if (distanceToSensor < 0) {
                    distanceToSensor = -1;
                }

                if ( (fault > 0) || (fault < 0) ) {
                    cerr << m_name << "(" << m_id << ")" << ": " << "faultModel.noise: " << "Adding " << fault << " to distance." << endl;
                }
            }

            // Secondly, check wether the current distance to be returned need to be skipped (i.e. overwritten by -1).
            // Thus, increment the current iteration.
            m_faultModelSkipCounter++;

            // Limit the counter range.
            if (m_faultModelSkipCounter == 100) {
                m_faultModelSkipCounter = 0;
            }

            if (m_faultModelSkip > 0) {
                unsigned int modulo = (unsigned int)(1.0/m_faultModelSkip);
                if ( (modulo == 0) || (m_faultModelSkipCounter % modulo)  == 0 ) {
                    cerr << m_name << "(" << m_id << ")" << ": " << "faultModel.skip: " << "Skipping current frame (" << m_faultModelSkip << "/" << m_faultModelSkipCounter << ")." << endl;

                    distanceToSensor = -1;
                }
            }

            return distanceToSensor;
        } 
Exemple #7
0
	StyleData getStyleData(const string& mId) 		{ return styleDataMap.find(mId)->second; }
Exemple #8
0
command_result df_autodump_destroy_item(color_ostream &out, vector <string> & parameters)
{
    // HOTKEY COMMAND; CORE ALREADY SUSPENDED
    if (!parameters.empty())
        return CR_WRONG_USAGE;

    df::item *item = Gui::getSelectedItem(out);
    if (!item)
        return CR_FAILURE;

    // Allow undoing the destroy
    if (world->frame_counter != last_frame)
    {
        last_frame = world->frame_counter;
        pending_destroy.clear();
    }

    if (pending_destroy.count(item->id))
    {
        df::item_flags old_flags = pending_destroy[item->id];
        pending_destroy.erase(item->id);

        item->flags.bits.garbage_colect = false;
        item->flags.bits.hidden = old_flags.bits.hidden;
        item->flags.bits.dump = old_flags.bits.dump;
        item->flags.bits.forbid = old_flags.bits.forbid;
        return CR_OK;
    }

    // Check the item is good to destroy
    if (item->flags.bits.garbage_colect)
    {
        out.printerr("Item is already marked for destroy.\n");
        return CR_FAILURE;
    }

    if (item->flags.bits.construction ||
        item->flags.bits.in_building ||
        item->flags.bits.artifact1)
    {
        out.printerr("Choosing not to destroy buildings, constructions and artifacts.\n");
        return CR_FAILURE;
    }

    for (size_t i = 0; i < item->itemrefs.size(); i++)
    {
        df::general_ref *ref = item->itemrefs[i];
        if (ref->getType() == general_ref_type::UNIT_HOLDER)
        {
            out.printerr("Choosing not to destroy items in unit inventory.\n");
            return CR_FAILURE;
        }
    }

    // Set the flags
    pending_destroy[item->id] = item->flags;

    item->flags.bits.garbage_colect = true;
    item->flags.bits.hidden = true;
    item->flags.bits.dump = true;
    item->flags.bits.forbid = true;
    return CR_OK;
}
Exemple #9
0
 Variant get(const char* set, const char* key) const {
     auto it = m_database.find(set);
     return (it == m_database.end() ? Variant() : it->second->get(key));
 }
Exemple #10
0
const string& Options::getName(OptionId id) {
  return names.at(id);
}
Exemple #11
0
vector<OptionId> Options::getOptions(OptionSet set) {
  return optionSets.at(set);
}
Exemple #12
0
vector<pair<int, double> > sortMapByValue(const map<int, double>& pccMap) {
    vector<pair<int, double> > vec(pccMap.begin(), pccMap.end());
    sort(vec.begin(), vec.end(), cmpPairbyValue);
    return vec;
}
Exemple #13
0
int main(int argc, char* argv[])
{
    int retval = 0;
    ForestT* forest = NULL;
    NetVT*   net_values_FF = NULL;
    int* retvals = NULL;
    IdType** thread_modules = NULL;
    NetVT**  net_values_E = NULL;

    do
    {
        if ((retval = ReadInput(argc, argv))) break;
        if ((retval = MakeOrder()          )) break;
        if ((retval = GetDependency()      )) break;

        #pragma omp parallel
        {
            int thread_num = omp_get_thread_num();
            int num_threads = omp_get_num_threads();

            #pragma omp single
            {
                do
                {
                    retvals = new int[num_threads];
                    memset(retvals, 0, sizeof(int) * num_threads);
                    forest = new ForestT;
                    if ((retvals[thread_num] = forest->Init(num_threads, num_inputs, net_widths))) break;
                    thread_inputs = new ValueType*[num_threads];
                    thread_outputs = new ValueType*[num_threads];
                    thread_modules = new IdType*[num_threads];
                    for (SizeType i=0; i<num_threads; i++)
                    {
                        thread_inputs[i] = new ValueType[max_num_inputs];
                        thread_outputs[i] = new ValueType[max_num_outputs];
                        thread_modules[i] = new IdType[num_modules];
                    } 

                    net_values_FF = new NetVT[num_nets];
                    //prepare the inputs
                    for (SizeType i=0; i<num_inputs; i++)
                    {
                        MapT* map = &net_values_FF[i].root_Ids;
                        for (ValueType j=0; j< (1<<net_widths[i]); j++)
                        {
                            IdType temp_Id = NULL_Id;
                            retvals[thread_num] = forest->NewTree(thread_num, i, j, temp_Id);
                            if (retvals[thread_num] != 0) break;
                            map->insert(MapTP(j, temp_Id));
                        }
                    }
                    for (IdType i=0; i<num_modules; i++)
                        thread_modules[thread_num][i] = i;

                    // Evaluate the FF cicuit
                    if ((retvals[thread_num] = Evaluate(num_modules, thread_modules[thread_num], net_values_FF, NULL, forest, thread_num))) break;

                    if ((retvals[thread_num] = GenerateErrors())) break;
                    net_values_E = new NetVT*[num_errors];
                    for (SizeType i=0; i<num_errors; i++)
                        net_values_E[i] = new NetVT[num_nets];
                } while(0);

            }

            #pragma omp for
            for (IdType i=0; i<num_errors; i++)
            {
                if (retvals[thread_num] != 0) continue;
                IdType error_type = error_types.find(i)->second;
                IdType error_Id   = error_Ids  .find(i)->second;
                IdType error_ref  = error_refs .find(i)->second;
                IdType error_cond = error_conds.find(i)->second;
                IdType start_module_Id = NULL_Id;
                SizeType module_count = 0;
                
                // Place the error
                if ((retvals[thread_num] = ProcessError(error_type, error_Id, error_ref, error_cond, 
                    net_values_FF, net_values_E[i], start_module_Id, forest, thread_num))) continue;
                if (start_module_Id == NULL_Id) continue;

                // Get list of modules to evaluate
                if ((retvals[thread_num] = GetModuleList(start_module_Id, module_count, thread_modules[thread_num]))) continue;
                // Evaluate the faulty circuit
                if ((retvals[thread_num] = Evaluate(module_count, thread_modules[thread_num], net_values_FF, net_values_E[i], forest, thread_num))) continue;
            } 

            if (retvals[thread_num] != 0) cerr<<"Thread "<<thread_num<<" terminated with error code "<<retvals[thread_num]<<endl;
        }
    } while(0);

    if (retval != 0) cerr<<"Terminated with error code "<<retval<<endl;
    return retval;
}
Exemple #14
0
int ReadInput(int argc, char* argv[])
{
    ifstream  fin;
    int       retval      = 0;
    pair<map<string, IdType>::iterator, bool> ret;

    if (argc < 2)
    {
        cout<<"Error: no input file name"<<endl;
        return 1;
    }
    fin.open(argv[1]);
    if (!fin.is_open())
    {
        cout<<"Error: cannot open input file "<<argv[1]<<endl;
        return 2;
    }

    fin>>num_modules;
    modules = new ModuleT*[num_modules];
    for (SizeType i=0; i<num_modules; i++)
    {
        string module_type="", str="";
        fin>>module_type;
        transform(module_type.begin(), module_type.end(), 
                  module_type.begin(), ::tolower);
        getline(fin, str);
        //cout<<module_type<<"|"<<str<<endl;
        if      (module_type == "cross") 
            modules[i] = new Connecter<IdType, ValueType, SizeType>();
        else if (module_type == "not"    )
            modules[i] = new NotGate  <IdType, ValueType, SizeType>();
        else if (module_type == "or"     )
            modules[i] = new OrGate   <IdType, ValueType, SizeType>();
        else if (module_type == "xor"    )
            modules[i] = new XorGate  <IdType, ValueType, SizeType>();
        else if (module_type == "nor"    )
            modules[i] = new NorGate  <IdType, ValueType, SizeType>();
        else if (module_type == "and"    )
            modules[i] = new AndGate  <IdType, ValueType, SizeType>();
        else if (module_type == "xand"   )
            modules[i] = new XandGate <IdType, ValueType, SizeType>();
        else if (module_type == "nand"   )
            modules[i] = new NandGate <IdType, ValueType, SizeType>();
        else if (module_type == "add"    )
            modules[i] = new Adder    <IdType, ValueType, SizeType>();
        else if (module_type == "subtract")
            modules[i] = new Subtractor<IdType, ValueType, SizeType>();
        else if (module_type == "enable" )
            modules[i] = new Enabler   <IdType, ValueType, SizeType>();
        else if (module_type == "mux"    )
            modules[i] = new Mux       <IdType, ValueType, SizeType>();
        else if (module_type == "demux" )
            modules[i] = new Demux     <IdType, ValueType, SizeType>();
        else {
            cerr<<"Error ["<<__FILE__<<","<<__LINE__<<"]: "
                <<" Module type "<<module_type<<" invalid"<<endl;
            return 8;
        }
        retval = modules[i]->Readin(str);
        if (retval != 0) return retval;
        if (modules[i]->num_inputs > max_num_inputs) max_num_inputs = modules[i]->num_inputs;
        if (modules[i]->num_outputs > max_num_outputs) max_num_outputs = modules[i]->num_outputs;
        
        for (SizeType j=0; j<modules[i]->num_inputs; j++)
        {
            ret = net_map.insert(
                pair<string, IdType>(modules[i]->input_names[j], num_nets));
            if (ret.second != false) num_nets++;
            modules[i]->input_Ids[j] = ret.first->second;
        }
        for (SizeType j=0; j<modules[i]->num_outputs; j++)
        {
            ret = net_map.insert(
                pair<string, IdType>(modules[i]->output_names[j], num_nets));
            if (ret.second != false) num_nets++;
            modules[i]->output_Ids[j] = ret.first->second;
        }

        //cout<<modules[i]->name << ":" << modules[i]->type;
        //for (SizeType j=0; j<modules[i]->num_inputs; j++)
        //    cout<<" "<<modules[i]->input_names[j]<<","<<modules[i]->input_Ids[j];
        //cout<<" -> ";
        //for (SizeType j=0; j<modules[i]->num_outputs; j++)
        //    cout<<" "<<modules[i]->output_names[j]<<","<<modules[i]->output_Ids[j];
        //cout<<endl;
    }
    num_nets = net_map.size();
    cout<<"#Modules = "<<num_modules<<" #Nets = "<<num_nets<<endl;

    fin>>num_inputs;
    net_widths = new SizeType[num_nets];
    inputs = new IdType[num_inputs];
    memset(net_widths, 0, sizeof(SizeType) * num_nets);
    for (SizeType i=0; i<num_nets; i++)
    {
        string str;
        fin>>str;
        transform(str.begin(), str.end(), str.begin(), ::tolower);
        map<string, IdType>::iterator it = net_map.find(str);
        if (it == net_map.end())
        {
            cerr<<"Error ["<<__FILE__<<","<<__LINE__<<"]: "
                <<" Net "<<str<<" cannot be found"<<endl;
            return 9;
        }
        fin>>net_widths[it->second];
        if (i<num_inputs) inputs[i] = it->second;
    }
    fin.close(); 
    return 0;
}
Exemple #15
0
int main()
{
#ifndef ONLINE_JUDGE
    freopen("vd.inp","r",stdin);
    freopen("vd.out","w",stdout);
#endif
    scanf("%d%d%d%d%d%d",&m,&n,&t,&tp,&tu,&td);
    int i,j,u,kq=-1;
    set<int>::iterator it;
    int kqi,kqj,kqu,kqv,tg;
    for(i=1; i<=m; ++i)
    {
        for(j=1; j<=n; ++j) scanf("%d",&a[i][j]);
    }
    for(i=1; i<m; ++i)
    {
        for(u=i+1; u<=m; ++u)
        {
            for(j=1; j<=n; ++j) f[i][u][j]=f[i][u-1][j]+g(u-1,j,u,j);
        }
    }
    for(i=m; i>1; --i)
    {
        for(u=i-1; u>=1; --u)
        {
            for(j=1; j<=n; ++j) f[i][u][j]=f[i][u+1][j]+g(u+1,j,u,j);
        }
    }
    for(i=1; i+2<=m; ++i)
    {
        for(u=i+2; u<=m; ++u)
        {
            mm.clear();
            ms.clear();
            h[1]=-f[u][i][1];
            ms.insert(h[1]);
            mm[h[1]]=1;
            h[2]=-f[u][i][2]+g(i,1,i,2)+g(u,2,u,1);
            tg=g(i,1,i,2)+g(u,2,u,1);
            for(j=3; j<=n; ++j)
            {
                tg+=g(i,j-1,i,j)+g(u,j,u,j-1);
                it=ms.lower_bound(tg+f[i][u][j]-t);
                if (it!=ms.end())
                {
                    if (kq==-1 || abs(tg+f[i][u][j]-*it-t)<abs(kq-t))
                    {
                        kq=tg+f[i][u][j]-*it;
                        kqi=i;
                        kqj=mm[*it];
                        kqu=u;
                        kqv=j;
                    }
                }
                if (it!=ms.begin())
                {
                    it--;
                    if (kq==-1 || abs(tg+f[i][u][j]-*it-t)<abs(kq-t))
                    {
                        kq=tg+f[i][u][j]-*it;
                        kqi=i;
                        kqj=mm[*it];
                        kqu=u;
                        kqv=j;
                    }
                }
                h[j]=tg-f[u][i][j];
                ms.insert(h[j-1]);
                mm[h[j-1]]=j-1;
            }
        }
    }
    printf("%d %d %d %d",kqi,kqj,kqu,kqv);
}
void NiLookAtInterpolator::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, const NifInfo & info ) const {
	//--BEGIN PRE-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//

	NiInterpolator::Write( out, link_map, info );
	NifStream( unknownShort, out, info );
	if ( info.version < VER_3_3_0_13 ) {
		WritePtr32( &(*lookAt), out );
	} else {
		if ( lookAt != NULL ) {
			map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(lookAt) );
			if (it != link_map.end()) {
				NifStream( it->second, out, info );
			} else {
				NifStream( 0xFFFFFFFF, out, info );
			}
		} else {
			NifStream( 0xFFFFFFFF, out, info );
		}
	}
	NifStream( target, out, info );
	NifStream( translation, out, info );
	NifStream( rotation, out, info );
	NifStream( scale, out, info );
	if ( info.version < VER_3_3_0_13 ) {
		WritePtr32( &(*unknownLink1), out );
	} else {
		if ( unknownLink1 != NULL ) {
			map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(unknownLink1) );
			if (it != link_map.end()) {
				NifStream( it->second, out, info );
			} else {
				NifStream( 0xFFFFFFFF, out, info );
			}
		} else {
			NifStream( 0xFFFFFFFF, out, info );
		}
	}
	if ( info.version < VER_3_3_0_13 ) {
		WritePtr32( &(*unknownLink2), out );
	} else {
		if ( unknownLink2 != NULL ) {
			map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(unknownLink2) );
			if (it != link_map.end()) {
				NifStream( it->second, out, info );
			} else {
				NifStream( 0xFFFFFFFF, out, info );
			}
		} else {
			NifStream( 0xFFFFFFFF, out, info );
		}
	}
	if ( info.version < VER_3_3_0_13 ) {
		WritePtr32( &(*unknownLink3), out );
	} else {
		if ( unknownLink3 != NULL ) {
			map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(unknownLink3) );
			if (it != link_map.end()) {
				NifStream( it->second, out, info );
			} else {
				NifStream( 0xFFFFFFFF, out, info );
			}
		} else {
			NifStream( 0xFFFFFFFF, out, info );
		}
	}

	//--BEGIN POST-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//
}
/* ****************************************************************************
*
* addTriggeredSubscriptions -
*/
static bool addTriggeredSubscriptions
(
  ContextRegistration                   cr,
  map<string, TriggeredSubscription*>&  subs,
  std::string&                          err,
  std::string                           tenant
)
{

  BSONArrayBuilder          entitiesNoPatternA;
  std::vector<std::string>  idJsV;
  std::vector<std::string>  typeJsV;

  for (unsigned int ix = 0; ix < cr.entityIdVector.size(); ++ix)
  {
    // FIXME: take into account subscriptions with no type
    EntityId* enP = cr.entityIdVector[ix];

    // The registration of isPattern=true entities is not supported, so we don't include them here
    if (enP->isPattern == "false")
    {
      entitiesNoPatternA.append(BSON(CASUB_ENTITY_ID << enP->id <<
                                     CASUB_ENTITY_TYPE << enP->type <<
                                     CASUB_ENTITY_ISPATTERN << "false"));
      idJsV.push_back(enP->id);
      typeJsV.push_back(enP->type);
    }
  }

  BSONArrayBuilder attrA;
  for (unsigned int ix = 0; ix < cr.contextRegistrationAttributeVector.size(); ++ix)
  {
    ContextRegistrationAttribute* craP = cr.contextRegistrationAttributeVector[ix];
    attrA.append(craP->name);
  }

  BSONObjBuilder queryNoPattern;
  queryNoPattern.append(CASUB_ENTITIES, BSON("$in" << entitiesNoPatternA.arr()));
  if (attrA.arrSize() > 0)
  {
    // If we don't do this checking, the {$in: [] } in the attribute name part will
    // make the query fail
    //

    // queryB.append(CASUB_ATTRS, BSON("$in" << attrA.arr()));
    queryNoPattern.append("$or", BSON_ARRAY(
                            BSON(CASUB_ATTRS << BSON("$in" << attrA.arr())) <<
                            BSON(CASUB_ATTRS << BSON("$size" << 0))));
  }
  else
  {
    queryNoPattern.append(CASUB_ATTRS, BSON("$size" << 0));
  }
  queryNoPattern.append(CASUB_EXPIRATION, BSON("$gt" << (long long) getCurrentTime()));


  //
  // This is JavaScript code that runs in MongoDB engine. As far as I know, this is the only
  // way to do a "reverse regex" query in MongoDB (see
  // http://stackoverflow.com/questions/15966991/mongodb-reverse-regex/15989520).
  // Note that although we are using a isPattern=true in the MongoDB query besides $where, we
  // also need to check that in the if statement in the JavaScript function given that a given
  // sub document could include both isPattern=true and isPattern=false documents
  //
  std::string idJsString = "[ ";

  for (unsigned int ix = 0; ix < idJsV.size(); ++ix)
  {
    if (ix != idJsV.size() - 1)
    {
      idJsString += "\""+idJsV[ix]+ "\" ,";
    }
    else
    {
      idJsString += "\"" +idJsV[ix]+ "\"";
    }
  }
  idJsString += " ]";

  std::string typeJsString = "[ ";

  for (unsigned int ix = 0; ix < typeJsV.size(); ++ix)
  {
    if (ix != typeJsV.size() - 1)
    {
      typeJsString += "\"" +typeJsV[ix] + "\" ,";
    }
    else
    {
      typeJsString += "\"" + typeJsV[ix] + "\"";
    }
  }
  typeJsString += " ]";

  std::string function = std::string("function()") +
    "{" +
      "enId = " + idJsString + ";" +
      "enType = " + typeJsString + ";" +
      "for (var i=0; i < this." + CASUB_ENTITIES + ".length; i++) {" +
        "if (this." + CASUB_ENTITIES + "[i]." + CASUB_ENTITY_ISPATTERN + " == \"true\") {" +
          "for (var j = 0; j < enId.length; j++) {" +
            "if (enId[j].match(this." + CASUB_ENTITIES + "[i]." + CASUB_ENTITY_ID +
              ") && this." + CASUB_ENTITIES + "[i]." + CASUB_ENTITY_TYPE + " == enType[j]) {" +
              "return true; " +
            "}" +
          "}" +
        "}" +
      "}" +
      "return false; " +
    "}";
  LM_T(LmtMongo, ("JS function: %s", function.c_str()));


  std::string     entPatternQ = CSUB_ENTITIES "." CSUB_ENTITY_ISPATTERN;
  BSONObjBuilder  queryPattern;

  queryPattern.append(entPatternQ, "true");
  queryPattern.append(CASUB_EXPIRATION, BSON("$gt" << (long long) getCurrentTime()));
  queryPattern.appendCode("$where", function);

  auto_ptr<DBClientCursor> cursor;
  BSONObj                  query = BSON("$or" << BSON_ARRAY(queryNoPattern.obj() << queryPattern.obj()));

  TIME_STAT_MONGO_READ_WAIT_START();
  DBClientBase* connection = getMongoConnection();
  if (!collectionQuery(connection, getSubscribeContextAvailabilityCollectionName(tenant), query, &cursor, &err))
  {
    TIME_STAT_MONGO_READ_WAIT_STOP();
    releaseMongoConnection(connection);
    return false;
  }
  TIME_STAT_MONGO_READ_WAIT_STOP();

  /* For each one of the subscriptions found, add it to the map (if not already there) */
  while (moreSafe(cursor))
  {
    BSONObj     sub;
    std::string err;
    if (!nextSafeOrErrorF(cursor, &sub, &err))
    {
      LM_E(("Runtime Error (exception in nextSafe(): %s - query: %s)", err.c_str(), query.toString().c_str()));
      continue;
    }
    BSONElement idField = getFieldF(sub, "_id");

    //
    // BSONElement::eoo returns true if 'not found', i.e. the field "_id" doesn't exist in 'sub'
    //
    // Now, if 'getFieldF(sub, "_id")' is not found, if we continue, calling OID() on it, then we get
    // an exception and the broker crashes.
    //
    if (idField.eoo() == true)
    {
      std::string details = std::string("error retrieving _id field in doc: '") + sub.toString() + "'";
      alarmMgr.dbError(details);
      continue;
    }
    alarmMgr.dbErrorReset();

    std::string subIdStr = idField.OID().toString();

    if (subs.count(subIdStr) == 0)
    {
      ngsiv2::HttpInfo httpInfo;

      httpInfo.url = getStringFieldF(sub, CASUB_REFERENCE);

      LM_T(LmtMongo, ("adding subscription: '%s'", sub.toString().c_str()));

      //
      // FIXME P4: Once ctx availability notification formats get defined for NGSIv2,
      //           the first parameter for TriggeredSubscription will have "normalized" as default value
      //
      TriggeredSubscription* trigs = new TriggeredSubscription(
        sub.hasField(CASUB_FORMAT)? stringToRenderFormat(getStringFieldF(sub, CASUB_FORMAT)) : NGSI_V1_LEGACY,
        httpInfo,
        subToAttributeList(sub));

      subs.insert(std::pair<string, TriggeredSubscription*>(subIdStr, trigs));
    }
  }
  releaseMongoConnection(connection);

  return true;
}
void NiBoneLODController::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, const NifInfo & info ) const {
	//--BEGIN PRE-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//

	NiTimeController::Write( out, link_map, info );
	numShapeGroups2 = (unsigned int)(shapeGroups2.size());
	numShapeGroups = (unsigned int)(shapeGroups1.size());
	numNodeGroups = (unsigned int)(nodeGroups.size());
	NifStream( unknownInt1, out, info );
	NifStream( numNodeGroups, out, info );
	NifStream( numNodeGroups2, out, info );
	for (unsigned int i1 = 0; i1 < nodeGroups.size(); i1++) {
		nodeGroups[i1].numNodes = (unsigned int)(nodeGroups[i1].nodes.size());
		NifStream( nodeGroups[i1].numNodes, out, info );
		for (unsigned int i2 = 0; i2 < nodeGroups[i1].nodes.size(); i2++) {
			if ( info.version < VER_3_3_0_13 ) {
				NifStream( (unsigned int)&(*nodeGroups[i1].nodes[i2]), out, info );
			} else {
				if ( nodeGroups[i1].nodes[i2] != NULL ) {
					NifStream( link_map.find( StaticCast<NiObject>(nodeGroups[i1].nodes[i2]) )->second, out, info );
				} else {
					NifStream( 0xFFFFFFFF, out, info );
				}
			}
		};
	};
	if ( info.version <= 0x0A000100 ) {
		NifStream( numShapeGroups, out, info );
		for (unsigned int i2 = 0; i2 < shapeGroups1.size(); i2++) {
			shapeGroups1[i2].numLinkPairs = (unsigned int)(shapeGroups1[i2].linkPairs.size());
			NifStream( shapeGroups1[i2].numLinkPairs, out, info );
			for (unsigned int i3 = 0; i3 < shapeGroups1[i2].linkPairs.size(); i3++) {
				if ( info.version < VER_3_3_0_13 ) {
					NifStream( (unsigned int)&(*shapeGroups1[i2].linkPairs[i3].shape), out, info );
				} else {
					if ( shapeGroups1[i2].linkPairs[i3].shape != NULL ) {
						NifStream( link_map.find( StaticCast<NiObject>(shapeGroups1[i2].linkPairs[i3].shape) )->second, out, info );
					} else {
						NifStream( 0xFFFFFFFF, out, info );
					}
				}
				if ( info.version < VER_3_3_0_13 ) {
					NifStream( (unsigned int)&(*shapeGroups1[i2].linkPairs[i3].skinInstance), out, info );
				} else {
					if ( shapeGroups1[i2].linkPairs[i3].skinInstance != NULL ) {
						NifStream( link_map.find( StaticCast<NiObject>(shapeGroups1[i2].linkPairs[i3].skinInstance) )->second, out, info );
					} else {
						NifStream( 0xFFFFFFFF, out, info );
					}
				}
			};
		};
		NifStream( numShapeGroups2, out, info );
		for (unsigned int i2 = 0; i2 < shapeGroups2.size(); i2++) {
			if ( info.version < VER_3_3_0_13 ) {
				NifStream( (unsigned int)&(*shapeGroups2[i2]), out, info );
			} else {
				if ( shapeGroups2[i2] != NULL ) {
					NifStream( link_map.find( StaticCast<NiObject>(shapeGroups2[i2]) )->second, out, info );
				} else {
					NifStream( 0xFFFFFFFF, out, info );
				}
			}
		};
	};

	//--BEGIN POST-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//
}
Exemple #19
0
	MusicData getMusicData(const string& mId) 		{ return musicDataMap.find(mId)->second; }
void  loadLabelledScene()
{

    mrpt::opengl::COpenGLScenePtr   labelledScene;

    labelledScene = mrpt::opengl::COpenGLScene::Create();
    if ( labelledScene->loadFromFile( configuration.labelledScene ) )
    {
        // Load previously inserted boxes
        bool keepLoading = true;
        size_t boxes_inserted = 0;

        while ( keepLoading )
        {
            CBoxPtr box = labelledScene->getByClass<CBox>(boxes_inserted);

            if ( box.null() )
                keepLoading = false;
            else
            {
                TLabelledBox labelled_box;

                labelled_box.box = box;
                labelled_box.label = box->getName();

                TPose3D pose = box->getPose();

                TPoint3D c1,c2;
                box->getBoxCorners(c1,c2);

                TPoint3D C111 ( CPose3D(pose) + TPose3D(TPoint3D(c1.x,c1.y,c1.z)) );
                TPoint3D C112 ( CPose3D(pose) + TPose3D(TPoint3D(c1.x,c1.y,c2.z)) );
                TPoint3D C121 ( CPose3D(pose) + TPose3D(TPoint3D(c1.x,c2.y,c1.z)) );
                TPoint3D C122 ( CPose3D(pose) + TPose3D(TPoint3D(c1.x,c2.y,c2.z)) );
                TPoint3D C211 ( CPose3D(pose) + TPose3D(TPoint3D(c2.x,c1.y,c1.z)) );
                TPoint3D C212 ( CPose3D(pose) + TPose3D(TPoint3D(c2.x,c1.y,c2.z)) );
                TPoint3D C221 ( CPose3D(pose) + TPose3D(TPoint3D(c2.x,c2.y,c1.z)) );
                TPoint3D C222 ( CPose3D(pose) + TPose3D(TPoint3D(c2.x,c2.y,c2.z)) );

                pcl::PointCloud<pcl::PointXYZ>::Ptr pointCloud ( new pcl::PointCloud<pcl::PointXYZ>());
                pointCloud->push_back( pcl::PointXYZ( C111.x, C111.y, C111.z ));
                pointCloud->push_back( pcl::PointXYZ( C112.x, C112.y, C112.z ));
                pointCloud->push_back( pcl::PointXYZ( C121.x, C121.y, C121.z ));
                pointCloud->push_back( pcl::PointXYZ( C122.x, C122.y, C122.z ));
                pointCloud->push_back( pcl::PointXYZ( C211.x, C211.y, C211.z ));
                pointCloud->push_back( pcl::PointXYZ( C212.x, C212.y, C212.z ));
                pointCloud->push_back( pcl::PointXYZ( C221.x, C221.y, C221.z ));
                pointCloud->push_back( pcl::PointXYZ( C222.x, C222.y, C222.z ));

                pcl::ConvexHull<pcl::PointXYZ> convex_hull;
                convex_hull.setInputCloud(pointCloud);
                convex_hull.setDimension(3);
                convex_hull.reconstruct(*labelled_box.convexHullCloud,
                                        labelled_box.polygons);

                Eigen::Matrix4f transMat;

                transMat(0,0)=0;    transMat(0,1)=-1;     transMat(0,2)=0;    transMat(0,3)=0;
                transMat(1,0)=0;    transMat(1,1)=0;      transMat(1,2)=+1;   transMat(1,3)=0;
                transMat(2,0)=1;    transMat(2,1)=0;      transMat(2,2)=0;    transMat(2,3)=0;
                transMat(3,0)=0;    transMat(3,1)=0;      transMat(3,2)=0;    transMat(3,3)=1;

                pcl::transformPointCloud( *labelled_box.convexHullCloud,
                                          *labelled_box.convexHullCloud,
                                          transMat );

                v_labelled_boxes.push_back( labelled_box );

                if ( !configuration.instancesLabeled )
                {
                    if ( !m_consideredLabels.count(labelled_box.label) )
                        cout << "[CAUTION] label " << labelled_box.label << " does not appear in the label list." << endl;
                }
                else
                {
                    string label = getInstanceLabel(labelled_box.label);
                    if ( label.empty() )
                        cout << "[CAUTION] label of instance " << labelled_box.label << " does not appear in the label list." << endl;
                }


                // Check if the label has been already inserted
                if ( find(v_appearingLabels.begin(),
                          v_appearingLabels.end(),
                          labelled_box.label) == v_appearingLabels.end() )
                    v_appearingLabels.push_back(labelled_box.label);
            }

            boxes_inserted++;
        }

        cout << "[INFO] " << v_labelled_boxes.size() <<  " labelled boxes loaded." << endl;

    }
    else
        cout << "[ERROR] While loading the labelled scene file." << endl;

}
Exemple #21
0
	LevelData getLevelData(const string& mId) 		{ return levelDataMap.find(mId)->second; }
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function Name:
// Purpose:
// Inputs:
// Output:
// Notes:
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
void ExpressionBuilder::withVariables(const map<string, double> &variableMap) {
	for (map<string, double>::const_iterator iter = variableMap.begin(); iter != variableMap.end(); iter++) {
		pair<string, double> obj((*iter).first, (*iter).second);
		m_variables.insert(obj);
	}
}
Exemple #23
0
	void setCurrentProfile(const string& mName) { currentProfilePtr = &profileDataMap.find(mName)->second; }
Exemple #24
0
int main (int argc, char** argv) {
	
//	cerr << "Before" << endl;
	if (argc == 1){
		cerr << "Usage: merge_gc-plp " << "<in.plp> <in.gc> > <out.cvgc>\n";
		return 0;  
	}
//	cerr << "After" << endl;

	string str = argv[1];
	ifstream cov_in(str.c_str());
	string ctg;
	int pos;
	char b;
	int cov;
	site* s;
	map<int,site>* sites;
	while (cov_in.good()){
		getline(cov_in,ctg,'\t');
		getline(cov_in,str,'\t');
		pos = atoi(str.c_str());
		getline(cov_in,str,'\t');
		b = str.at(0);
		getline(cov_in,str,'\t');
		cov = atoi(str.c_str());
		getline(cov_in,str);
		s = new site; 
		s->ctg = ctg;
		s->pos = pos;
		s->b = b;
		s->cov = cov;
		s->gc = -1.0;
		sites = &(table.find(ctg)->second);
		if (sites == &(table.end()->second)){
			sites = new map<int,site>();
			(*sites)[pos] = *s;	
			table[ctg] = *sites;
			order.push_back(ctg);
		} else {
			(*sites)[pos] = *s;	
		}
	}	
	str = argv[2];
	ifstream gc_in(str.c_str());
	double gc;
//	while(gc_in.good()){
	while(getline(gc_in,ctg,'\t')){ //;
		getline(gc_in,str,'\t');
		pos = atoi(str.c_str());
		getline(gc_in,str);
		gc = atof(str.c_str());
		sites = &(table.find(ctg)->second);
		if (sites == &(table.end()->second)){
			sites = new map<int,site>();
			s = new site; 
			s->ctg = ctg;
			s->pos = pos;
			s->b = '-';
			s->cov = 0;
			s->gc = gc;
			(*sites)[pos] = *s;
			table[ctg] = *sites;
			order.push_back(ctg);
		} else {
			s = &(sites->find(pos)->second);
			if (s == &(sites->end()->second)){
				s = new site; 
				s->ctg = ctg;
				s->pos = pos;
				s->b = '-';
				s->cov = 0;
				s->gc = gc;
				(*sites)[pos] = *s;
			} else 
				s->gc = gc;
		}
	}

	list<string>::iterator ctg_it;
	map<int,site>::iterator site_it;
	cout << "ctg\tpos\tbase\tcov\tgc" << endl; 
	for (ctg_it = order.begin(); ctg_it != order.end(); ctg_it++){
		sites = &(table.find(*ctg_it)->second);
		for (site_it = sites->begin(); site_it != sites->end(); site_it++){
			s = &(site_it->second);
			if (s->complete() || KEEP_ALL)
				printSite(*s,cout);
		}	
	}
	

}
Exemple #25
0
	string getFirstProfileName() { return profileDataMap.begin()->second.getName(); }
Exemple #26
0
//Process groups by computing percentiles for each item and lo-values for each group
//groups: genes
//lists: a set of different groups. Comparison will be performed on individual list
int ProcessGroups(GROUP_STRUCT *groups, int groupNum, LIST_STRUCT *lists, int listNum, double maxPercentile)
{
	int i,j;
	int listIndex, index1, index2;
	int maxItemPerGroup;
	double *tmpF;
	double *tmpProb;
	bool isallone; // check if all the probs are 1; if yes, do not use accumulation of prob. scores
	
	maxItemPerGroup = 0;

  PRINT_DEBUG=1;
	
	for (i=0;i<groupNum;i++){
		if (groups[i].itemNum>maxItemPerGroup){
			maxItemPerGroup = groups[i].itemNum;
		}
	}
	
	assert(maxItemPerGroup>0);
	
	tmpF = new double[maxItemPerGroup];
	tmpProb = new double [maxItemPerGroup];
	
	for (i=0;i<listNum;i++){
		QuicksortF(lists[i].values, 0, lists[i].itemNum-1);
	}
	
	for (i=0;i<groupNum;i++){
		//Compute percentile for each item
		
		isallone=true;
    int validsgs=0;
		for (j=0;j<groups[i].itemNum;j++){
      if(groups[i].items[j].isChosen==0) continue;
			listIndex = groups[i].items[j].listIndex;
			
			index1 = bTreeSearchingF(groups[i].items[j].value-0.000000001, lists[listIndex].values, 0, lists[listIndex].itemNum-1);
			index2 = bTreeSearchingF(groups[i].items[j].value+0.000000001, lists[listIndex].values, 0, lists[listIndex].itemNum-1);
			
			groups[i].items[j].percentile = ((double)index1+index2+1)/(lists[listIndex].itemNum*2);
			tmpF[validsgs] = groups[i].items[j].percentile;
			tmpProb[validsgs]=groups[i].items[j].prob;
			if(tmpProb[validsgs]!=1.0){
				isallone=false;
			}
      // save for control sequences
      if(UseControlSeq){
        string sgname(groups[i].items[j].name);
        if(ControlSeqMap.count(sgname)>0){
          int sgindex=ControlSeqMap[sgname];
          ControlSeqPercentile[sgindex]=tmpF[validsgs];
        }
      }//end if
      validsgs++;
		}// end j
    if(validsgs<=1){
      isallone=true;
    }
    //printf("Gene: %s\n",groups[i].name);
		if(isallone){
			ComputeLoValue(tmpF, validsgs, groups[i].loValue, maxPercentile, groups[i].goodsgrnas);
		}
		else{
			ComputeLoValue_Prob(tmpF, validsgs, groups[i].loValue, maxPercentile, tmpProb,groups[i].goodsgrnas);
		}
    groups[i].isbad=0;
	}//end i loop

	delete[] tmpF;
	delete[] tmpProb;
  //check if all control sequences are properly assigned a value
  if(UseControlSeq){
    for(map<string,int>::iterator mit = ControlSeqMap.begin(); mit != ControlSeqMap.end(); mit++){
      if(ControlSeqPercentile[mit->second]<0){
        cerr<<"Warning: sgRNA "<<mit->first<<" not found in the ranked list. \n";
        //ControlSeqPercentile[mit->second]=0.5;
      }
    }
  }//end UseControlSeq
	
	return 1;
}
Exemple #27
0
	EventData* getEventData(const string& mId, HexagonGame* mHgPtr)
	{
		EventData* result = new EventData(eventDataMap.find(mId)->second);
		result->setHexagonGamePtr(mHgPtr);
		return result;
	}
Exemple #28
0
//Compute False Discovery Rate based on uniform distribution
int ComputeFDR(GROUP_STRUCT *groups, int groupNum, double maxPercentile, int numOfRandPass)
{
	int i,j,k;
	double *tmpPercentile;
	int maxItemNum = 0;
	int scanPass = numOfRandPass/groupNum+1;
	double *randLoValue;
	int randLoValueNum;

	//WL
	double *tmpProb;
	double isallone;
	
	for (i=0;i<groupNum;i++){
		if (groups[i].itemNum>maxItemNum){
			maxItemNum = groups[i].itemNum;
		}
	}
	
	assert(maxItemNum>0);
	
	//tmpPercentile = (double *)malloc(maxItemNum*sizeof(double));
	//tmpProb= (double *)malloc(maxItemNum*sizeof(double));
  tmpPercentile=new double[maxItemNum];
  tmpProb=new double[maxItemNum];	

	randLoValueNum = groupNum*scanPass;
	
	assert(randLoValueNum>0);
	
	//randLoValue = (double *)malloc(randLoValueNum*sizeof(double));
  randLoValue=new double[randLoValueNum];
	
	randLoValueNum = 0;
	
	PlantSeeds(123456);
  
  PRINT_DEBUG=0;
  
  // set up control sequences
  int n_control=0;
  double* control_prob_array=NULL;
  double ufvalue=0.5;
  int rand_ctl_index=0;
  int tmp_int;
	if(UseControlSeq){
    for(map<string,int>::iterator mit = ControlSeqMap.begin(); mit != ControlSeqMap.end(); mit++){
      if(ControlSeqPercentile[mit->second]>=0){
        n_control++;
      }
    }
    control_prob_array=new double[n_control];
    n_control=0;
    for(map<string,int>::iterator mit = ControlSeqMap.begin(); mit != ControlSeqMap.end(); mit++){
      if(ControlSeqPercentile[mit->second]>=0){
        control_prob_array[n_control]=ControlSeqPercentile[mit->second];
        n_control++;
      }
    }
    cout<<"Total # control sgRNAs: "<<n_control<<endl;
  }
  
	for (i=0;i<scanPass;i++){
    for (j=0;j<groupNum;j++){
			isallone=true;
      int validsgs=0;
			for (k=0;k<groups[j].itemNum;k++)
			{
        if(groups[j].items[k].isChosen==0) continue;
        ufvalue=Uniform(0.0, 1.0);
        if(UseControlSeq){
          rand_ctl_index=(int)(n_control*ufvalue);
          if(rand_ctl_index>=n_control) rand_ctl_index=n_control-1;
          tmpPercentile[validsgs]=control_prob_array[rand_ctl_index];
        }else{
				  tmpPercentile[validsgs] = ufvalue;
        }
				tmpProb[validsgs]=groups[j].items[k].prob;
				if(tmpProb[validsgs]!=1.0)
				{
					isallone=false;
				}
        validsgs++;
			} //end for k
      if(validsgs<=1)
        isallone=true;
			
			if(isallone){
				ComputeLoValue(tmpPercentile, validsgs,randLoValue[randLoValueNum], maxPercentile, tmp_int);
			}
			else
			{
				ComputeLoValue_Prob(tmpPercentile, validsgs,randLoValue[randLoValueNum], maxPercentile,tmpProb,tmp_int);
			}
			
			randLoValueNum++;
		}// end for j
	}//end for i
	
	QuicksortF(randLoValue, 0, randLoValueNum-1);
						  
	QuickSortGroupByLoValue(groups, 0, groupNum-1);
	
  //FDR calcuation
  int goodGroupNum=0;
  for(i=0;i<groupNum;i++){
     //if(groups[i].isbad==0) 
    goodGroupNum+=1;
  }
  //save the index
  if(goodGroupNum==0) goodGroupNum=1;
  cout<<"Number of groups under permutation and FDR adjustment: "<<goodGroupNum<<endl;
  int* indexval=new int[goodGroupNum];
  int goodindex=0;
	for (i=0;i<groupNum;i++){
		//groups[i].fdr = (double)(bTreeSearchingF(groups[i].loValue-0.000000001, randLoValue, 0, randLoValueNum-1)
		//						 +bTreeSearchingF(groups[i].loValue+0.000000001, randLoValue, 0, randLoValueNum-1)+1)
		//						/2/randLoValueNum/((double)i+0.5)*groupNum;
    if(groups[i].isbad==0){
      groups[i].pvalue=(double)(bTreeSearchingF(groups[i].loValue-0.000000001, randLoValue, 0, randLoValueNum-1)
								 +bTreeSearchingF(groups[i].loValue+0.000000001, randLoValue, 0, randLoValueNum-1)+1)
								/2/randLoValueNum;
		  groups[i].fdr = groups[i].pvalue/((double)i+1.0)*goodGroupNum;
      indexval[goodindex]=i;
      goodindex++;
    }else{
      groups[i].pvalue=1.0;
      groups[i].fdr=1.0;
    }
	}
	
	if (groups[groupNum-1].fdr>1.0)
	{
		groups[groupNum-1].fdr = 1.0;
	}
	
	for (i=goodGroupNum-2;i>=0;i--){
    int g_i=indexval[i];
    int g_ip1=indexval[i+1];
		if (groups[g_i].fdr>groups[g_ip1].fdr){
			groups[g_i].fdr = groups[g_ip1].fdr;
		}
	}
	
	//free(tmpPercentile);
	//free(tmpProb);
	//free(randLoValue);
  delete []tmpPercentile;
  delete []tmpProb;
  delete []randLoValue;
  
  if(UseControlSeq){
    delete[] control_prob_array;
  }
  delete []indexval;
	
	return 1;
}
Exemple #29
0
	void reset()
	{
		isShowDown=false;
		result.clear();
	}
 //To print the entries in spare
 void printspare()
 {
     cout<<"Entries in spare\nrow col value\n";
     for(mapiterator=spare.begin();mapiterator!=spare.end();mapiterator++)
         cout<<mapiterator->first.first<<" "<<mapiterator->first.second<<" "<<mapiterator->second<<endl;
 }