示例#1
0
void HashTable::loadActionValueTable(const string& fileName)
{
    //        fprintf(stream, "Q-Hash Table\n");
        
    
    double maxDiscreteBin = 0.;
    ifstream inFile(fileName.c_str());
    if (!inFile.is_open())
    {
        cerr << "ERROR: Cannot open Q Table file <" << fileName << ">!" << endl;
        exit(1);
    }
    
    _valueTable.clear();
    
    nor_utils::StreamTokenizer lineToken(inFile, "\n\r");
    while (lineToken.has_token())
    {
        string line = lineToken.next_token();
        
        if (line.size() == 0)
            continue;
        
        stringstream ssLine(line);
        nor_utils::StreamTokenizer itemToken(ssLine, " \n\r\t");

        ValueKey key;
        string item = itemToken.next_token();
//        assert(tmp.compare("(") == 0);
        
        int pointer = 0;
        while (itemToken.has_token()) {
            item = itemToken.next_token();

            if (item.size() == 0)
                continue;
            if (item.compare(")") == 0) 
                break;
            
            stringstream ssItem(item);
            double k;
            ssItem >> k;
            key.push_back(k);
            
            // if it points to the bin index and if it's not the max yet
            if (pointer == (_numWinnerClasses + 1) && k > maxDiscreteBin) {
                maxDiscreteBin = k;
            }

            ++pointer;
        }
        
        while (itemToken.has_token())
        {
            item = itemToken.next_token();

            if (item.size() == 0)
                continue;

            stringstream ssItem(item);
            AlphaReal q;
            ssItem >> q;
            _valueTable[key].push_back(q);
        }
        
        assert(_valueTable[key].size() == _numberOfActions);
    }
    
    ++maxDiscreteBin; //starts at 0
    
    if ((1./maxDiscreteBin) != _stepResolution) {
        cout << "[!] Warning: the score resolution used (" << 1/_stepResolution << ") seems to be different in the Q table file (" << (int)maxDiscreteBin << ")." << endl;
    }
}
示例#2
0
bool BedValidator::validate() 
{
	dumpmessage(DEBUG, __FILE__, " In BedValidator::validate()");

	bool isValid = true;	

	int colCount = -1;
	int trackCount = 1;

	string line, token;
	string traceChromName = "";
	string trackName = "track1";
	string dumpMsg;
			
	const string TRACK = "track";
	const char lineDelim = '\n';

	if(mBamChromNames.size() != mBamChromSizes.size()) 
	{
		dumpmessage(ERROR, __FILE__, " Validation failed. Size of input chrom names is not the same as the chrom sizes.");
		return false;
	}
	
	ifstream bedStream;
	// Open BED file for validation
	bedStream.open(mBedFn.c_str(), ifstream::in);
	if( !bedStream.is_open() )
	{
		dumpMsg = " BED file: " + mBedFn + ". BED file can not be opened";
		dumpmessage(ERROR, __FILE__, dumpMsg);
		return false;
	}
	
	dumpMsg = " BED file: " + mBedFn;
	dumpmessage(INFO, __FILE__, dumpMsg);
	
	while( getline(bedStream, line, lineDelim) )
	{		
		size_t pos = line.find(TRACK);
		if (pos < line.length())
		{	//Track is present 

			if(!getTrackName(trackName, line, trackCount))
			{
				dumpmessage(ERROR, __FILE__, " ERROR while reading track name.");
			}

			// Reset column count as new track starting
			colCount = -1;
			//Increment track count for every track
			++trackCount; 
		}
		else
		{	// Process BED file data
			bool dataLineFound = false;
				
			int colIdx = 1;
			int64 chromStart = -1, chromEnd = -1, score = -1;
			
			string chromName, strand;

			const char colDelim = '\t';
			
			// push the line into stringstream line for another round of getline
			stringstream ssLine(line); 
			for(; getline(ssLine, token, colDelim); ++colIdx)
			{
				stringstream ssToken(token);
				dataLineFound = true;
				
				switch(colIdx)
				{	// Validate Column data from BED file
					case CHROM_IDX:
						chromName = token;
						break;
							
					case CHROMSTART_IDX:
						ssToken >> chromStart;
						
						if(chromStart < 0 || ssToken.fail())
						{
							dumpMsg = " Track: " + trackName + " Chrom: " + chromName + " chromStart:"+ token + " Error: chromStart can not be less than 0";
							dumpmessage(ERROR, __FILE__, dumpMsg);
							isValid = false;
						}
						break;	
			
					case CHROMEND_IDX:
						ssToken >> chromEnd;

						if(chromEnd < 1 || ssToken.fail())
						{
							dumpMsg = " Track: " + trackName + " Chrom: " + chromName + " chromEnd:" + token + " Error: chromEnd can not be less than 1";
							dumpmessage(ERROR, __FILE__, dumpMsg);
							isValid = false;
						}

						if( chromStart > chromEnd)
						{
							stringstream ssValue;
							
							ssValue << " ChromStart: " << chromStart << ", ChromEnd: " << chromEnd;
							dumpMsg = " Track: " + trackName + " Chrom: " + chromName + ssValue.str() + " Error: chromStart can not be greater than chromEnd";
							dumpmessage(ERROR, __FILE__, dumpMsg);
							isValid = false;
						}
						
						break;
							
					case SCORE_IDX:
						ssToken >> score;

						if(score < SCORE_MIN || score > SCORE_MAX || ssToken.fail())
						{
							stringstream ssValue;
						
							ssValue << " ChromStart: " << chromStart;
							dumpMsg = " Track: " + trackName + " Chrom: " + chromName + ssValue.str() + " score:" + token + " Error: Score is not in 0 to 1000 limit";
							dumpmessage(ERROR, __FILE__, dumpMsg);
							isValid = false;
						}
						break;
							
					case STRAND_IDX:
						strand = token;
						if(token[0] != STRAND_PLUS && token[0] != STRAND_MINUS)
						{
							stringstream ssValue;
						
							ssValue << " ChromStart: " << chromStart;
							dumpMsg = " Track: " + trackName + " Chrom: " + chromName + ssValue.str() + " strand:" + token + " Error: Strand value is not + or -";
							dumpmessage(ERROR, __FILE__, dumpMsg);			
							isValid = false;
						}
						break;
							
					case NAME_IDX:
					case THICKSTART_IDX:
					case THICKEND_IDX:
					case ITEMRGB_IDX:
					case BLOCKCOUNT_IDX:
					case BLOCKSIZES_IDX:
					case BLOCKSTARTS_IDX:
					default:
						break;
				} // switch()
			} // for()
				
			if( colCount > 0 )
			{	// Verify the column count with the previous column count
				if( dataLineFound )
				{
					--colIdx;
						
					if(colCount < MIN_COLUMNS) 
					{ // Minimum three columns must be present	
						dumpMsg = " Track: " + trackName + " Chrom: " + chromName + " ERROR - Do not match the minimum three columns criteria";
						dumpmessage(ERROR, __FILE__, dumpMsg);
						isValid = false;
					}
					
					if( colCount != colIdx )
					{ // If the column count do not match		
						stringstream ssValue;
						
						ssValue << " ChromStart: " << chromStart;
						dumpMsg = " Track: " + trackName + " Chrom: " + chromName + ssValue.str() + " ERROR - Columns do not match from same track";						
						dumpmessage(ERROR, __FILE__, dumpMsg);
						isValid = false;
					}
				}
			}
			else
			{	// Initialize Column count for current Track
				stringstream ssColcount;

				colCount = --colIdx;
				ssColcount << colCount;
				dumpMsg = " Track: " + trackName + " - Column count: " + ssColcount.str();
				dumpmessage(INFO, __FILE__, dumpMsg);
			}
				
			// Validating Bam Header data if present otherwise return the validation of BED file
			if( dataLineFound && mBamChromNames.size() > 0)
			{
				bool retVal;

				retVal = checkWithBAMHeader(trackName, chromName, chromStart, chromEnd);

				if(!retVal)
					isValid = retVal;
			}
				
		} // else{} process BED data
	} // while()
	
	//Close the BED file
	bedStream.close();

	dumpmessage(DEBUG, __FILE__, " Out BedValidator::validate()");	
	return isValid;
}
示例#3
0
int KGTestMapDisuseResource::FindResInMDL(const char cszResourceName[], set<string>& setResList)
{
	//参照KG3DModelST::LoadMDLContent
	int nResult = false;
	char szFilePath[MAX_PATH] = {0};
	IFile* pFile = NULL;
	unsigned long uSize = 0;
	unsigned long uFileSize = 0;
	char* pBuffer = NULL;
	std::stringstream ss;
	std::string strBuffer;
	std::string strFilePath;
	MDLFileContent Content;

	KG_ASSERT_EXIT(cszResourceName);
	KGLOG_PROCESS_ERROR(cszResourceName[0] != '\0');

	Content.dwNumModels = 0;
	pFile = g_OpenFile(cszResourceName);
	KG_PROCESS_ERROR(pFile);

	uFileSize = pFile->Size();

	pBuffer = (char*)malloc(uFileSize + 1);
	KG_PROCESS_ERROR(pBuffer);

	uSize = pFile->Read(pBuffer, uFileSize);
	KG_PROCESS_ERROR(uSize == uFileSize);

	pBuffer[uSize] = '\0'; // TODO : text 文件没有使用'\0'作结束,不能作为字符串处理,特别麻烦,建议使用binary

	ss << pBuffer;

	std::getline(ss, strBuffer);
	strBuffer.erase(strBuffer.find_last_not_of("\n\r") + 1);
	KG_PROCESS_ERROR(!strBuffer.empty());

	g_ExtractFilePath(szFilePath, cszResourceName);

	strFilePath = szFilePath;
	strFilePath += "\\";

	if (strBuffer[0] == '\\')
	{
		Content.strBipFile = strBuffer;
	}
	else
	{
		Content.strBipFile = std::string(strFilePath + strBuffer);
	}
	FindResource(Content.strBipFile.c_str(), setResList);

	while (std::getline(ss, strBuffer))
	{
		strBuffer.erase(strBuffer.find_last_not_of("\n\r") + 1);
		if (strBuffer.empty())
			break;

		std::stringstream ssLine(strBuffer);
		std::string strMesh, strMtl;
		ssLine >> strMesh >> strMtl;

		if (strMtl.size())
		{
			Content.strMaterialFile[Content.dwNumModels] = strMtl;
		}
		FindResource(Content.strMaterialFile[Content.dwNumModels].c_str(), setResList);

		if (strMesh.size())
		{
			if (strMesh[0] == '\\')
			{
				Content.strMeshFile[Content.dwNumModels] = strMesh;
			}
			else
			{
				Content.strMeshFile[Content.dwNumModels] = strFilePath + strMesh;
			}
			FindResource(Content.strMeshFile[Content.dwNumModels].c_str(), setResList);
			Content.dwNumModels++;
		}
	}
	nResult = true;
Exit0:
	SAFE_FREE(pBuffer);
	KG_COM_RELEASE(pFile);

	if (!nResult && cszResourceName)
	{
		KGLogPrintf(KGLOG_ERR, "Find Res In MDL %s failed.\n", cszResourceName);
	}
	return nResult;
}
示例#4
0
    SceneManager::SceneManager(GLint width, GLint height)
