Example #1
0
void Functionality::callSort()
{
	if(highPriority.size()>=2)
		sortVector(highPriority);
	if(normalPriority.size()>=2)
		sortVector(normalPriority);
}
TEST(PrecomputationTest, TestIndexSorting) 
{
  IndType assSectors[6] = {0,9,13,13,8,26};
  IndType expectedSectors[6] = {0,8,9,13,13,26};

  gpuNUFFT::Array<IndType> assignedSectors;
  assignedSectors.data = assSectors;
  assignedSectors.dim.length = 6;

  std::vector<gpuNUFFT::IndPair> secVector = sortVector(assignedSectors);

  // print out content:
  if (DEBUG)
  {
    std::cout << "vector contains:";
    for (std::vector<gpuNUFFT::IndPair>::iterator it=secVector.begin(); it!=secVector.end(); ++it)
      std::cout << " " << it->second << " (" << it->first << ") ";
    std::cout << '\n';
  }
  gpuNUFFT::IndPair* sortedArray = &secVector[0];

  //print indices for reselect
  for (IndType i=0; i<6;i++)
  {
    if (DEBUG)
	    std::cout << sortedArray[i].first ;
	  EXPECT_EQ(sortedArray[i].second, expectedSectors[i]);
  }
  if (DEBUG)
    std::cout << std::endl;
}
Example #3
0
//mode value from 1d vector
int  Utility::mode(vector<int> &numberVector, int eraseValue)
{
	if (numberVector.size() <= 0)return 0;

	//remove element from vector
	if (eraseValue >= 0)
	{
		numberVector = removeElement(numberVector, eraseValue);
	}

	//sort vector
	numberVector = sortVector(numberVector);

	int maxCount = 0, maxPosition = 0;
	int count = 1;

	for (unsigned int ii = 0; ii<numberVector.size() - 1; ii++)
	{
		if (numberVector[ii] == numberVector[ii + 1])
		{
			count++;
		}
		else
			count = 1;

		if (count>maxCount)
		{
			maxCount = count;
			maxPosition = ii;
		}
	}


	return numberVector[maxPosition];
}
Example #4
0
// Prints the ratio of unique programs to total programs
void mVUprintUniqueRatio(microVU& mVU) {
	std::vector<u64> v;
	for(u32 pc = 0; pc < mProgSize/2; pc++) {
		microProgramList* list = mVU.prog.prog[pc];
		if (!list) continue;
		std::deque<microProgram*>::iterator it(list->begin());
		for ( ; it != list->end(); ++it) {
			v.push_back(mVUrangesHash(mVU, *it[0]));
		}
	}
	u32 total = v.size();
	sortVector(v);
	makeUnique(v);
	if (!total) return;
	DevCon.WriteLn("%d / %d [%3.1f%%]", v.size(), total, 100.-(double)v.size()/(double)total*100.);
}
Example #5
0
void Shape::drawTextured(ShadowBuffer& sb, Point const textureAnchor, int textureWidth, int textureHeight, Color ** textureCache) {
    Util util;

    Point p1, p2;
    Point * tipPoints = getTipPoints();

    for(int i = tipPoints[0].y; i <= tipPoints[1].y; i++) {
        vector<Point> ListOfIntersectPoints;
        for(int j = 0; j < points.size(); j++) {
            if (j != (points.size() - 1)) {
                p1 = points[j];
                p2 = points[j+1];
            } else {
                p1 = points[j];
                p2 = points[0];
            }
            int intersectX;
            if (findIntersection(p1,p2,i,intersectX)) {
                if(p1.y > p2.y) {
                    std::swap(p1,p2);
                }

                if (i != p2.y) {
                    Point intersect(intersectX, i, 0);
                    ListOfIntersectPoints.push_back(intersect);
                }
            }
        }
        vector<Point> sortedResult = sortVector(ListOfIntersectPoints);
        int intersectPointsSize = sortedResult.size();
        Color d(225, 0, 0);
        for(int j = 0; j < intersectPointsSize-1; j+=2) {
            Line line(sortedResult[j], sortedResult[j + 1]);
            line.drawTextured(sb, textureAnchor, textureWidth, textureHeight, textureCache);
        }
    }
    delete [] tipPoints;
}
Example #6
0
int main(int argc, char **argv)
{
    std::fstream fp;
    std::vector<int> numbers;
    int number;

    fp.open(argv[1], std::ios::in );
    std::ofstream myfile;
     myfile.open (argv[2]);

    if(fp.is_open()){
      while(fp >> number){
         numbers.push_back(number);
         fp.get();
      }
    }

    fp.close();

    // before sort
    std::cout << "Numbers:\n";
    displayVector(numbers);

    // Sort the values
    sortVector(numbers);

    //after sort
    displayVector(numbers);

    if (std::binary_search (numbers.begin(), numbers.end(), 5))
        std::cout << "The number 5 was found!\n"; else std::cout << "not found.\n";

    //myfile << displayVector(numbers);
    
    myfile.close();

    return 0;
}
TEST(PrecomputationTest, ComputeDataIndices) {
	IndType imageWidth = 16; 
	DType osr = 1.5;
	IndType sectorWidth = 8;

	const IndType coordCnt = 6;
	
	// Coords as StructureOfArrays
	// i.e. first x-vals, then y-vals and z-vals
	DType coords[coordCnt*3] = {-0.5,-0.3,-0.1, 0.1, 0.3, 0.5,//x
	                            -0.5,-0.5,   0,   0, 0.5, 0.45,//y
	                            -0.33,-0.16666,   0,   0, -0.23, 0.45};//z

	gpuNUFFT::Array<DType> kSpaceData;
    kSpaceData.data = coords;
    kSpaceData.dim.length = coordCnt;

	gpuNUFFT::Dimensions gridDim;
	gridDim.width = (IndType)(imageWidth * osr);
	gridDim.height = (IndType)(imageWidth * osr);
	gridDim.depth = (IndType)(imageWidth * osr);

	gpuNUFFT::Dimensions sectorDims= computeSectorCountPerDimension(gridDim,sectorWidth);

	IndType expectedSec[6] = {0,9,13,13,8,26};

	gpuNUFFT::Array<IndType> assignedSectors;
    assignedSectors.data = (IndType*)malloc(coordCnt * sizeof(IndType));
    assignedSectors.dim.length = coordCnt;

	for (int cCnt = 0; cCnt < coordCnt; cCnt++)
	{
		DType3 coord;
		coord.x = kSpaceData.data[cCnt];
		coord.y = kSpaceData.data[cCnt + kSpaceData.count()];
		coord.z = kSpaceData.data[cCnt + 2*kSpaceData.count()];

		IndType3 mappedSectors = computeSectorMapping(coord,sectorDims);

		IndType sector = computeInd32Lin(mappedSectors,sectorDims);
		assignedSectors.data[cCnt] = sector;
		EXPECT_EQ(expectedSec[cCnt],sector);
	}

	IndType expectedSecSorted[6] = {0,8,9,13,13,26};
	IndType expectedSecIndexSorted[6] = {0,4,1,2,3,5};

    std::vector<gpuNUFFT::IndPair> secVector = sortVector(assignedSectors);

	DType coords_sorted[coordCnt*3];
	
	for (int i=0; i<coordCnt;i++)
	{
		//compare index
		EXPECT_EQ(expectedSecIndexSorted[i],secVector[i].first);
		EXPECT_EQ(expectedSecSorted[i],secVector[i].second);
		coords_sorted[i] = kSpaceData.data[secVector[i].first];
		coords_sorted[i + 1*coordCnt] = kSpaceData.data[secVector[i].first + 1*coordCnt];
		coords_sorted[i + 2*coordCnt] = kSpaceData.data[secVector[i].first + 2*coordCnt];
	}

	IndType cnt = 0;
	std::vector<IndType> dataIndices;

	IndType sectorDataCount[29] = {0,1,1,1,1,1,1,1,1,2,3,3,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6};
	
	dataIndices.push_back(0);
	for (int i=0; i<=sectorDims.count(); i++)
	{	
		while (cnt < coordCnt && i == secVector[cnt].second)
			cnt++;
		
		dataIndices.push_back(cnt);
		EXPECT_EQ(sectorDataCount[i+1],cnt);
	}

  if (DEBUG)
  {
	  for (int i=0; i<dataIndices.size(); i++)
	  {
		  std::cout << dataIndices.at(i) << " " ;
	  }
	  std::cout << std::endl;
  }
	free(assignedSectors.data);
}
bool MoveToTheVictim::moveToTheVictim(TPlayer bot, Player * bot_n,
                                      TVector * victim_position, sf::Vector2i *direction_bot)
{
    /*
     *if bot is already dead then return;
     */

    //std::cout << "MoveToTheVictim -> ";

    if(!bot_n->isAlive())
        return false;

    /*
     *We are creating vectors with x- and y-
     *coordinates of walls, bot and players
     *from opposite command;
     */

    if(num-- != 0)
    {
        //bot_n->Move(lastHorDirection);
        //bot_n->Move(lastVertDirection);
        //std::cout << "num != 0 -> ";
//        this->moveToTheNextPixel(lastHorDirection);
//        this->moveToTheNextPixel(lastVertDirection);
  //      std::cout << "return false;\n";
        *direction_bot = bot_n->lastDirection;
        return false;
    }

    this->direction_bot = direction_bot;

    lastHorDirection = DIRECTION_NODIRECTION;
    lastVertDirection = DIRECTION_NODIRECTION;
    num = 0;

    std::vector<int> x_coord;
    std::vector<int> y_coord;

    x_coord.push_back(X_MIN);
    y_coord.push_back(Y_MIN);
    for(int i = 0; i < (int)this->walls.size(); i++)
    {
        x_coord.push_back(this->walls[i].A.x);
        x_coord.push_back(this->walls[i].B.x);
        y_coord.push_back(this->walls[i].A.y);
        y_coord.push_back(this->walls[i].B.y);
    }
    x_coord.push_back(bot.coord.x); //
    y_coord.push_back(bot.coord.y); //
    for(int i = 0; i < (int)victims.size(); i++)
    {
        x_coord.push_back(victims[i].coord.x);
        y_coord.push_back(victims[i].coord.y);
    }
    x_coord.push_back(X_MAX);
    y_coord.push_back(Y_MAX);

    sortVector(x_coord);    //check!
    sortVector(y_coord);    //check!

    int rows = y_coord.size()-1, columns = x_coord.size()-1;
    int **cells = new int*[columns];
    for(int i = 0; i < columns; i++)
        cells[i] = new int[rows];
    TVector tmp_vector,bot_cell,neighCells[4];
    for(int i = 0; i < columns; i++)
        for(int j = 0; j < rows; j++)
        {

            bool cell_is_wall = true;

            for(int x = 0; x <= 1; x++)
                for(int y = 0; y <= 1; y++)
                {
                    tmp_vector.x = x_coord[i]+x;
                    tmp_vector.y = y_coord[j]+y;

                    if( !pixelIsInTheWall(tmp_vector) )
                        cell_is_wall = false;
                }

            //if( (x_coord[i] + 1 == x_coord[i+1])&&(y_coord[j] + 1 == y_coord[j+1]) )
            //    cell_is_wall = true;

            if(cell_is_wall)
                 cells[i][j] = -1;   //якщо стіна;
                     else
                 cells[i][j] = 0;    //якщо пусто;

          //  if( (tmp_vector.x == x_coord[i+1])||(tmp_vector.y == y_coord[j+1]) )
          //      cells[i][j] = -2;   //якщо внутрішність пуста;
            if( (x_coord[i] == bot.coord.x)&&(y_coord[j] == bot.coord.y) )
            {
                bot_cell.x = i;
                bot_cell.y = j;
            }
        }

    neighCells[0].x = bot_cell.x - 1;
    neighCells[0].y = bot_cell.y - 1;
   // if(/*(x_coord[neighCells[0].x+1] - x_coord[neighCells[0].x] == 1)&&*/(neighCells[0].x != 0))
     //   neighCells[0].x--;
   // if(/*(y_coord[neighCells[0].y+1] - y_coord[neighCells[0].y] == 1)&&*/(neighCells[0].y != 0))
     //   neighCells[0].y--;
    neighCells[1].x = bot_cell.x;
    neighCells[1].y = neighCells[0].y;
    /*if((x_coord[neighCells[1].x+1] - x_coord[neighCells[1].x] == 1)&&
            (neighCells[1].x != x_coord.size() - 2))
        neighCells[1].x++;*/
    neighCells[2].x = bot_cell.x/*neighCells[1].x*/;
    neighCells[2].y = bot_cell.y;
    /*if((y_coord[neighCells[2].y+1] - y_coord[neighCells[2].y] == 1)&&
            (neighCells[2].y != y_coord.size() - 2))
        neighCells[2].y++;*/
    neighCells[3].x = neighCells[0].x;
    neighCells[3].y = neighCells[2].y;

    for(int i = 0; i < 4; i++)
        if(cells[neighCells[i].x][neighCells[i].y] == 0)
            cells[neighCells[i].x][neighCells[i].y] = 1;

    int MAX_Column = x_coord.size() - 2, MAX_Row = y_coord.size() - 2;

    std::vector<TVector> next_cells,new_cells,tmp_cells;
    for(int i = 0; i < 4; i++)
        if(cells[neighCells[i].x][neighCells[i].y] == 1)
            next_cells.push_back(neighCells[i]);
    //std::cout << "Bot_x;y: " << bot.coord.x << ";" << bot.coord.y << "\n";
    //if(this->pixelIsInTheWall(bot.coord))
    //    std::cout << "Pixel is in the wall!!!!!!!!!!!!!!!!!!!!!!!!!!\n";

    /*
    next_cells.push_back(neighCells[0]);
    next_cells.push_back(neighCells[1]);
    next_cells.push_back(neighCells[2]);
    next_cells.push_back(neighCells[3]);
*/
    TVector tmp_cell;
    tmp_cell.x = -1;
    tmp_cell.y = -1;

    while((!victimIsInTheCellsVector(next_cells,x_coord,y_coord,&tmp_cell,victim_position))&&(!next_cells.empty()))
    {
        for(int i = 0; i < (int)next_cells.size(); i++)
        {
            tmp_cells = wave(cells,next_cells[i],MAX_Column,MAX_Row);
            for(int k = 0; k < (int)tmp_cells.size(); k++)
                new_cells.push_back(tmp_cells[k]);
            tmp_cells.clear();
        }
        next_cells.clear();
        next_cells = new_cells;
        new_cells.clear();

        //if(next_cells.empty())
        //    std::cout << "next_cells is empty!\n";
    }

    if((tmp_cell.x == -1)||(tmp_cell.y == -1))
    {
        //std::cout << "Victim wasn't founded! ERROR!\n";
        return false;
    }

    std::vector<TVector> way;
    for(int i = cells[tmp_cell.x][tmp_cell.y]; i > 0; i--)
    {
        way.push_back(tmp_cell);
        if( (tmp_cell.x != 0)&&
                (cells[tmp_cell.x-1][tmp_cell.y] == cells[tmp_cell.x][tmp_cell.y] - 1) )
            tmp_cell.x--;
                else
            if( (tmp_cell.y != 0)&&
                    (cells[tmp_cell.x][tmp_cell.y-1] == cells[tmp_cell.x][tmp_cell.y] - 1) )
                tmp_cell.y--;
                    else
                if( (tmp_cell.x != MAX_Column)&&
                        (cells[tmp_cell.x+1][tmp_cell.y] == cells[tmp_cell.x][tmp_cell.y] - 1) )
                    tmp_cell.x++;
                        else
                    if( (tmp_cell.y != MAX_Row)&&
                            (cells[tmp_cell.x][tmp_cell.y+1] == cells[tmp_cell.x][tmp_cell.y] - 1) )
                        tmp_cell.y++;
    }

    //std::cout << "way is: {";
    //for(int i = 0; i < (int)way.size(); i++)
    //    std::cout << "(" << way[i].x << "," << way[i].y << ")" << ",";
    //std::cout << "} -> ";


    if(way.size() <= 2)
    {
        //std::cout << "return true;\n";
        return true;
    }

    tmp_cell = way[way.size() - 2];
    way.clear();
    moveToTheCell(x_coord,y_coord,tmp_cell,bot/*,bot_n*/);
    //std::cout << "return false;\n";
    return false;
}
Example #9
0
void Shape::scanLineIntersect(ShadowBuffer& sb, Shape available) {
    Point p1, p2;   

    int nAvailable = available.points.size();

    int nDemand = points.size();
    int a = 0;
    available.draw(sb);
    Point * tipPoints = available.getTipPoints();
    //cout<< "ymin : "<<tipPoints[0].y<< " ymax : "<<tipPoints[1].y<<endl;
    for (int i = tipPoints[0].y; i <= tipPoints[1].y; i++) {  

    //Line line(Point(1,i,0),Point(500,i,0));
      //  line.color= Color(225,0,0);
        //line.draw(sb);
        //for (int k = 0; k < nAvailable; k++) {
            vector<Point> ListOfIntersectPoints;
            //Shape tempShape = pointToPrint[k];
            int edgesSize = available.points.size();
            //Color c = Color(tempShape.points[edgesSize-1].x,tempShape.points[edgesSize-1].y + 180 - (int)(i / 2),tempShape.points[edgesSize-1].z); 

            for (int j = 0; j < edgesSize ; j++) {
                //cout<< "GARIS ke-"<<j<<endl;
                if (j != (edgesSize - 1)) {
                    p1 = available.points[j];
                    p2 = available.points[j+1];
                } else {
                    p1 = available.points[j];
                    p2 = available.points[0];
                }

                int intersectX;

                if (findIntersection(p1,p2,i,intersectX)){
                    //cout<< intersectX<<endl;
                    if (p1.y > p2.y) {
                        std::swap(p1,p2);
                    }
                    Point intersect(intersectX, i,0);

                    if (intersect.y != p2.y) 
                    ListOfIntersectPoints.push_back(intersect);
                }
            }
            vector<Point> sort = sortVector(ListOfIntersectPoints);
            //cout<<"setelah sort"<<endl;
            // for(int i=0; i<sort.size(); i++){
            //     //cout<< "x, y =" << sort[i].x << ", " << sort[i].y<< endl;
            // }
            if(sort.size()>0) {
                vector<Line> resultAvailable = initAvailable(sort,sb);
                vector<Point> ListOfIntersectPoints2;
                int edgesSize2 = points.size();
                for (int j = 0; j < (edgesSize2 ); j++) {
                    if (j != (edgesSize2 - 1)) {
                        p1 = points[j];
                        p2 = points[j+1];
                    } else {
                        p1 = points[j];
                        p2 = points[0];
                    }

                    int intersectX;

                    if (findIntersection(p1,p2,i,intersectX)){
                        if (p1.y > p2.y) {
                            std::swap(p1,p2);
                        }
                        Point intersect(intersectX, i,0);
                        if (intersect.y == p2.y) continue;
                        ListOfIntersectPoints2.push_back(intersect);
                    }
                }
                vector<Point> resultDemand = sortVector(ListOfIntersectPoints2);
                drawAvailable(resultAvailable, resultDemand,sb, this->color);
            }
        //} 
    }

    delete [] tipPoints;
}
Example #10
0
void Shape::scanLineFill(ShadowBuffer& sb, vector<Point> v) {
    Util util;

    Point p1, p2;   
    int edgesSize = v.size();
    Point * tipPoints = getTipPoints();
    // vector<map<int,int> > brensenham;
    // for(int i=1; i < v.size(); i++){
    //     if(v[i-1].y!=v[i].y){
    //         Line l(v[i-1], v[i]);
    //         brensenham.push_back(l.getLinePoints());
    //     }
        
    // }
    // Line l(v[v.size()-1], v[0]);
    // brensenham.push_back(l.getLinePoints());

    for(int i = tipPoints[0].y; i <= tipPoints[1].y; i++) {
        vector<Point> ListOfIntersectPoints;
        for(int j = 0; j < edgesSize; j++) {
            if (j != (edgesSize - 1)) {
                p1 = v[j];
                p2 = v[j+1];
            } else {
                p1 = v[j];
                p2 = v[0];
            }
            int intersectX;
            // if((floatToInt(p1.y)==floatToInt(p2.y))&&(floatToInt(p1.x)==floatToInt(p2.x))&&(floatToInt(p1.y)==i)){
            //     Point intersect(floatToInt(p1.x), i, 0);
            //     ListOfIntersectPoints.push_back(intersect);
            // }
            if (findIntersection(p1,p2,i,intersectX)) {
                if(p1.y > p2.y) {
                    std::swap(p1,p2);
                }

                if (i != p2.y) {
                    Point intersect(intersectX, i, 0);
                    ListOfIntersectPoints.push_back(intersect);
                }
            }
        }
        // for(int j=0; j < brensenham.size(); j++){
        //     try{
        //         if(brensenham[j][i]!=0)
        //         ListOfIntersectPoints.push_back(Point(brensenham[j][i], i, 0));
                
        //     }catch(const std::out_of_range& oor) {

        //     }
        // }
        vector<Point> result = sortVector(ListOfIntersectPoints);
        int intersectPointsSize = result.size();
        Color d(225, 0, 0);
        /*if(result.size()>0 ){
            if (i >= 400 && i <= 410) {
                cout<<"y: "<<i<<endl<< "nilai x:";
                for(int k=0; k< intersectPointsSize; k++) {
                    cout << result[k].x<< "--"; //<< " , "<< result[k+1].x << "  ";
                }
                cout << endl;
                // for (int k = 0; k < ListOfIntersectPoints.size(); k++) {
                //     cout << ListOfIntersectPoints[k].x << "--";
                // }
                // cout << endl;
            }
        }*/
        for(int j = 0; j < intersectPointsSize-1; j+=2) {
            Line line(result[j], result[j + 1]);
            line.color = this->color;
            line.draw(sb);
            //line.draw(sb, line.getPoint1(), line.getPoint1().getDistance(line.getPoint2()), line.color, Color(line.color.r - 50, line.color.g - 50, line.color.b - 50));
            //line.drawTextured(sb, basePoint, textureWidth, textureHeight, textureCache);
        }
    }

    delete [] tipPoints;
}
Example #11
0
AUD_Int32s wov_adapt_gmm_si()
{
	AUD_Error  error = AUD_ERROR_NONE;
	AUD_Int32s ret   = 0;
	AUD_Int8s  wavPath[256] = { 0, };
	AUD_Int32s data;

	setbuf( stdout, NULL );
	setbuf( stdin, NULL );
	AUDLOG( "pls give adapt wav stream's folder path:\n" );
	wavPath[0] = '\0';
	data = scanf( "%s", wavPath );
	AUDLOG( "adapt wav stream's folder path is: %s\n", wavPath );

	// step 1: read UBM model from file
	void *hUbm = NULL;
	FILE *fpUbm = fopen( WOV_UBM_GMMMODEL_FILE, "rb" );
	if ( fpUbm == NULL )
	{
		AUDLOG( "cannot open ubm model file: [%s]\n", WOV_UBM_GMMMODEL_FILE );
		return AUD_ERROR_IOFAILED;
	}
	error = gmm_import( &hUbm, fpUbm );
	AUD_ASSERT( error == AUD_ERROR_NONE );
	fclose( fpUbm );
	fpUbm = NULL;

	// AUDLOG( "ubm GMM as:\n" );
	// gmm_show( hUbm );

	AUD_Int32s i = 0, j = 0;
	entry      *pEntry = NULL;
	dir        *pDir   = NULL;

	AUD_Int32s totalWinNum = 0;
	pDir = openDir( (const char*)wavPath );
	if ( pDir == NULL )
	{
		AUDLOG( "cannot open folder: %s\n", wavPath );
		return -1;
	}

	while ( ( pEntry = scanDir( pDir ) ) )
	{
		AUD_Int8s   keywordFile[256] = { 0, };
		AUD_Summary fileSummary;
		AUD_Int32s  sampleNum = 0;

		snprintf( (char*)keywordFile, 256, "%s/%s", wavPath, pEntry->name );
		// AUDLOG( "%s\n", keywordFile );

		ret = parseWavFromFile( keywordFile, &fileSummary );
		if ( ret < 0 )
		{
			continue;
		}
		AUD_ASSERT( fileSummary.channelNum == CHANNEL_NUM && fileSummary.bytesPerSample == BYTES_PER_SAMPLE && fileSummary.sampleRate == SAMPLE_RATE );

		// request memeory for template
		sampleNum = fileSummary.dataChunkBytes / fileSummary.bytesPerSample;
		for ( j = 0; j * FRAME_STRIDE + FRAME_LEN <= sampleNum; j++ )
		{
			;
		}
		j = j - MFCC_DELAY;

		totalWinNum += j;
	}
	closeDir( pDir );
	pDir = NULL;

	AUD_Matrix featureMatrix;
	featureMatrix.rows     = totalWinNum;
	featureMatrix.cols     = MFCC_FEATDIM;
	featureMatrix.dataType = AUD_DATATYPE_INT32S;
	ret = createMatrix( &featureMatrix );
	AUD_ASSERT( ret == 0 );

	AUD_Int32s currentRow  = 0;
	pDir = openDir( (const char*)wavPath );
	while ( ( pEntry = scanDir( pDir ) ) )
	{
		AUD_Int8s   keywordFile[256] = { 0, };
		AUD_Summary fileSummary;
		AUD_Int32s  sampleNum        = 0;
		void        *hMfccHandle     = NULL;

		snprintf( (char*)keywordFile, 256, "%s/%s", wavPath, pEntry->name );
		// AUDLOG( "%s\n", keywordFile );

		ret = parseWavFromFile( keywordFile, &fileSummary );
		if ( ret < 0 )
		{
			continue;
		}
		AUD_ASSERT( fileSummary.channelNum == CHANNEL_NUM && fileSummary.bytesPerSample == BYTES_PER_SAMPLE && fileSummary.sampleRate == SAMPLE_RATE );

		AUD_Int32s bufLen = fileSummary.dataChunkBytes;
		AUD_Int16s *pBuf  = (AUD_Int16s*)calloc( bufLen, 1 );
		AUD_ASSERT( pBuf );

		sampleNum = readWavFromFile( (AUD_Int8s*)keywordFile, pBuf, bufLen );
		AUD_ASSERT( sampleNum > 0 );

		// pre-processing

		 // pre-emphasis
		sig_preemphasis( pBuf, pBuf, sampleNum );

		 // calc framing number
		for ( j = 0; j * FRAME_STRIDE + FRAME_LEN <= sampleNum; j++ )
		{
			;
		}

		 // XXX: select salient frames
		AUD_Feature feature;
		feature.featureMatrix.rows     = j - MFCC_DELAY;
		feature.featureMatrix.cols     = MFCC_FEATDIM;
		feature.featureMatrix.dataType = AUD_DATATYPE_INT32S;
		feature.featureMatrix.pInt32s  = featureMatrix.pInt32s + currentRow * feature.featureMatrix.cols;

		feature.featureNorm.len      = j - MFCC_DELAY;
		feature.featureNorm.dataType = AUD_DATATYPE_INT64S;
		ret = createVector( &(feature.featureNorm) );
		AUD_ASSERT( ret == 0 );

		error = mfcc16s32s_init( &hMfccHandle, FRAME_LEN, WINDOW_TYPE, MFCC_ORDER, FRAME_STRIDE, SAMPLE_RATE, COMPRESS_TYPE );
		AUD_ASSERT( error == AUD_ERROR_NONE );

		error = mfcc16s32s_calc( hMfccHandle, pBuf, sampleNum, &feature );
		AUD_ASSERT( error == AUD_ERROR_NONE );

		error = mfcc16s32s_deinit( &hMfccHandle );
		AUD_ASSERT( error == AUD_ERROR_NONE );

		free( pBuf );
		pBuf   = NULL;
		bufLen = 0;

		ret = destroyVector( &(feature.featureNorm) );
		AUD_ASSERT( ret == 0 );

		currentRow += feature.featureMatrix.rows;
	}
	closeDir( pDir );
	pDir = NULL;

	AUD_Matrix llrMatrix;
	llrMatrix.rows     = totalWinNum;
	llrMatrix.cols     = gmm_getmixnum( hUbm );
	llrMatrix.dataType = AUD_DATATYPE_DOUBLE;
	ret = createMatrix( &llrMatrix );
	AUD_ASSERT( ret == 0 );

	AUD_Double llr = 0.;
	for ( j = 0; j < featureMatrix.rows; j++ )
	{
		AUD_Vector componentLLR;
		componentLLR.len      = llrMatrix.cols;
		componentLLR.dataType = AUD_DATATYPE_DOUBLE;
		componentLLR.pDouble  = llrMatrix.pDouble + j * llrMatrix.cols;

		llr = gmm_llr( hUbm, &(featureMatrix), j, &componentLLR );
	}

	AUD_Vector sumLlr;
	sumLlr.len      = llrMatrix.cols;
	sumLlr.dataType = AUD_DATATYPE_DOUBLE;
	ret = createVector( &sumLlr );
	AUD_ASSERT( ret == 0 );

	AUD_Double *pSumLlr = sumLlr.pDouble;
	for ( j = 0; j < llrMatrix.cols; j++ )
	{
		pSumLlr[j] = llrMatrix.pDouble[j];
	}
	for ( i = 1; i < llrMatrix.rows; i++ )
	{
		for ( j = 0; j < llrMatrix.cols; j++ )
		{
			pSumLlr[j] = logadd( pSumLlr[j],  *(llrMatrix.pDouble + i * llrMatrix.cols + j) );
		}
	}

#if 0
	AUD_Vector bestIndex;
	bestIndex.len      = TOP_N;
	bestIndex.dataType = AUD_DATATYPE_INT32S;
	ret = createVector( &bestIndex );
	AUD_ASSERT( ret == 0 );

	// get top TOP_N component
	ret = sortVector( &sumLlr, &bestIndex );
	AUD_ASSERT( ret == 0 );
#else
	llr = pSumLlr[0];
	for ( j = 1; j < sumLlr.len; j++ )
	{
		llr = logadd( llr, pSumLlr[j] );
	}
	// AUDLOG( "llr: %.f\n", llr );

	AUD_Vector sortIndex;
	sortIndex.len      = sumLlr.len;
	sortIndex.dataType = AUD_DATATYPE_INT32S;
	ret = createVector( &sortIndex );
	AUD_ASSERT( ret == 0 );

	ret = sortVector( &sumLlr, &sortIndex );
	AUD_ASSERT( ret == 0 );

	int    num = 0;
	double val = 0.;
	for ( i = 0; i < sortIndex.len; i++ )
	{
		// ln( 0.001 ) ~= -7.
		val =  pSumLlr[sortIndex.pInt32s[i]] - llr + 7.;
		// AUDLOG( "%f, \n", val );
		if ( val < 0 )
		{
			break;
		}
		num++;
	}
	// AUDLOG( "\n" );
	AUD_ASSERT( num > 0 );

	AUDLOG( "computed component num: %d\n", num );

	num = AUD_MAX( num, TOP_N );
	AUDLOG( "normalized component num: %d\n", num );

	AUD_Vector bestIndex;
	bestIndex.len      = num;
	bestIndex.dataType = AUD_DATATYPE_INT32S;
	bestIndex.pInt32s  = sortIndex.pInt32s;
#endif

	int slash = '/';
	char *ptr = strrchr( (char*)wavPath, slash );
	ptr++;

	// select imposter GMM
	void      *hImposterGmm        = NULL;
	AUD_Int8s imposterGmmName[256] = { 0, };
	snprintf( (char*)imposterGmmName, 256, "%s-imposter", ptr );
	error = gmm_select( &hImposterGmm, hUbm, &bestIndex, 0 | GMM_INVERTSELECT_MASK, imposterGmmName );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	gmm_show( hImposterGmm );

	// export gmm
	char imposterFile[256] = { 0 };
	snprintf( imposterFile, 256, "%s/%s-imposter.gmm", WOV_IMPOSTER_GMMMODEL_DIR, ptr );
	AUDLOG( "Export imposter GMM Model to: %s\n", imposterFile );
	FILE *fpImposterGmm = fopen( imposterFile, "wb" );
	AUD_ASSERT( fpImposterGmm );

	error = gmm_export( hImposterGmm, fpImposterGmm );
	AUD_ASSERT( error == AUD_ERROR_NONE );
	AUDLOG( "Export imposter GMM Model File Done\n" );

	fclose( fpImposterGmm );
	fpImposterGmm = NULL;

	error = gmm_free( &hImposterGmm );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	// select keyword GMM
	void      *hAdaptedGmm        = NULL;
	AUD_Int8s adaptedGmmName[256] = { 0, };
	snprintf( (char*)adaptedGmmName, 256, "%s", ptr );
	// AUDLOG( "%s\n", adaptedGmmName );
	error = gmm_select( &hAdaptedGmm, hUbm, &bestIndex, 0, adaptedGmmName );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	ret = destroyVector( &sumLlr );
	AUD_ASSERT( ret == 0 );

	ret = destroyMatrix( &llrMatrix );
	AUD_ASSERT( ret == 0 );

#if 0
	ret = destroyVector( &bestIndex );
	AUD_ASSERT( ret == 0 );
#else
	ret = destroyVector( &sortIndex );
	AUD_ASSERT( ret == 0 );
#endif

#if 1
	// adapt GMM
	error = gmm_adapt( hAdaptedGmm, &featureMatrix );
	AUD_ASSERT( error == AUD_ERROR_NONE );
#endif

	gmm_show( hAdaptedGmm );

	// export gmm
	char modelFile[256] = { 0 };
	snprintf( modelFile, 256, "%s/%s.gmm", WOV_KEYWORD_GMMMODEL_DIR, ptr );
	AUDLOG( "Export GMM Model to: %s\n", modelFile );
	FILE *fpGmm = fopen( modelFile, "wb" );
	AUD_ASSERT( fpGmm );

	error = gmm_export( hAdaptedGmm, fpGmm );
	AUD_ASSERT( error == AUD_ERROR_NONE );
	AUDLOG( "Export GMM Model File Done\n" );

	fclose( fpGmm );
	fpGmm = NULL;

	ret = destroyMatrix( &featureMatrix );
	AUD_ASSERT( ret == 0 );

	error = gmm_free( &hAdaptedGmm );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	error = gmm_free( &hUbm );
	AUD_ASSERT( error == AUD_ERROR_NONE );

	AUDLOG( "keyword model adapt2 done\n" );

	return 0;
}
Example #12
0
SEXP typeconvert(SEXP call, SEXP op, SEXP args, SEXP env)
{
    SEXP cvec, a, dup, levs, dims, names, dec;
    SEXP rval = R_NilValue; /* -Wall */
    int i, j, len, asIs;
    Rboolean done = FALSE;
    char *endp;
    const char *tmp = NULL;
    LocalData data = {NULL, 0, 0, '.', NULL, NO_COMCHAR, 0, NULL, FALSE,
		      FALSE, 0, FALSE, FALSE};
    Typecvt_Info typeInfo;      /* keep track of possible types of cvec */
    typeInfo.islogical = TRUE;  /* we can't rule anything out initially */
    typeInfo.isinteger = TRUE;
    typeInfo.isreal = TRUE;
    typeInfo.iscomplex = TRUE;
    data.NAstrings = R_NilValue;

    args = CDR(args);

    if (!isString(CAR(args)))
	error(_("the first argument must be of mode character"));

    data.NAstrings = CADR(args);
    if (TYPEOF(data.NAstrings) != STRSXP)
	error(_("invalid '%s' argument"), "na.strings");

    asIs = asLogical(CADDR(args));
    if (asIs == NA_LOGICAL) asIs = 0;

    dec = CADDDR(args);

    if (isString(dec) || isNull(dec)) {
	if (length(dec) == 0)
	    data.decchar = '.';
	else
	    data.decchar = translateChar(STRING_ELT(dec, 0))[0];
    }

    cvec = CAR(args);
    len = length(cvec);

    /* save the dim/dimnames attributes */

    PROTECT(dims = getAttrib(cvec, R_DimSymbol));
    if (isArray(cvec))
	PROTECT(names = getAttrib(cvec, R_DimNamesSymbol));
    else
	PROTECT(names = getAttrib(cvec, R_NamesSymbol));

    /* Use the first non-NA to screen */
    for (i = 0; i < len; i++) {
	tmp = CHAR(STRING_ELT(cvec, i));
	if (!(STRING_ELT(cvec, i) == NA_STRING || strlen(tmp) == 0
	      || isNAstring(tmp, 1, &data) || isBlankString(tmp)))
	    break;
    }
    if (i < len) {  /* not all entries are NA */
	ruleout_types(tmp, &typeInfo, &data);
    }

    if (typeInfo.islogical) {
	PROTECT(rval = allocVector(LGLSXP, len));
	for (i = 0; i < len; i++) {
	    tmp = CHAR(STRING_ELT(cvec, i));
	    if (STRING_ELT(cvec, i) == NA_STRING || strlen(tmp) == 0
		|| isNAstring(tmp, 1, &data) || isBlankString(tmp))
		LOGICAL(rval)[i] = NA_LOGICAL;
	    else {
		if (strcmp(tmp, "F") == 0 || strcmp(tmp, "FALSE") == 0)
		    LOGICAL(rval)[i] = 0;
		else if(strcmp(tmp, "T") == 0 || strcmp(tmp, "TRUE") == 0)
		    LOGICAL(rval)[i] = 1;
		else {
		    typeInfo.islogical = FALSE;
		    ruleout_types(tmp, &typeInfo, &data);
		    break;
		}
	    }
	}
	if (typeInfo.islogical) done = TRUE; else UNPROTECT(1);
    }

    if (!done && typeInfo.isinteger) {
	PROTECT(rval = allocVector(INTSXP, len));
	for (i = 0; i < len; i++) {
	    tmp = CHAR(STRING_ELT(cvec, i));
	    if (STRING_ELT(cvec, i) == NA_STRING || strlen(tmp) == 0
		|| isNAstring(tmp, 1, &data) || isBlankString(tmp))
		INTEGER(rval)[i] = NA_INTEGER;
	    else {
		INTEGER(rval)[i] = Strtoi(tmp, 10);
		if (INTEGER(rval)[i] == NA_INTEGER) {
		    typeInfo.isinteger = FALSE;
		    ruleout_types(tmp, &typeInfo, &data);
		    break;
		}
	    }
	}
	if(typeInfo.isinteger) done = TRUE; else UNPROTECT(1);
    }

    if (!done && typeInfo.isreal) {
	PROTECT(rval = allocVector(REALSXP, len));
	for (i = 0; i < len; i++) {
	    tmp = CHAR(STRING_ELT(cvec, i));
	    if (STRING_ELT(cvec, i) == NA_STRING || strlen(tmp) == 0
		|| isNAstring(tmp, 1, &data) || isBlankString(tmp))
		REAL(rval)[i] = NA_REAL;
	    else {
		REAL(rval)[i] = Strtod(tmp, &endp, FALSE, &data);
		if (!isBlankString(endp)) {
		    typeInfo.isreal = FALSE;
		    ruleout_types(tmp, &typeInfo, &data);
		    break;
		}
	    }
	}
	if(typeInfo.isreal) done = TRUE; else UNPROTECT(1);
    }

    if (!done && typeInfo.iscomplex) {
	PROTECT(rval = allocVector(CPLXSXP, len));
	for (i = 0; i < len; i++) {
	    tmp = CHAR(STRING_ELT(cvec, i));
	    if (STRING_ELT(cvec, i) == NA_STRING || strlen(tmp) == 0
		|| isNAstring(tmp, 1, &data) || isBlankString(tmp))
		COMPLEX(rval)[i].r = COMPLEX(rval)[i].i = NA_REAL;
	    else {
		COMPLEX(rval)[i] = strtoc(tmp, &endp, FALSE, &data);
		if (!isBlankString(endp)) {
		    typeInfo.iscomplex = FALSE;
		    /* this is not needed, unless other cases are added */
		    ruleout_types(tmp, &typeInfo, &data);
		    break;
		}
	    }
	}
	if(typeInfo.iscomplex) done = TRUE; else UNPROTECT(1);
    }

    if (!done) {
	if (asIs) {
	    PROTECT(rval = duplicate(cvec));
	    for (i = 0; i < len; i++)
		if(isNAstring(CHAR(STRING_ELT(rval, i)), 1, &data))
		    SET_STRING_ELT(rval, i, NA_STRING);
	}
	else {
	    PROTECT(dup = duplicated(cvec, FALSE));
	    j = 0;
	    for (i = 0; i < len; i++) {
		/* <NA> is never to be a level here */
		if (STRING_ELT(cvec, i) == NA_STRING) continue;
		if (LOGICAL(dup)[i] == 0 && !isNAstring(CHAR(STRING_ELT(cvec, i)), 1, &data))
		    j++;
	    }

	    PROTECT(levs = allocVector(STRSXP,j));
	    j = 0;
	    for (i = 0; i < len; i++) {
		if (STRING_ELT(cvec, i) == NA_STRING) continue;
		if (LOGICAL(dup)[i] == 0 && !isNAstring(CHAR(STRING_ELT(cvec, i)), 1, &data))
		    SET_STRING_ELT(levs, j++, STRING_ELT(cvec, i));
	    }

	    /* We avoid an allocation by reusing dup,
	     * a LGLSXP of the right length
	     */
	    rval = dup;
	    SET_TYPEOF(rval, INTSXP);

	    /* put the levels in lexicographic order */

	    sortVector(levs, FALSE);

	    PROTECT(a = matchE(levs, cvec, NA_INTEGER, env));
	    for (i = 0; i < len; i++)
		INTEGER(rval)[i] = INTEGER(a)[i];

	    setAttrib(rval, R_LevelsSymbol, levs);
	    PROTECT(a = mkString("factor"));
	    setAttrib(rval, R_ClassSymbol, a);
	    UNPROTECT(3);
	}
    }

    setAttrib(rval, R_DimSymbol, dims);
    setAttrib(rval, isArray(cvec) ? R_DimNamesSymbol : R_NamesSymbol, names);
    UNPROTECT(3);
    return rval;
}
vector<string> DecodingLayer::getDecodedLabels() {
    int nbWords = words.size();

    for(int t = 1; t < T; ++t)
    {
        token highestOutputToken = getHighestScoreOutputToken(t);

        for(int i = 0; i < nbWords; ++i)
        {
            words[i].tok[0][t] = highestOutputToken;
            words[i].tok[0][t].history.push_back(words[i].label); //add w to tok(w, 0, t) history

            string w_prime = createExtendedLabel(words[i].label);
            int S = w_prime.size();
            for(int s = 0; s < S; ++s)
            {
//                vector<token> P; //don't used -- compute maxTok directly
                token maxTok = words[i].tok[s+2][t-1];
//                P.push_back(words[i].tok[s+2][t-1]);
//                P.push_back(words[i].tok[s+1][t-1]);
                int prevSeg = //(s == 0) ? 0 :
                              s+1; // s+1 is different for the first segment !! better results without condition

                if(words[i].tok[prevSeg][t-1].score > maxTok.score)
                    maxTok = words[i].tok[prevSeg][t-1];

                if(w_prime[s] != ' ' && s >= 2 && w_prime[s-2] != w_prime[s])
                {
//                    P.push_back(words[i].tok[s][t-1]);
                    if(words[i].tok[s][t-1].score > maxTok.score)
                        maxTok = words[i].tok[s][t-1];
                }
                words[i].tok[s+2][t] = maxTok; //highest scoring token from set P
                words[i].tok[s+2][t].score += safe_log( y(t, alphabet[w_prime[s]]) );
            }

            //compute the highest score
            token maxTok = words[i].tok[S + 1][t];
            if(words[i].tok[S][t].score > maxTok.score)
                maxTok = words[i].tok[S][t];
            words[i].tok[1][t] = maxTok;
        }
    }


    //output the top 10 bestwords
    sortVector(words);
    token maxTok = words[0].tok[1][T-1];
    string bestword = words[0].label;

    cout << "+++ ";
    for(int i = 0; i < maxTok.history.size(); ++i)
        cout << maxTok.history[i] <<  " ";
    cout << "++++\n";

    vector<string> result;
    for(int i = 0; i < 10; ++i)
        result.push_back(words[i].label);

    return result;//maxTok.history;
}