#endif
    {
        Log << Function << endl;

        // The projection matrix is represented by the perspective matrix given by glm, assign it to each one of the objects
        GLfloat aspect = static_cast<GLfloat>(width) / static_cast<GLfloat>(height);
        projectionMatrix = glm::perspective(
            45.0f,      // Field of view, is the amount of zoom. A wide angle is 90 and a narrow angle is 30
            aspect,     // Depends on the size of the window
            0.1f,       // Near clipping plane
            500.0f      // Far clipping plane
        );

        // Read the resources.txt file to obtain the valid configuration for the engine
        string resourcesFileName = "resources.txt";
#if defined(__ANDROID__)
        AAssetManager* mgr = AAssetManager_fromJava(*env, assetManager);
        AAsset* pFile = AAssetManager_open(mgr, resourcesFileName.c_str(), AASSET_MODE_UNKNOWN);
        if (!pFile)
#else
        ifstream resourcesFile(resourcesFileName, ios::in);
        if (!resourcesFile.is_open())
#endif
        {
            Log << Error << "Unable to read the resources file: " << resourcesFileName << endl;
            terminate();
        }

#if defined(__ANDROID__)
        // Get the file size
        size_t fileSize = AAsset_getLength(pFile);
        // Read data from the file
        char* pData = (char*)calloc(fileSize + 1, sizeof(char));
        AAsset_read(pFile, pData, fileSize);
        // fix the string to be zero-terminated
        pData[fileSize] = 0;
        // Copy the data to a stringstream
        stringstream resourcesFile(pData);
        AAsset_close(pFile);
        free(pData);
#endif

        Log << Debug << "Parsing the resources.txt file." << endl;
        string line, name, vertex, fragment, object, texture, projection, modelview;
        vector<string> cubeTextures{ NumCubeFaces };
        GLuint size, bufferType;
        vec3 pos, scl, rot;
        char token;
        bool finished = true;

        while (getline(resourcesFile, line))
        {
            stringstream ssLine(line);
            // Ignore empty lines on the configuration file
            if(line.size() == 0)
                continue;

            ssLine >> token;
            switch (token)
            {
            // If the line is a comment get the next token
            case '#':
                continue;
            // Start of object definition
            case '.':
                // Create a new scene object
                Log << Debug << "Starting an object definition." << endl;
                sceneobjects.push_back(make_unique<SceneObject>());
                finished = false;
                break;
            // End of an object definition
            case '-':
                Log << Debug << "End an object definition." << endl;
                finished = true;
                break;
            // Attributes used on the shaders
            case 'A':
                ssLine >> name >> size >> bufferType;
                Log << Debug << "Adding the attribute: " << name << endl;
                attributes.push_back(make_unique<Variable>(name, size, (BufferType)bufferType));
                break;
            // Uniforms used on the shaders
            case 'U':
                ssLine >> name;
                Log << Debug << "Adding the uniform: " << name << endl;
                uniforms.push_back(make_unique<Variable>(name));
                break;
            // Shaders creation
            case 'S':
                ssLine >> vertex >> fragment;
                Log << Debug << "Creating the shaders." << endl;
#if defined (__ANDROID__)
                sceneobjects.back()->SetShader(make_shared<Shader>(&mgr, vertex, fragment, attributes, uniforms));
#else
                sceneobjects.back()->SetShader(make_shared<Shader>(vertex, fragment, attributes, uniforms));
#endif
                break;
            // Object definitions
            case 'O':
                ssLine >> object;
                Log << Debug << "Loading a model." << endl;
#if defined (__ANDROID__)
                sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, object, sceneobjects.back()->GetShader()));
#else
                sceneobjects.back()->SetMesh(make_unique<Mesh>(object, sceneobjects.back()->GetShader()));
#endif
                break;
            // Textures
            case 'T':
                ssLine >> texture;
                Log << Debug << "Loading a texture." << endl;
#if defined(__ANDROID__)
                sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, texture, sceneobjects.back()->GetShader()));
#else
                sceneobjects.back()->SetTexture(make_unique<Texture>(texture, sceneobjects.back()->GetShader()));
#endif
                break;
            // Initial coordinates
            case 'C':
                Log << Debug << "Adding coordinates to the object." << endl;
                ssLine >> pos.x >> pos.y >> pos.z >> scl.x >> scl.y >> scl.z >> rot.x >> rot.y >> rot.z >> angle;
                sceneobjects.back()->SetCoordinates(pos, scl, rot, angle);
                break;
            // Projection matrix
            case 'P':
                ssLine >> projection;
                break;
            // Modelview matrix
            case 'M':
                ssLine >> modelview;
                break;
            // Skybox
            case 'B':
                Log << Debug << "Adding a skybox." << endl;
                ssLine >> cubeTextures[0] >> cubeTextures[1] >> cubeTextures[2] >> cubeTextures[3] >> cubeTextures[4] >> cubeTextures[5];
                sceneobjects.back()->SetSkymap();
#if defined(__ANDROID__)
                sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, string(""), sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, cubeTextures, sceneobjects.back()->GetShader()));
#else
                sceneobjects.back()->SetMesh(make_unique<Mesh>(string(""), sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetTexture(make_unique<Texture>(cubeTextures, sceneobjects.back()->GetShader()));
#endif
                break;
            // Terrain Heightmap
            case 'H':
                Log << Debug << "Loading the terrain." << endl;
                ssLine >> texture >> object;
#if defined(__ANDROID__)
                sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, texture, sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, object, sceneobjects.back()->GetShader(), &sceneobjects.back()->GetTexture()));
#else
                sceneobjects.back()->SetTexture(make_unique<Texture>(texture, sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetMesh(make_unique<Mesh>(object, sceneobjects.back()->GetShader(), &sceneobjects.back()->GetTexture()));
#endif
                break;
            default:
                continue;
            }

            // Check if the definition of an object is complete or if more lines are needed
            if (finished)
            {
                // Get the projection and modelview uniforms
                if (!projection.empty())
                {
                    sceneobjects.back()->SetProjectionUni(glGetUniformLocation(sceneobjects.back()->GetShader()->getProgramObject(), "Projection"));
                    projection.clear();
                }
                if (!modelview.empty())
                {
                    sceneobjects.back()->SetModelviewUni(glGetUniformLocation(sceneobjects.back()->GetShader()->getProgramObject(), "Modelview"));
                    modelview.clear();
                }

                // Clear the attributes and uniforms in order to load the next object
                attributes.clear();
                uniforms.clear();
            }
        }
#if !defined(__ANDROID__)
        // Close de the resources file
        resourcesFile.close();
#endif

        // Set the initial position of the camera
        camera = vec3(2.5f, -1.0f, -5.0f);

        // Initial value of the rotation angle
        angle = 0.0f;
    }