Ejemplo n.º 1
0
/*----------------------------------------------------------------------------------------------------------------------
|	SquareMatrix copy constructor. This is necessary because the standard vector resize function in some implementations
|	of the standard template library creates only one element with the default constructor, then creates the remaining
|	elements using the copy constructor.
*/
SquareMatrix::SquareMatrix(
  const SquareMatrix & other)	/**< is the SquareMatrix to copy */
  : id(++k), m(0), dim(other.dim)
	{
	//std::cerr << "|----> copy constructing SquareMatrix " << id << " from " << other.id << " <----" << (this) << std::endl;
	if (dim > 0)
		{
		CreateMatrix(dim, 0.0);
		double * pother = &other.m[0][0];
		double * p = &m[0][0];
		unsigned last = dim*dim;
		for (unsigned i = 0; i < last; ++i)
			*p++ = *pother++;
		}
	}
/* CalcCovs: calculate covariance of speech data */
void CalcCovs(void)
{
   int x,y,s,V;
   float meanx,meany,varxy,n;
   Matrix fullMat;
   
   if (totalCount<2)
      HError(2021,"CalcCovs: Only %d speech frames accumulated",totalCount);
   if (trace&T_TOP)
      printf("%ld speech frames accumulated\n", totalCount);
   n = (float)totalCount;     /* to prevent rounding to integer below */
   for (s=1; s<=hset.swidth[0]; s++){  /* For each stream   */
      V = hset.swidth[s];
      for (x=1; x<=V; x++)            /* For each coefficient ... */
         accs[s].meanSum[x] /= n;         /* ... calculate mean */
      for (x=1;x<=V;x++) {
         meanx = accs[s].meanSum[x];      /* ... and [co]variance */
         if (fullcNeeded[s]) {
            for (y=1; y<=x; y++) {
               meany = accs[s].meanSum[y];
               varxy = accs[s].squareSum.inv[x][y]/n - meanx*meany;
               accs[s].squareSum.inv[x][y] =
                  (x != y || varxy > minVar) ? varxy : minVar;    
            }
         }
         else {
            varxy = accs[s].squareSum.var[x]/n - meanx*meanx;
            accs[s].fixed.var[x] = (varxy > minVar) ? varxy :minVar;
         }
      }
      if (fullcNeeded[s]) { /* invert covariance matrix */
         fullMat=CreateMatrix(&gstack,V,V);
         ZeroMatrix(fullMat); 
         CovInvert(accs[s].squareSum.inv,fullMat);
         Mat2Tri(fullMat,accs[s].fixed.inv);
         FreeMatrix(&gstack,fullMat);
      }
      if (trace&T_COVS) {
         printf("Stream %d\n",s);
         if (meanUpdate)
            ShowVector(" Mean Vector ", accs[s].meanSum,12);
         if (fullcNeeded[s]) {
            ShowTriMat(" Covariance Matrix ",accs[s].squareSum.inv,12,12);
         } else
            ShowVector(" Variance Vector ", accs[s].fixed.var,12);
      }
   }
}
Ejemplo n.º 3
0
LRESULT CALLBACK ScreensaverProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	MATRIX* matrix = GetMatrix(hwndDlg);

	switch(uMsg)
	{
		case WM_NCCREATE:
			_ShowCursor(0);

			matrix = CreateMatrix(hwndDlg, ((CREATESTRUCT*)lParam)->cx, ((CREATESTRUCT*)lParam)->cy);

			if(!matrix)
			{
				MessageBox(hwndDlg, L"Ошибка работы скринсейвера", L"Ошибка", MB_OK | MB_ICONSTOP);
				return 0;
			}

			SetMatrix(hwndDlg, matrix);
			SetTimer(hwndDlg, 0xdeadbeef, ((SPEED_MAX - g_nMatrixSpeed) + SPEED_MIN) * 10, 0);

			return 1;

		case WM_TIMER:
			DecodeMatrix(hwndDlg, matrix);
			break;

		case WM_KEYDOWN:
			if(wParam == VK_ESCAPE)
				SendMessage(hwndDlg, WM_CLOSE, 0, 0);

			break;

		case WM_CLOSE:
			_ShowCursor(1);
			DestroyMatrix(matrix);

			DestroyWindow(hwndDlg);
			PostQuitMessage(0);

			break;

		default:
			return DefWindowProc(hwndDlg, uMsg, wParam, lParam);
	}

	return 0;
}
Ejemplo n.º 4
0
void UIMatrix::CreateChildren()
{
	if (childrenCreated)
		return;

	/*
	/// Create a label
	label = new UILabel();
	label->text = name;
	label->sizeRatioY = 0.1f;
	label->alignmentY = 0.95f;
	AddChild(label);
*/
	/// Booyakacha!
	CreateMatrix();
	childrenCreated = true;
}
Ejemplo n.º 5
0
void DlxSolve(INT *Data, INT nb_rows, INT nb_cols, 
	INT &nb_sol, INT &nb_backtrack, 
	INT f_write_file, const BYTE *solution_fname, 
	INT f_write_tree_file, const BYTE *tree_fname, 
	INT verbose_level)
{
	INT f_v = (verbose_level >= 1);

	if (f_v) {
		cout << "DlxSolve nb_rows = " << nb_rows << " nb_cols = " << nb_cols << endl;
		}


	CreateMatrix(Data, nb_rows, nb_cols, verbose_level - 1);

	open_solution_file(f_write_file, solution_fname, verbose_level);
	open_tree_file(f_write_tree_file, tree_fname, verbose_level);

	dlx_nb_backtrack_nodes = 0;



	DlxSearch(0);


	nb_sol = ::dlx_nb_sol;
	nb_backtrack = dlx_nb_backtrack_nodes;


	if (f_v) {
		cout << "DlxSolve finds " << dlx_nb_sol << " solutions with nb_backtrack_nodes=" << dlx_nb_backtrack_nodes << endl;
		}

	close_solution_file(f_write_file);
	close_tree_file(f_write_tree_file);
	



	DeleteMatrix();


	if (f_v) {
		cout << "DlxSolve done" << endl;
		}
}
Ejemplo n.º 6
0
/* Function: DeterminantOfMatrix
 * -----------------
 *		Description: Returns the determinant of a square matrix
 *
 *		Arguments:
 *			Arg1: (SMatrix) Matrix with which to find determinant.
 *
 *		Returns: (int) Determinant of a matrix
 *
 *		Author: Jacob Hull
 */
int DeterminantOfMatrix( SMatrix* qMatrix )
{
	if( qMatrix->m_iRows != qMatrix->m_iColumns )
	{
		return 0;
	}
	else if( qMatrix->m_iRows == 2 )
	{
		return( ( qMatrix->m_ppdMatrix[0][0] * qMatrix->m_ppdMatrix[1][1] ) - ( qMatrix->m_ppdMatrix[0][1] * qMatrix->m_ppdMatrix[1][0] ) );
	}
	else
	{
		int iMult = 1;
		int iProduct = 0;
		
		SMatrix* qSubMatrix = CreateMatrix( qMatrix->m_iRows - 1, qMatrix->m_iRows - 1 );

		for( int i = 0; i < qMatrix->m_iRows; ++i )
		{		
			for( int j = 0; j < ( qMatrix->m_iRows - 1 ); ++j )
			{
				int iSpace = 0;
				for( int k = 0; k < qMatrix->m_iRows; ++k )
				{
					if( k == i )
					{
						iSpace = 1;
					}
					else
					{
						qSubMatrix->m_ppdMatrix[j][k-iSpace] = qMatrix->m_ppdMatrix[j+1][k];
					}
				}
			}
			iProduct += iMult * ( qMatrix->m_ppdMatrix[0][i] * DeterminantOfMatrix( qSubMatrix ) );
			iMult *= -1;
		}
		
		FreeMatrix( qSubMatrix );
		
		return iProduct;
	}
	
	return 0;
}
Ejemplo n.º 7
0
// read in patterns from file
bool ReadPatterns( void ) 
{
	ifstream infile;
	int 	 dummyInt;
	float	 dummyFloat;
	char	 filename[256];
	
// open the file
	strcpy( filename, gSequenceAPI->SequenceGetDirectory());
	strcat( filename, "/pat.txt" );	
	infile.open( filename );
	if ( infile.fail() )
	{		
		FileOpenError( filename );
		return false;
	}

// read the number of patterns
	SkipComments( &infile );
	infile >> kNumPats;

// read the sequence type, but ignored here as by default we use cyclic sequences
	SkipComments( &infile );
	infile >> dummyInt;
	
// create the storage matrix
	gOnlinePatterns = CreateMatrix( 0.0, kNumPats, gSequenceAPI->SequenceGetLayerSize() );

// read in the pattern values
	for ( int i = 0; i < kNumPats; i++ )
	{
		for ( int j = 0; j < gSequenceAPI->SequenceGetLayerSize(); j++ )
		{
			SkipComments( &infile );
			infile >> gOnlinePatterns[i][j];
		}
	}
	
// close and return
	infile.close();
	return true;
}
Ejemplo n.º 8
0
matrix* AssembleF(matrix* (*makef)(double, double), matrix* mesh, double Pe)
{
    matrix *F, *f;
    int n, i;

    n = mtxlen2(mesh);

    F = CreateMatrix(n+1, 1);

    for(i=0; i<n; i++) {
        f = makef(Pe, val(mesh, i, 0));

        addval(F, val(f, 0, 0), i, 0);
        addval(F, val(f, 1, 0), i+1, 0);

        DestroyMatrix(f);
    }

    return F;
}
Ejemplo n.º 9
0
matrix* fitdata(matrix *t, matrix *J)
{
    double J0, Jt;
    J0 = val(J, 0, 0);
    Jt = val(J, nRows(J)-1, 0);

    matrix *beta0, *beta;
    beta0 = CreateMatrix(4, 1);
    setval(beta0,
           sqrt( .5*(Jt-J0) ),
           0, 0);
    setval(beta0, sqrt(10), 1, 0);
    setval(beta0,
           sqrt( .5*(Jt-J0) ),
           2, 0);
    setval(beta0, sqrt(200), 3, 0);
    beta = fitnlmP(&PronyModel, t, J, beta0, &J0);
    DestroyMatrix(beta0);
    return beta;
}
Ejemplo n.º 10
0
matrix* MeshXCoords(matrix *mesh, double left, double right)
{
    matrix *x;
    int i;
    int n = mtxlen2(mesh);

    x = CreateMatrix(n+1, 1);

    setval(x, left, 0, 0);

    for(i=1; i<=n; i++) {
        setval(x, val(x, i-1, 0) + val(mesh, i-1, 0), i, 0);
    }

    if((val(x, n, 0) - right) > 1e-5) {
        fprintf(stderr, "Warning: mesh not aligned.\n");
    }

    return x;
}
Ejemplo n.º 11
0
/**
 * Matlab "polyfit" function. This fits the x-y data to a polynomial of
 * arbitrary order using the regress function.
 * @param x Column vector of dependent variable values
 * @param y Column vector of independent variable values
 * @param order Degree of the polynomial to fit to
 * @returns Column matrix of fitted parameters. Element n corresponds to the
 *      coefficient in front of x^n.
 */
matrix* polyfit(matrix* x, matrix* y, int order)
{
    matrix *X, *beta;
    int i, j, nelem;

    X = NULL;
    nelem = nRows(x);

    X = CreateMatrix(nelem, order+1);

    for(i=0; i<=nelem; i++) {
        for(j=0; j<=order; j++) {
            setval(X, pow(val(x, i, 0), j), i, j);
        }
    }

    beta = regress(y, X);
    DestroyMatrix(X);

    return beta;
}
Ejemplo n.º 12
0
void BuildData(void) {
	int a, b, c;
	int Index;
	nCol = 324;
	nRow = 729 + 1;

	for (a = 0; a < 9; a++) {
		for (b = 0; b < 9; b++) {
			for (c = 0; c < 9; c++) {
				Index = getIn(c, a, b);
				Data[SQ_OFFSET + retSq(Index)][Index] = 1; //Constraint 1: Only 1 per square
				Data[RW_OFFSET + retRn(Index)][Index] = 1; //Constraint 2: Only 1 of per number per Row
				Data[CL_OFFSET + retCn(Index)][Index] = 1; //Constraint 3: Only 1 of per number per Column
				Data[BX_OFFSET + retBn(Index)][Index] = 1; //Constraint 4: Only 1 of per number per Box
			}
		}
	}
	for (a = 0; a < nCol; a++)
		Data[a][nRow - 1] = 2;

	CreateMatrix();

	for (a = 0; a < RW_OFFSET; a++) {
		Matrix[a][nRow - 1].IDName = 'S';
		Matrix[a][nRow - 1].IDNum = a;
	}
	for (a = RW_OFFSET; a < CL_OFFSET; a++) {
		Matrix[a][nRow - 1].IDName = 'R';
		Matrix[a][nRow - 1].IDNum = a - RW_OFFSET;
	}
	for (a = CL_OFFSET; a < BX_OFFSET; a++) {
		Matrix[a][nRow - 1].IDName = 'C';
		Matrix[a][nRow - 1].IDNum = a - CL_OFFSET;
	}
	for (a = BX_OFFSET; a < nCol; a++) {
		Matrix[a][nRow - 1].IDName = 'B';
		Matrix[a][nRow - 1].IDNum = a - BX_OFFSET;
	}
}
Ejemplo n.º 13
0
int main()
{
    int i;
    CreateMatrix();
    printf("The number of vertices is %d\n\n",NrOfVertices);
    printf("The adjacency matrix is:\n");
    PrintMatrix();

    char FirstVertex;   //the vertex from where the minimum spanning tree begins
    printf("\nInput the vertex from which you want to start the Minimum Spanning Tree\n");
    scanf("%c",&FirstVertex);
    //printf("%c\n",FirstVertex);

    int position;   //to obtain the position of the FirstVertex from the vector they are stored
    for(i=0;i<NrOfVertices;i++)
        if(FirstVertex==vertices[i])
            {position=i;
             break;}

    PRIM(position);

    return 0;
}
Ejemplo n.º 14
0
// Najde vsechny jmena Metod a Parametru a spravne je oznaci
int CKerNamesMain::FindMethodsAndParams() {
	CKerNameList *n = Names;
	int err=1;
	if (!MatrixesCalculated) CreateMatrix();
	// Oznacim stred komponenty
	while (n) {
		if (n->name->Type==eKerNTmethod) if (n->name->Component->Type==eKerNTvoid) n->name->Component->Type = eKerNTmethod;
		if (n->name->Type==eKerNTparam) if (n->name->Component->Type==eKerNTvoid) n->name->Component->Type = eKerNTparam;
		if (n->name->Type==eKerNTobject) if (n->name->Component->Type==eKerNTvoid) n->name->Component->Type = eKerNTobjectVoid;
		n=n->next;
	}
	n = Names;
	// Oznacim celou komponentu, podle oznaceni stredu
	while (n) {
		if (n->name->Component->Type==eKerNTmethod) if (n->name->Type==eKerNTvoid||n->name->Type==eKerNTmethod) n->name->Type = eKerNTmethod; else err=0;
		if (n->name->Component->Type==eKerNTparam) if (n->name->Type==eKerNTvoid||n->name->Type==eKerNTparam) n->name->Type = eKerNTparam; else err=0;
		if (n->name->Component->Type==eKerNTobject || n->name->Component->Type==eKerNTobjectVoid) {
			if (n->name->Type==eKerNTvoid) n->name->Type = eKerNTobjectVoid;
			else if (n->name->Type!=eKerNTobject && n->name->Type!=eKerNTobjectVoid) err=0;
		}
		n=n->next;
	}
	return err;
}
Ejemplo n.º 15
0
void SobelEdge::Filter(unsigned char** input, int col, int row)
{
    int i = 0, j = 0;
    float tempAngle = 0;
    m_ppEdgeMap = (unsigned char**)CreateMatrix(col+2, row+2, -1, -1, sizeof(unsigned char), &m_lPointerOffset);
    if(m_bSaveAsOriginal)
    {
        m_ppOriginalEdgeMap = (unsigned char**)CreateMatrix(col+2, row+2, -1, -1, sizeof(unsigned char), &m_lPointerOffset);
    }
    AllocateMemory(col, row, 0, 0);
    float **tempEdge = NULL;
	float **tempEdge1 = NULL;

    long long tempPointerOffset;
    tempEdge = (float**)CreateMatrix(col+2, row+2, -1, -1, sizeof(float), &tempPointerOffset);
	tempEdge1 = (float**)CreateMatrix(col+2, row+2, -1, -1, sizeof(float), &tempPointerOffset);

	float max = 0.0, min = 50000000;

	if(m_fLowerThreshold > m_fUpperThreshold)
	{
		std::cerr<<"Lower threshold is bigger than the upper threshold!"<<std::endl;
		return;
	}

    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            // Simple Sobel filter kernels.
            float temp = 0.0, temp1 = 0.0, temp2 = 0.0;
            temp = (float)(input[i-1][j-1]*m_SobelOperator1[0][0] + input[i-1][j]*m_SobelOperator1[0][1] + input[i-1][j+1]*m_SobelOperator1[0][2] + 
                        input[i][j-1]*m_SobelOperator1[1][0]   + input[i][j]*m_SobelOperator1[1][1]   + input[i][j+1]*m_SobelOperator1[1][2] + 
                        input[i+1][j-1]*m_SobelOperator1[2][0] + input[i+1][j]*m_SobelOperator1[2][1] + input[i+1][j+1]*m_SobelOperator1[2][2]);

            temp1 = (float)(input[i-1][j-1]*m_SobelOperator2[0][0] + input[i-1][j]*m_SobelOperator2[0][1] + input[i-1][j+1]*m_SobelOperator2[0][2] +
                        input[i][j-1]*m_SobelOperator2[1][0]   + input[i][j]*m_SobelOperator2[1][1]   + input[i][j+1]*m_SobelOperator2[1][2] +
                        input[i+1][j-1]*m_SobelOperator2[2][0] + input[i+1][j]*m_SobelOperator2[2][1] + input[i+1][j+1]*m_SobelOperator2[2][2]);

            temp2 = temp*temp + temp1*temp1;

            // Preparation for converting float type to unsigned char for saving unthresholded edgemap.
			if(temp2>max)
			{
				max = temp2;
			}
			if(temp2<min)
			{
				min = temp2;
			}
			tempEdge[i][j] = temp2;

            tempAngle = atan2(temp, temp1);

            m_ppGradientDirection[i][j] = tempAngle;
        }
    }
    // Converting float to unsigned char for saving.
    Suppress(m_iColumns, m_iRows, tempEdge, tempEdge1);
	if(m_bSaveAsOriginal)
	{
		for(i=0;i<row;i++)
		{
			for(j=0;j<col;j++)
			{
				m_ppOriginalEdgeMap[i][j] = (unsigned char)(255.0-(tempEdge1[i][j]/(max-min)*255.0)); // Edge is black
			}
		}
	}
    for(i=0;i<row;i++)
	{
		for(j=0;j<col;j++)
		{
			if(tempEdge1[i][j]>m_fUpperThreshold)
            {
                m_ppEdgeMap[i][j] = 0; // Edge is black
#ifdef _DEBUG					
                m_statistic++;
#endif
            }
			else if(tempEdge1[i][j]<=m_fUpperThreshold && tempEdge1[i][j]>m_fLowerThreshold)
			{
				m_MaybePixels.push_back(PixelLocation(j, i)); // Remember maybe-pixels
			}
            else
            {
                m_ppEdgeMap[i][j] = 255;
            }
		}
	}
	Resolveambiguity(); // Resolve maybe-pixels

    tempEdge += tempPointerOffset;
    if(tempEdge != NULL)
    {
        free(tempEdge);
    }
	tempEdge1 += tempPointerOffset;
    if(tempEdge1 != NULL)
    {
        free(tempEdge1);
    }
#ifdef _DEBUG
    std::cout<<"Edge Pixels: "<<m_statistic<<std::endl;
#endif
}
Ejemplo n.º 16
0
// Porovnani
int CKerNamesMain::Compare(CKerName *name1,CKerName *name2) {
	//0 - neporovnatelne, 1 - n1 je otcem n2, 2 - n1 je synem n2, 3 - cyklus, identifikace poradovymi cisly
	if (MatrixesCalculated==0) CreateMatrix();
	if (name1->Component!=name2->Component) return 0;
	return Matrix[name1->number][name2->MatrixPos];
}
Ejemplo n.º 17
0
void BoxBrowser::CreateMaxtrices()
{
	mtxBox.clear();

	float zoom1 = 395.0f;// lol.  theres probably a better way to do it than to scale the whole matrix.
	float zoom2 = 395.0f;// but this is working for now.
	float zoom3 = 395.0f;
	float zoom4 = 395.0f;
	float zoom5 = 395.0f;

	float posY1 = 362.0f;
	float posY2 = 362.0f;
	float posY3 = 362.0f;
	float posY4 = 362.0f;
	float posY5 = 362.0f;

	float posZ1 = 5600.0f;
	float posZ2 = 5600.0f;
	float posZ3 = 5600.0f;
	float posZ4 = 5600.0f;
	float posZ5 = 5600.0f;

	float rotX1 = 7.5f;
	float rotX2 = 7.5f;
	float rotX3 = 7.5f;
	float rotX4 = 7.5f;
	float rotX5 = 7.5f;

	float rotZ1 = 180;
	float rotZ2 = 180;
	float rotZ3 = 180;
	float rotZ4 = 180;
	float rotZ5 = 180;

	float angleLeft = 105.0f;
	float angleCenter = 180.0f;
	float angleRight = 75.0f;

	float angleDeltaLeft = 2.0f;
	float angleDeltaRight = 2.0f;

	float spacingSides = 110.0f;
	float spacingCenter = 400.0f;

	float selectedX = 0.0f;

	float rightAdjXpos = 100.0f;//move all the boxes on the right over a bit


	int left = BOXES_PER_SIDE - 1;
	int right = 0;

	int sideFrames = ( ( BOXES_PER_SIDE - 1 ) * ( ANIMATION_FRAMES ) ) + 1;
	int sideCenterFrames = ( ANIMATION_FRAMES - 1 );
	float angleDeltaLeftMtx = ( angleDeltaLeft / ANIMATION_FRAMES );
	float angleDeltaLeftCenterMtx = ( angleCenter - angleLeft ) / ANIMATION_FRAMES;
	float angleDeltaRightMtx = ( angleDeltaRight / ANIMATION_FRAMES );
	float angleDeltaRightCenterMtx = ( angleRight - angleCenter ) / ANIMATION_FRAMES;
	float spacingSidesMtx = ( spacingSides / ANIMATION_FRAMES );
	left = sideFrames;
	right = 0;
	//create left matrices
	for( int i = 0; i < sideFrames; i++ )
	{
		int rotx, roty, rotz, posx, posy, posz;
		float scale;

		rotx = ( rotX2 - ( left * ( rotX2 - rotX1 ) / sideFrames ) );
		roty = ( angleLeft - ( left * angleDeltaLeftMtx ) );
		rotz = ( rotZ2 - ( left * ( rotZ2 - rotZ1 ) / BOXES_PER_SIDE ) );

		posx = ( selectedX - ( spacingCenter + ( left * spacingSidesMtx ) ) );
		posy = ( posY2 - ( left * ( posY2 - posY1 ) / sideFrames ) );
		posz = ( posZ2 - ( left * ( posZ2 - posZ1 ) / sideFrames ) );

		scale = ( zoom2 - ( left * ( zoom2 - zoom1 ) / sideFrames ) );
		left--;

		CreateMatrix( posx, posy, posz, rotx, roty, rotz, scale );
	}

	//create center matrices
	int leftCenterSpacingX = ( selectedX - spacingCenter ) / ANIMATION_FRAMES;
	left = sideCenterFrames;
	for( int i = 0; i < sideCenterFrames; i++ )
	{
		int rotx, roty, rotz, posx, posy, posz;
		float scale;

		rotx = ( rotX3 - ( left * ( rotX3 - rotX2 ) / sideCenterFrames ) );
		roty = ( angleLeft + ( i * angleDeltaLeftCenterMtx ) );
		rotz = ( rotZ3 - ( left * ( rotZ3 - rotZ2 ) / sideCenterFrames ) );

		posx = ( selectedX + ( left * leftCenterSpacingX ) );
		posy = ( posY3 - ( left * ( posY3 - posY2 ) / sideCenterFrames ) );
		posz = ( posZ3 - ( left * ( posZ3 - posZ2 ) / sideCenterFrames ) );

		scale = ( zoom3 - ( left * ( zoom3 - zoom2 ) / sideCenterFrames ) );
		left--;

		CreateMatrix( posx, posy, posz, rotx, roty, rotz, scale );
	}

	//center matrix
	CreateMatrix( selectedX, posY3, posZ3, rotX3, angleCenter, rotZ3, zoom3 );

	//create right-center matrices
	float rightCenterSpacingX = ( selectedX - ( spacingCenter + rightAdjXpos ) ) / ANIMATION_FRAMES;
	left = sideCenterFrames;
	for( int i = 0; i < sideCenterFrames; i++ )
	{
		int rotx, roty, rotz, posx, posy, posz;
		float scale;

		rotx = ( rotX4 + ( i * ( rotX5 - rotX4 ) / sideCenterFrames ) );
		roty = ( angleCenter + ( ( i + 1 ) * angleDeltaRightCenterMtx ) );
		rotz = ( rotZ4 + ( i * ( rotZ5 - rotZ4 ) / sideCenterFrames ) );

		posx = ( selectedX - ( i * rightCenterSpacingX ) );
		posy = ( posY4 + ( i * ( posY5 - posY4 ) / sideCenterFrames ) );
		posz = ( posZ4 + ( i * ( posZ5 - posZ4 ) / sideCenterFrames ) );

		scale = ( zoom4 + ( i * ( zoom5 - zoom4 ) / sideCenterFrames ) );

		CreateMatrix( posx, posy, posz, rotx, roty, rotz, scale );
	}

	//create right matrices
	for( int i = 0; i < sideFrames; i++ )
	{
		int rotx, roty, rotz, posx, posy, posz;
		float scale;

		rotx = ( rotX4 + ( right * ( rotX5 - rotX4 ) / sideFrames ) );
		roty = ( angleRight + ( right * angleDeltaRightMtx ) );
		rotz = ( rotZ4 + ( right * ( rotZ5 - rotZ4 ) / BOXES_PER_SIDE ) );

		posx = ( selectedX + rightAdjXpos + ( spacingCenter + ( right * spacingSidesMtx ) ) );
		posy = ( posY4 + ( right * ( posY5 - posY4 ) / sideFrames ) );
		posz = ( posZ4 + ( right * ( posZ5 - posZ4 ) / sideFrames ) );

		scale = ( zoom4 + ( right * ( zoom5 - zoom4 ) / sideFrames ) );
		++right;

		CreateMatrix( posx, posy, posz, rotx, roty, rotz, scale );
	}
}
Ejemplo n.º 18
0
/**
 * Nonlinear finite element solver. (1D version)
 *
 * This does all the same stuff as the linear
 * solver (assembling the global matricies), but utilizes an initial guess to
 * calculate them. It then iterates using Newton's method and updates this
 * guess at each iteration.
 *
 * @param problem The struct containing the problem to solve
 * @param guess The initial guess
 *
 * @returns A matrix with the solution at each node
 */
matrix* NLinSolve1D(struct fe1d *problem, matrix *guess)
{
    matrix *dx; /* How much to update the guess by */
    matrix *newguess;
    //int rows = (2*problem->mesh->nelemx+1)*(2*problem->mesh->nelemy+1);
    int rows = problem->nrows;
    int iter = 0;
    int maxiter = 500;

    if(!guess) {
        guess = CreateMatrix(rows*problem->nvars, 1);
    }

    do {
        iter++;

        if(problem->J)
            DestroyMatrix(problem->J);
        if(problem->F)
            DestroyMatrix(problem->F);

        AssembleJ1D(problem, guess);
        problem->F = CreateMatrix(rows*problem->nvars, 1);
        //AssembleF(problem, guess);
        problem->applybcs(problem);

        //if(!CalcDeterminant(problem->J)) {
        //    iter = -1;
        //   break;
        //}

        /* ToDo: Write this function! */
        CalcResidual1D(problem, guess);
        dx = SolveMatrixEquation(problem->J, problem->R);
        newguess = mtxadd(guess, dx);
        DestroyMatrix(guess);
        guess = newguess;

        /* Quit if we've reached the maximum number of iterations */
        if(iter == maxiter)
            break;

        /* Print the current iteration number to the console. */
        printf("\rIteration %d", iter);
        fflush(stdout); // Flush the output buffer.

    } while(!CheckConverg1D(problem, dx));
    /* ^^ Also quit if the dx variable is small enough. */

    if(iter == -1)
        /* If we've determined the matrix to be singular by calculating the
         * determinant, then output the appropriate error message. */
        printf("\rSingular matrix.\n");
    else if(iter == maxiter)
        /* If the solver didn't find a solution in the specified number of
         * iterations, then say so. */
        printf("\rNonlinear solver failed to converge. "
               "Maximum number of iterations reached.\n");
    else
        /* Print out the number of iterations it took to converge
         * successfully. */
        printf("\rNonlinear solver converged after %d iterations.\n", iter);

    return guess;
}
Ejemplo n.º 19
0
/* 
pass the rgb pixel vector for filtering; the response is returned in the response vector. 
This vector will be initialized by the Gabor API, but MUST disposed of it by the user.
respLen is the address of an int holding the length of the response vector. 
*/
float* ProcessFile( char* file, int*** rgb, int h, int w, float* response, int* respLen )
{
	char 	basename[256];
	char	dirStr[256];
	char*	fileStr;
	int		i, j, len;
	float	norm, max, min;

// extract directory path from filename
	strcpy( dirStr, file );
	fileStr = strrchr( dirStr, '/' );
	if ( fileStr != NULL )
	{
		strcpy( basename, fileStr );				// save part after last slash
		dirStr[fileStr-dirStr+1] = '\0';				// save directory string
		strcat( dirStr, basename );
		strcat( dirStr, "-localGF" );
		basename[strlen(basename)-4] = '\0';			// remove extension
		for ( i = 0; i < strlen( basename ); i++ )		// remove intial slash
			basename[i] = basename[i+1];
		basename[i] = '\0';
	}
	else	// we are in working directory
	{
		strcpy( basename, file );
		basename[strlen(basename)-4] = '\0';			// remove extension
		strcpy( dirStr, basename );
		strcat( dirStr, "-localGF" );
	}

// create img directory in extracted path
	if ( kSaveFilter == 1 )
	{
		mkdir( dirStr, S_IRWXU | S_IRWXG );
		if ( kVerbosity ) cerr << "Created directory: \"" << dirStr << "\"" << endl;
		strcat( dirStr, "/" );
	}

// allocate pixels for rgb matrix
	float** pixels = CreateMatrix( (float)255.0, h, w );

//  convert rgb info to grayscale
	for ( i = 0; i < h; i++ )
	{
		for ( j = 0; j < w; j++ )
		{
			if (rgb[0][i][j] == 0) {
				pixels[i][j] = 1;
			} else {
				pixels[i][j] = 0;
			}
//			pixels[i][j] = sqrt( (float)( rgb[0][i][j]*rgb[0][i][j] +
//										  rgb[1][i][j]*rgb[1][i][j] + 
//										  rgb[2][i][j]*rgb[2][i][j] ) ) / sqrt( 3.0 );
			cout << pixels[i][j];
		}
		cout << endl;
	}

// process grayscale pixels, get gabor filter response length and allocate the return vector
	len = 0;
	strcpy( basename, dirStr );

	cout << endl;
	cout << endl;
	for ( i = 0; i < h; i++ )
	{
		for ( j = 0; j < w; j++ )
		{
			cout << pixels[i][j];
		}
		cout << endl;
	}
	response = ProcessChannel( pixels, h, w, response, &len, basename );
	*respLen = len;

// original float values scaled to [0,1]
	if ( kVerbosity ) cerr << "scaling..." << endl;
	max = min = response[0];
	cerr << endl;
	for ( i = 0; i < len; i++ )
	{
		if( response[i] > max ) max = response[i];
		if( response[i] < min ) min = response[i];
	}
	cerr << endl;
	norm = max - min;
	for ( i = 0; i < len; i++ ) {
		response[i] = 1.0 * ( ( response[i] - min ) / norm );
		cerr << response[i] << " ";
	}
	
// dispose of pixel storage	
	if ( pixels != NULL ) DisposeMatrix( pixels, h );
	
	return response;
}
Ejemplo n.º 20
0
void Renderer::paintGL()
{
	if (!_shaderProgram)
	{
		glClearColor(0.5, 0.25, 0.4, _background.alphaF());
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		return;
	}

	emit reportSignal(MInfo, "Rendering frame");
	glClearColor(_background.redF(), _background.greenF(), _background.blueF(), _background.alphaF());
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// for each object that was split or loaded separately
	QMatrix4x4 modelMatrix = CreateMatrix(_desc[PositionModel]);
	QMatrix4x4 cameraMatrix = CreateMatrix(_desc[PositionCamera]);
	QMatrix4x4 perspectiveMatrix;
	float ratio = size().width() / (float)size().height();
	perspectiveMatrix.setToIdentity();
	perspectiveMatrix.perspective(90, ratio, .5f, 10000.0f);
	QMatrix4x4 mvp = perspectiveMatrix * cameraMatrix * modelMatrix;

	auto test1 = mvp*QVector3D(0, 0, 0);
	auto test2 = mvp*QVector3D(0, 0, 0.5);
	///////////////////////////////////////
	/////////// setting uniform values
	///////////////////////////////////////
	_shaderProgram->setUniformValue("modelToCamera", mvp);
	_shaderProgram->setUniformValue("viewMatrix", cameraMatrix);
	_shaderProgram->setUniformValue("modelMatrix", modelMatrix);
	QVector3D cameraPosition(_desc[PositionCamera]._xPos, _desc[PositionCamera]._yPos, _desc[PositionCamera]._zPos);
	_shaderProgram->setUniformValue("cameraPosition", cameraPosition);
	//const float * df = _mesh.Diffuse();
	//_shaderProgram->setUniformValue("MaterialDiffuseColor", QVector3D(df[0],df[1],df[2]) );
	// set 
	QVector3D lightPos(_desc[PositionLight]._xPos, _desc[PositionLight]._yPos, _desc[PositionLight]._zPos);
	_shaderProgram->setUniformValue("LightPosition_worldspace", lightPos);
	
	///////////////////////////////////////
	/////////// setting arrays
	///////////////////////////////////////

	// take vertex array from opengl context
	_shaderProgram->enableAttributeArray(VERTEX_LOCATION);
	_shaderProgram->enableAttributeArray(NORMAL_LOCATION);
	_shaderProgram->enableAttributeArray(BARYCENTRIC_LOCATION);

	_shaderProgram->setAttributeBuffer(VERTEX_LOCATION, GL_FLOAT, 3*VERTEX_LOCATION * sizeof(GLfloat), 3, 3 * NEntries * sizeof(GLfloat));

	_shaderProgram->setAttributeBuffer(NORMAL_LOCATION, GL_FLOAT, 3*NORMAL_LOCATION * sizeof(GLfloat), 3, 3 * NEntries * sizeof(GLfloat));

	_shaderProgram->setAttributeBuffer(BARYCENTRIC_LOCATION, GL_FLOAT, 3*BARYCENTRIC_LOCATION * sizeof(GLfloat), 3, 3 * NEntries * sizeof(GLfloat));

	_shaderProgram->setUniformValue("wireframe", 0);
	///////////////////////////////////////
	/////////// Actual drawing
	///////////////////////////////////////
	switch (_renderStyle)
	{
	case RenderPoints:
	{
		int size = 0;
		for (int i = 0; i < _renderData.size(); i++)
		{
			size += _renderData[i]._mesh.NVertices();
		}
		glDrawArrays(GL_POINTS, 0, size );
		break;
	}
	case RenderWireframe:
	{
		_shaderProgram->setUniformValue("wireframe", 1);
		//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		glDrawElements(GL_TRIANGLES, _indices, GL_UNSIGNED_INT, 0);
		break;
	}
	default:
	{
		auto test = glGetString(GL_VERSION);
		glDrawElements(GL_TRIANGLES, _indices, GL_UNSIGNED_INT, 0);
		break;
	}
	}

	//for (int i = 0; i < total; ++i) {
	//	//textures[i]->bind();
	//	glDrawArrays(GL_TRIANGLE_STRIP, i * 3, 3);
	//}
}
Ejemplo n.º 21
0
_List*	 _LikelihoodFunction::RecoverAncestralSequencesMarginal (long index, _Matrix & supportValues, _List& expandedSiteMap, bool doLeaves) 
// index:			which part to process
// supportValues:	for each internal node and site stores alphabetDimension values for the 
//				:	relative support of each residue at a given site
//				:   linearized 3D matrix
//				:   1st - node index (same order as flatTree)
//				:   2nd - site index (only unique patterns are stored)
//				:   3rd - the character

// doLeaves		:	compute support values leaves instead of internal nodes

{	
	
	_DataSetFilter* dsf				= (_DataSetFilter*)dataSetFilterList (theDataFilters(index));
	_TheTree		*blockTree		= (_TheTree*)LocateVar(theTrees.lData[index]);
					 
	long			patternCount					= dsf->NumberDistinctSites	(),
					alphabetDimension				= dsf->GetDimension			(),
					unitLength						= dsf->GetUnitLength		(),
					iNodeCount						= blockTree->GetINodeCount	(),
					leafCount						= blockTree->GetLeafCount   (),
					matrixSize						= doLeaves?leafCount:iNodeCount,
					siteCount						= dsf->GetSiteCount			(),
					shiftForTheNode					= patternCount * alphabetDimension;
	
	_Parameter		*siteLikelihoods				= new _Parameter [2*patternCount],
					*siteLikelihoodsSpecState		= new _Parameter [2*patternCount];
	
	_SimpleList		scalersBaseline, 
					scalersSpecState,
					branchValues,
					postToIn;
	
	blockTree->MapPostOrderToInOderTraversal (postToIn, doLeaves == false);
	supportValues.Clear						 ();
	CreateMatrix					         (&supportValues,matrixSize,shiftForTheNode,false,true,false);
	
	ComputeSiteLikelihoodsForABlock			 (index, siteLikelihoods, scalersBaseline); 
													// establish a baseline likelihood for each site
		
	if (doLeaves)
	{
		for								(long currentChar = 0; currentChar < alphabetDimension; currentChar++)
		{
			branchValues.Populate			(patternCount,currentChar,0);
			for (long branchID = 0; branchID < leafCount; branchID ++)
			{
				blockTree->AddBranchToForcedRecomputeList (branchID);
				long mappedBranchID = postToIn.lData[branchID];
				ComputeSiteLikelihoodsForABlock (index, siteLikelihoodsSpecState, scalersSpecState, 
												 branchID+iNodeCount, &branchValues);
				for (long siteID = 0; siteID < patternCount; siteID++)
				{
					long scaleDiff = (scalersSpecState.lData[siteID]-scalersBaseline.lData[siteID]);
					_Parameter ratio = siteLikelihoodsSpecState[siteID]/siteLikelihoods[siteID];
					
					if (scaleDiff > 0)
						ratio *= acquireScalerMultiplier(scaleDiff);
					supportValues.theData[mappedBranchID*shiftForTheNode + siteID*alphabetDimension + currentChar] = ratio;
				}
				blockTree->AddBranchToForcedRecomputeList (branchID);
			}			
		}
	}
	
	else
		for								(long currentChar = 0; currentChar < alphabetDimension-1; currentChar++)
			// the prob for the last char is  (1 - sum (probs other chars))
		{
			branchValues.Populate			(patternCount,currentChar,0);
			for (long branchID = 0; branchID < iNodeCount; branchID ++)
			{
				long mappedBranchID = postToIn.lData[branchID];
				ComputeSiteLikelihoodsForABlock (index, siteLikelihoodsSpecState, scalersSpecState, branchID, &branchValues);
				for (long siteID = 0; siteID < patternCount; siteID++)
				{
					long scaleDiff = (scalersSpecState.lData[siteID]-scalersBaseline.lData[siteID]);
					_Parameter ratio = siteLikelihoodsSpecState[siteID]/siteLikelihoods[siteID];
					if (scaleDiff > 0)
						ratio *= acquireScalerMultiplier(scaleDiff);
					supportValues.theData[mappedBranchID*shiftForTheNode + siteID*alphabetDimension + currentChar] = ratio;
				}
				blockTree->AddBranchToForcedRecomputeList (branchID+leafCount);
			}			
		}
	
	_SimpleList  conversion;
	_AVLListXL	 conversionAVL (&conversion);
	_String		 codeBuffer    (unitLength, false);
	_List	     *result	   = new _List;
	
	for (long k = 0; k < matrixSize; k++)
		result->AppendNewInstance (new _String(siteCount*unitLength,false));
	
	for (long siteID = 0; siteID < patternCount; siteID++)
	{
		_SimpleList*	patternMap = (_SimpleList*) expandedSiteMap (siteID);
				
		for  (long nodeID = 0; nodeID < matrixSize ; nodeID++)
		{
			long			mappedNodeID = postToIn.lData[nodeID];
			_Parameter		max_lik     = 0.,	
							sum			= 0.,
							*scores		= supportValues.theData + shiftForTheNode*mappedNodeID +  siteID*alphabetDimension;
			long			max_idx     = 0;

			for (long charID = 0; charID < alphabetDimension-(!doLeaves); charID ++)
			{
				sum+=scores[charID];
				if (scores[charID] > max_lik)
				{
					max_idx = charID; max_lik = scores[charID];
					
				}
			}
				   
			//if (fabs(scores[alphabetDimension-1]+sum-1.) > 0.1)
			//	WarnError (_String("Bad monkey!") & scores[alphabetDimension-1] & ":" & (1.-sum) );
			
			if (doLeaves)
			{
				sum = 1./sum;
				for (long charID = 0; charID < alphabetDimension; charID ++)
				{
					scores [charID] *= sum;
					/*if (siteID == 16)
						printf ("Site %ld Leaf %ld (%ld) Char %ld = %g\n", siteID, nodeID, mappedNodeID, charID, 
								supportValues.theData[mappedNodeID*shiftForTheNode + siteID*alphabetDimension + charID]);
					 */
		
				}
			}
			else
			{
				scores[alphabetDimension-1] = 1. - sum;

				if (scores[alphabetDimension-1] > max_lik)
					max_idx = alphabetDimension-1; 
			}
						
			dsf->ConvertCodeToLettersBuffered (dsf->CorrectCode(max_idx), unitLength, codeBuffer.sData, &conversionAVL);
			_String  *sequence   = (_String*) (*result)(mappedNodeID);
			
			for (long site = 0; site < patternMap->lLength; site++)
			{
				//if (patternMap->lData[site] == 119)
				//	printf ("%ld\n", 
				//			siteID);
				char* storeHere = sequence->sData + patternMap->lData[site]*unitLength;
				for (long charS = 0; charS < unitLength; charS ++)
					storeHere[charS] = codeBuffer.sData[charS];
			}
			
		}
	}
	delete [] siteLikelihoods; 
	delete [] siteLikelihoodsSpecState;
	return result;
}
Ejemplo n.º 22
0
void LoadAnimation(AnimationData& aAnimation,FbxNode* aNode,FbxAMatrix& aParentOrientation, FbxPose* aPose, FbxAnimLayer* aCurrentAnimLayer, int parentBone)
{
	FbxAMatrix lGlobalPosition = GetGlobalPosition(aNode, static_cast<FbxTime>(0.0f), aPose, &aParentOrientation);
	FbxNodeAttribute* lNodeAttribute = aNode->GetNodeAttribute();
	int boneId = -1;
	if (lNodeAttribute)
	{
		if(lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eSkeleton)
		{
			Bone newBone;
			newBone.myAnimationTime = GetAnimationTime(aNode,aCurrentAnimLayer);
			float oneFrameTime = 1.0f/24.0f;
				
			CU::Matrix44f fixMatrix;
			fixMatrix.myMatrix[0] = -1;
			FbxAMatrix lLocalTransform = aNode->EvaluateLocalTransform();
			newBone.myBaseOrientation = fixMatrix * CreateMatrix(lLocalTransform) * fixMatrix;

			char buffer[32];
			_itoa_s<32>(parentBone,buffer,10);
			newBone.myName = aNode->GetName();	
			newBone.myName += buffer;

			int lNodeIndex = aPose->Find(aNode);
			auto bindPoseMatrix = aPose->GetMatrix(lNodeIndex);

			FbxAMatrix bindMatrix;
			memcpy((double*)bindMatrix, (double*)bindPoseMatrix, sizeof(bindMatrix.mData));

			FbxAMatrix localPosOffset;
				
			memcpy((double*)localPosOffset, (double*)bindPoseMatrix, sizeof(localPosOffset.mData));
			localPosOffset =  localPosOffset * aParentOrientation.Inverse();

			newBone.myBindMatrix = fixMatrix * CreateMatrix(lGlobalPosition.Inverse()) * fixMatrix;

			CU::Matrix44f localStartOffset = CreateMatrix(bindMatrix.Inverse());
			for(float currentFrameTime = 0.0f;currentFrameTime < newBone.myAnimationTime;currentFrameTime+= oneFrameTime)
			{
				KeyFrame keyFrame;
				keyFrame.myTime = currentFrameTime;

				FbxTime time;
				time.SetSecondDouble(currentFrameTime);
				keyFrame.myMatrix = fixMatrix * CreateMatrix(aNode->EvaluateLocalTransform(time)) * fixMatrix;
				newBone.myFrames.push_back(keyFrame);
			}
			FbxAMatrix animationMatrix;

			FbxSkeleton* sekeleton = aNode->GetSkeleton();
			if(sekeleton->IsSkeletonRoot())
			{
				aAnimation.myBindMatrix = CU::Matrix44<float>();
				aAnimation.myRootBone = aAnimation.myBones.size();
			}
			boneId = aAnimation.myBones.size();
			aNode->SetUserDataPtr((void*)boneId);

			if(parentBone != -1)
			{
				aAnimation.myBones[parentBone].myChilds.push_back(boneId);
			}
			newBone.myId = boneId;
			aAnimation.myBones.push_back(newBone);
		}
	}

	const int lChildCount = aNode->GetChildCount();
	for (int lChildIndex = 0; lChildIndex < lChildCount; ++lChildIndex)
	{
		LoadAnimation( aAnimation, aNode->GetChild(lChildIndex), lGlobalPosition , aPose, aCurrentAnimLayer, boneId);
	}
}
Ejemplo n.º 23
0
/**
 * Calculate the equilibrium moisture content. This algorithm takes an initial
 * guess for Xe and then fits a linear equation to
 * \f$\ln\frac{X-X_e}{X_0-X_e}\f$ vs. \f$ t\f$. It then determines the \f$R^2\f$
 * value for that set of coefficients and then iteratively improves the fit
 * using Newton's method.
 * @param initial Row number of the first data point to use
 * @param t Vector of time values [s]
 * @param Xdb Vector of moisture contents [kg/kg db]
 * @param Xe0 Initial guess for equilibrium moisture content [kg/kg db]
 * @returns Equilibrium moisture content [kg/kg db]
 *
 * @see regress
 */
double CalcXeIt(int initial, vector *t, vector *Xdb, double Xe0)
{
    int iter = 0, /* Keep track of the number of iterations */
        i; /* Loop index */
    double Xinit, /* Initial moisture content */
           Xe, /* Current guess for Xe */
           Xep, /* Previous guess for Xe */
           dR, /* First derivative of R^2 with respect to Xe */
           d2R, /* Second derivative of R^2 */
           kF,
           tol = 1e-7, /* How close Xe and Xep need to be before we stop */
           h = 1e-7, /* Used for numerical differentiation */
           m = 2; /* Used to increase the rate of convergence */
    matrix *beta, /* Beta value from regress */
           *beta_ph, /* Same, but calculated at Xe + h */
           *beta_mh, /* Beta at Xe - h */
           *tmp_ph, /* Same as beta_ph, but with an extra zero to make rsquared
                       happy */
           *tmp,
           *tmp_mh,
           *y, /* y values */
           *yph, /* Same as y, but at Xe + h */
           *ymh, /* y at Xe - h */
           *tadj, /* New matrix of t values that starts at the initial row */
           *Xadj; /* Same as tadj, but for Xdb */

    /* Set the initial moisture content */
    Xinit = valV(Xdb, initial);
    /* Set the first value of Xe to Xe0 */
    Xe = Xe0;

    /* Make smaller matricies that contain only the "good" data. */
    tadj = CreateMatrix(len(t) - initial, 1);
    Xadj = CreateMatrix(len(Xdb) - initial, 1);
    for(i=initial; i<len(t); i++) {
        /* In addition to just copying the data, subtract the initial time from
         * each value to make sure that the intercept for the model goes through
         * the origin */
        setval(tadj, valV(t, i)-valV(t, initial), i-initial, 0);
        setval(Xadj, valV(Xdb, i), i-initial, 0);
    }

    /* Actually find Xe */
    do {
        /* Make a y matrix containing ln((Xdb - Xe)/(X0-Xe)) */
        y = CreateMatrix(nRows(Xadj), 1);
        for(i=0; i<nRows(Xadj); i++)
            setval(y, log((val(Xadj, i, 0) - Xe)/(Xinit - Xe)), i, 0);
        /* Calculate the kf parameter */
        beta = regress(y, tadj);

        /* Do the same, but at Xe - h */
        ymh = CreateMatrix(nRows(Xadj), 1);
        for(i=0; i<nRows(Xadj); i++)
            setval(ymh, log((val(Xadj, i, 0) - Xe-h)/(Xinit - Xe-h)), i, 0);
        beta_ph = regress(ymh, tadj);

        /* At Xe + h */
        yph= CreateMatrix(nRows(Xadj), 1);
        for(i=0; i<nRows(Xadj); i++)
            setval(yph, log((val(Xadj, i, 0) - Xe+h)/(Xinit - Xe+h)), i, 0);
        beta_mh = regress(yph, tadj);

        /* Add in a constant parameter of zero to the beta matrix. Do this for
         * each of the beta matricies we've got. */
        tmp_ph = CreateMatrix(2,1);
        setval(tmp_ph, 0, 0, 0);
        setval(tmp_ph, val(beta_ph, 0, 0), 1, 0);

        tmp = CreateMatrix(2,1);
        setval(tmp, 0, 0, 0);
        setval(tmp, val(beta, 0, 0), 1, 0);

        tmp_mh = CreateMatrix(2,1);
        setval(tmp_mh, 0, 0, 0);
        setval(tmp_mh, val(beta_mh, 0, 0), 1, 0);

        /* Calculate f and df */
        dR = (rsquared(tadj, yph, tmp_ph) - rsquared(tadj, ymh, tmp_mh))/(2*h);
        d2R = (rsquared(tadj, yph, tmp_ph) - 2*rsquared(tadj, y, tmp) + rsquared(tadj, ymh, tmp_mh))/(h*h);
        if(d2R == 0) {
            printf("Terminating due to division by zero.\n");
            break;
        }

        /* Calculate the new value of Xe */
        Xep = Xe;
        Xe = Xep + m*dR/d2R;

        kF = val(tmp, 1, 0);

        /* Clean up */
        DestroyMatrix(y);
        DestroyMatrix(yph);
        DestroyMatrix(ymh);
        DestroyMatrix(beta);
        DestroyMatrix(tmp_ph);
        DestroyMatrix(tmp);
        DestroyMatrix(tmp_mh);

        /* Keep track of how many iterations we've gone through */
        iter++;

        /* Print out the current value */
        printf("Xe = %g\r", Xe);

        /* If Xe ever goes negative, admit defeat. */
        if(Xe < 0) {
            printf("Failure to converge after %d iterations.\n", iter);
            return Xe;
        }
    } while( fabs(Xe - Xep) > tol ); /* Check our value */

    /* Print out how many iterations it took to find Xe */
    printf("Solution converged after %d iterations.\n", iter);
    printf("kF = %g\n", kF);

    return Xe;
}
Ejemplo n.º 24
0
int main(int argc, char* argv[]){


	//Debug place holder for input data creating  
	CreateMatrix(50, 10, "v.data");	
	
	
	//debug add input data form here
	CreateMatrix(50, 10, "x.data");
	CreateMatrix(50, 10, "y.data");	
	CreateMatrix(50, 10, "h.data");
	



	myArray MatX;
	MatX.name = "Matrix X coordinate of target";
	MatX.ar = readFile("x.data", &(MatX.row), &(MatX.col));

	myArray MatY;
	MatY.name = "Matrix Y coordinate of target";
	MatY.ar = readFile("y.data", &(MatY.row), &(MatY.col));
	
	myArray MatH;
	MatH.name = "Matrix with relative height coordinate of target";
	MatH.ar = readFile("h.data", &(MatH.row), &(MatH.col));
	
	myArray MatV;
	MatV.name = "Matrix with relative height coordinate of target";
	MatV.ar = readFile("v.data", &(MatV.row), &(MatV.col));

	myArray MatDefec;
	MatDefec.name = "defection to target";
	MatDefec.row = MatY.row;
	MatDefec.col = MatY.col;
	MatDefec.ar = malloc(sizeof(double)*(MatY.row * MatY.col));
	
	myArray MatElev;
	MatElev.name = "Elevation to target";
	MatElev.row = MatY.row;
	MatElev.col = MatY.col;
	MatElev.ar = malloc(sizeof(double)*(MatY.row * MatY.col));

	
	printf("-----------------------------------------------\n");
	
	printf("Oringinal X and Y\n-----------------------------------------------\n");
	printf("XXXX printing original matrixX ");
	printArray(MatX.row, MatX.col, MatX.ar);
	
	printf("YYYYYprinting original matrixY ");
	printArray(MatY.row, MatY.col, MatY.ar);
	
	printf("\n-----------------------------------------------\n");
	printf("-----------------------------------------------\n");
	

	printf("printing original matrix Defelction to target\n");	
	printArray(MatDefec.row, MatDefec.col, MatDefec.ar);
	
	printf("performing the operation\n");
	Defection(&MatX, &MatY, &MatDefec);
 	// Defection2(MatX.ar, MatY.ar, MatDefec.ar, MatX.row * MatY.col);
	
	printf("-----------------------------------------------\n");
	
	printf("printing original matrix Defelction to target\n");	
	printArray(MatDefec.row, MatDefec.col, MatDefec.ar);
	
	printf("-----------------------------------------------\n");
	printf("-----------------------------------------------\n");
	printf("printing elevation to target\n");	
	
	elevation(&MatX, &MatY, &MatH,  &MatV, &MatElev);

	printArray(MatElev.row, MatElev.col, MatElev.ar);
	
	



	//Thou shalt free all that thy malloc
	free(MatDefec.ar);
	free(MatY.ar);
	free(MatX.ar);
	free(MatH.ar);
	free(MatElev.ar);
	free(MatV.ar);
	return 0;
}
Ejemplo n.º 25
0
/**
 * Calculate the equilibrium moisture content. This function determines the best
 * value of Xe to make a plot of \f$\ln\frac{X-X_e}{X_0-X_e}\f$ vs time linear.
 * In order to do this, it fits the data to the equation \f$y = a t + b\f$, where
 * \f$y = \ln(X-X_e)\f$ and \f$b = \ln(X_0-X_e)\f$, and then solves the equation
 * \f$F(X_e) = b - \ln(X_0-X_e) = 0\f$ using Newton's method.
 *
 * This function is made obsolete by CalcXeIt
 *
 * @param t Column matrix containing time during drying [s]
 * @param Xdb Column matrix of moisture content [kg/kg db]
 * @param Xe0 Initial guess for equilibrium moisture content.
 * @returns Equilibrium moisture content [kg/kg db]
 *
 * @see polyfit CalcXeIt
 */
double CalcXe(int initial, matrix *t, matrix *Xdb, double Xe0)
{
    double f, df, /* Function values and derivatives */
           b, /* Fitting parameters. Only the constant matters */
           tol = 1e-10, /* Tolerance for Newton's method */
           Xe = Xe0, /* Set Xe to the initial guess */
           Xep, /* Previous guess */
           X0, /* Initial moisture content */
           r2;
    matrix *beta, /* Matrix of fitting values */
           *y, /* Set equal to ln(X - Xe) */
           *Xadj,
           *tadj;
    int i, /* Loop index */
        iter = 0; /* Current iteration */

    /* Set the initial moisture content */
    X0 = val(Xdb, initial, 0);

    /* Make smaller matricies that contain only the "good" data. */
    tadj = CreateMatrix(nRows(Xdb) - initial, 1);
    Xadj = CreateMatrix(nRows(Xdb) - initial, 1);

    for(i=initial; i<nRows(t); i++) {
        setval(tadj, val(t, i, 0), i-initial, 0);
        setval(Xadj, val(Xdb, i, 0), i-initial, 0);
    }

    /* Actually find Xe */
    do {
        /* Make a y matrix containing ln(Xdb - Xe) */
        y = CreateMatrix(nRows(Xadj), 1);
        for(i=0; i<nRows(Xadj); i++)
            setval(y, log(val(Xadj, i, 0) - Xe), i, 0);

        /* Calculate b */
        beta = polyfit(tadj, y, 1);
        r2 = rsquared(tadj, y, beta);
        b = val(beta, 0, 0);

        /* Calculate f and df */
        f = b - log(X0 - Xe);
        df = 1/(X0 - Xe);

        /* Calculate the new value of Xe */
        Xep = Xe;
        Xe = Xe - f/df;

        /* Clean up */
        DestroyMatrix(y);
        DestroyMatrix(beta);

        /* Keep track of how many iterations we've gone through */
        iter++;

        /* Print out the current value */
        printf("Xe = %g, R^2 = %g\n", Xe, r2);
        if(Xe < 0) {
            printf("Failure to converge after %d iterations.\n", iter);
            return 0;
        }
    } while( fabs(Xe - Xep) > tol ); /* Check our value */

    /* Print out how many iterations it took to find Xe */
    printf("Solution converged after %d iterations.\n", iter);

    return Xe;
}
Ejemplo n.º 26
0
void LoadNodeRecursive(FbxModelData* aModel,AnimationData& aAnimation,FbxNode* aNode,FbxAMatrix& aParentOrientation, FbxPose* aPose, FbxAnimLayer* aCurrentAnimLayer, int parentBone)
{
	parentBone;
	FbxAMatrix lGlobalPosition = GetGlobalPosition(aNode, static_cast<FbxTime>(0.0f), aPose, &aParentOrientation);
	FbxNodeAttribute* lNodeAttribute = aNode->GetNodeAttribute();
		
	if (lNodeAttribute && lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eSkeleton)
	{
		return;
	}

	CU::Matrix44f fixMatrix;
	fixMatrix = CU::Matrix44<float>::CreateReflectionMatrixAboutAxis(CU::Vector3f(1, 0, 0));

	FbxAMatrix lGeometryOffset = GetGeometry(aNode);
	FbxAMatrix lGlobalOffPosition = lGlobalPosition * lGeometryOffset;

	FbxAMatrix lRotationOffset = GetRotaionPivot(aNode);

	aModel->myRotationPivot = fixMatrix * CreateMatrix(lRotationOffset) * fixMatrix;

	aModel->myOrientation = fixMatrix * CreateMatrix(lGlobalOffPosition) * fixMatrix;

	int boneId = -1;
	if (lNodeAttribute)
	{

		if(lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh)
		{
			aModel->myData = new ModelData();
			aModel->myData->myLayout.Init(8);
				
			// Geometry offset.
			// it is not inherited by the children.
			FillData(aModel->myData, aNode, &aAnimation);
		}
		else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eLight)
		{
			FBXLight* newLight = new FBXLight();
			FbxLight* light = aNode->GetLight();
				
			newLight->myIntensity = static_cast<float>(light->Intensity);
			auto color = light->Color.Get();
			newLight->myColor = CU::Vector3<float>(static_cast<float>(color.mData[0]), static_cast<float>(color.mData[1]), static_cast<float>(color.mData[2]));

			auto type = light->LightType.Get();
			if (type == FbxLight::eDirectional)
			{
				newLight->myType = EDirectionalLight;
			}
			else if (type == FbxLight::ePoint)
			{
				newLight->myType = EPointLight;
			}
			else if (type == FbxLight::eSpot)
			{
				newLight->myInnerAngle = static_cast<float>(light->InnerAngle);
				newLight->myOuterAngle = static_cast<float>(light->OuterAngle);
			}
				
			aModel->myLight = newLight;
		}
		else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eCamera)
		{
			aModel->myCamera = new Camera();
			auto orgCamera = aNode->GetCamera();
			aModel->myCamera->myFov = static_cast<float>(orgCamera->FieldOfViewY);
		}
		FbxTimeSpan animationInterval;
			
		if (aNode->GetAnimationInterval(animationInterval))
		{
			aModel->myAnimationCurves = new AnimationCurves();
			aModel->myAnimationCurves->myRotationCurve[0] = aNode->LclRotation.GetCurve(aCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_X);
			aModel->myAnimationCurves->myRotationCurve[1] = aNode->LclRotation.GetCurve(aCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y);
			aModel->myAnimationCurves->myRotationCurve[2] = aNode->LclRotation.GetCurve(aCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z);
			aModel->myAnimationCurves->myRotationCurve[3] = aNode->LclRotation.GetCurve(aCurrentAnimLayer, FBXSDK_CURVENODE_ROTATION);
			aModel->myAnimationCurves->myScalingCurve[0] = aNode->LclScaling.GetCurve(aCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_X);
			aModel->myAnimationCurves->myScalingCurve[1] = aNode->LclScaling.GetCurve(aCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y);
			aModel->myAnimationCurves->myScalingCurve[2] = aNode->LclScaling.GetCurve(aCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z);
			aModel->myAnimationCurves->myTtranslationCurve[0] = aNode->LclTranslation.GetCurve(aCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_X);
			aModel->myAnimationCurves->myTtranslationCurve[1] = aNode->LclTranslation.GetCurve(aCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y);
			aModel->myAnimationCurves->myTtranslationCurve[2] = aNode->LclTranslation.GetCurve(aCurrentAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z);

			int nrOfKeys = 0;
			nrOfKeys;

			float startTime = (float)animationInterval.GetStart().GetSecondDouble();
			float endTime = (float)animationInterval.GetStop().GetSecondDouble();

			aModel->myAnimatedOrientation.Init((int)((endTime - startTime) / (1.0f / 24.0f)));

			for (float currentTime = startTime; currentTime < endTime; currentTime += 1.0f / 24.0f)
			{
				FbxTime time;
				time.SetSecondDouble(currentTime);

				KeyFrame animationFrame;
				animationFrame.myTime = currentTime;
					
				animationFrame.myMatrix = fixMatrix * CreateMatrix(aNode->EvaluateLocalTransform(time)) * fixMatrix;
				aModel->myAnimatedOrientation.Add(animationFrame);
			}
		}
	}

	const int lChildCount = aNode->GetChildCount();
	if(lChildCount > 0)
	{
		aModel->myChilds.Init(lChildCount);
		for (int lChildIndex = 0; lChildIndex < lChildCount; ++lChildIndex)
		{
			aModel->myChilds.Add(new FbxModelData());
			
			LoadNodeRecursive(aModel->myChilds.GetLast(), aAnimation, aNode->GetChild(lChildIndex), lGlobalPosition , aPose, aCurrentAnimLayer, boneId);
		}
	}
}
Ejemplo n.º 27
0
int main()
{	
	char** ppchReactants = NULL;
	int iReactantCounter = 0;
	
	SMatrix* qElementEquations = CreateMatrix( 0, 0 );
	char** ppchElementNames = NULL;
	int iElementCounter = 0;
	
	SMatrix* qMatrixB = CreateMatrix( 0, 0 );
	
	int iChangePoint;
	int iCount = 0;
	
	char* pchInput;
	pchInput = (char*)malloc( sizeof( char ) * 64 );
	memset( pchInput, ' ', 64 );
	printf( "Please enter the reactants one at a time.\nPlease use () to denote subscript.\nH(2)O for example. When finished enter '>'.\n\n" );
	
	int iMult = 1;
	
	while( 1 )
	{
		if( iMult == 1 )
		{
			printf( "Enter reactant:\n" );
		}
		else
		{
			printf( "Enter product:\n" );
		}
		scanf( "%s", pchInput );
		
		if( pchInput[0] == '>' )
		{
			if( iMult == 1 )
			{
				iChangePoint = iCount;
				iMult = -1;
				memset( pchInput, ' ', 64 );
				continue;
			}
			else
			{
				break;
			}
		}
		
		++iCount;
		
		int iLength = 0;
		while( pchInput[iLength] != ' ' )
		{
			++iLength;
		}
		pchInput[iLength-1] = '\0';
		
		++iReactantCounter;
		ppchReactants = (char**)realloc( ppchReactants, sizeof( char* ) * iReactantCounter );
		ppchReactants[iReactantCounter-1] = (char*)malloc( sizeof( char ) * iLength );
		memcpy( ppchReactants[iReactantCounter-1], pchInput, iLength );
		
		int iPass = 0;
		for( int i = 0; i < (iLength-1); ++i )
		{
			int iIncrement = 0;
			if( ( pchInput[i] >= 65 ) && ( pchInput[i] <= 90 ) )
			{
				if( ( pchInput[i+1] >= 97 ) && ( pchInput[i+1] <= 122 ) )
				{
					char* pchName = (char*)malloc( sizeof( char ) * 3 );
					pchName[0] = pchInput[i];
					pchName[1] = pchInput[i+1];
					pchName[2] = '\0';
					iIncrement += 1;
					
					int iAmount = 1;
					
					if( ( pchInput[i+2] == '(' ) && ( ( pchInput[i+3] >= 48 ) && ( pchInput[i+3] <= 57 ) )  )
					{
						iIncrement += 1;
						char* chNumberBuffer = (char*)malloc( sizeof( char ) * 10 );
						for( int j = 3; j <= 10; ++j )
						{
							iIncrement += 1;
							if( pchInput[i+j] == ')' )
							{
								break;
							}
							chNumberBuffer[j-3] = pchInput[i+j];
						}
						iAmount = atoi( chNumberBuffer );
						free( chNumberBuffer );
					}
					
					int iPlace = -1;
					for( int j = 0; j < iElementCounter; ++j )
					{
						if( !strcmp( pchName, ppchElementNames[j] ) )
						{
							iPlace = j;
						}
					}
					
					if( iPlace == -1 )
					{
						++iElementCounter;
						ppchElementNames = (char**)realloc( ppchElementNames, sizeof( char* ) * iElementCounter );
						ppchElementNames[iElementCounter-1] = (char*)malloc( sizeof( char ) * 3 );
						memcpy( ppchElementNames[iElementCounter-1], pchName, 3 );
						
						qElementEquations->m_iRows = iElementCounter;
						qElementEquations->m_ppdMatrix = (double**)realloc( qElementEquations->m_ppdMatrix, sizeof( double * ) * iElementCounter );
						if( !iPass )
						{
							for( int j = 0; j < iElementCounter; ++j )
							{
								qElementEquations->m_iColumns = iReactantCounter;
								qElementEquations->m_ppdMatrix[j] = (double*)realloc( qElementEquations->m_ppdMatrix[j], sizeof( double ) * iReactantCounter );
								qElementEquations->m_ppdMatrix[j][iReactantCounter-1] = 0;
							}
						}
						else
						{
							qElementEquations->m_ppdMatrix[iElementCounter-1] = (double*)malloc( sizeof( double ) * iReactantCounter );
						}
						memset( qElementEquations->m_ppdMatrix[iElementCounter-1], 0, sizeof( double ) * ( iReactantCounter - 1 ) );
						qElementEquations->m_ppdMatrix[iElementCounter-1][iReactantCounter-1] = ( iMult * iAmount );
					}
					else
					{
						if( !iPass )
						{
							for( int j = 0; j < iElementCounter; ++j )
							{
								qElementEquations->m_iColumns = iReactantCounter;
								qElementEquations->m_ppdMatrix[j] = (double*)realloc( qElementEquations->m_ppdMatrix[j], sizeof( double ) * iReactantCounter );
								qElementEquations->m_ppdMatrix[j][iReactantCounter-1] = 0;
							}
						}
						qElementEquations->m_ppdMatrix[iPlace][iReactantCounter-1] = ( iMult * iAmount );
					}
					
					free( pchName );
				}
				else
				{
					char* pchName = (char*)malloc( sizeof( char ) * 2 );
					pchName[0] = pchInput[i];
					pchName[1] = '\0';
					
					int iAmount = 1;
					
					if( ( pchInput[i+1] == '(' ) && ( ( pchInput[i+2] >= 48 ) && ( pchInput[i+2] <= 57 ) ) )
					{
						iIncrement += 1;
						char* chNumberBuffer = (char*)malloc( sizeof( char ) * 10 );
						for( int j = 2; j <= 9; ++j )
						{
							iIncrement += 1;
							if( pchInput[i+j] == ')' )
							{
								break;
							}
							chNumberBuffer[j-2] = pchInput[i+j];
						}
						iAmount = atoi( chNumberBuffer );
						free( chNumberBuffer );
					}
					
					int iPlace = -1;
					for( int j = 0; j < iElementCounter; ++j )
					{
						if( !strcmp( pchName, ppchElementNames[j] ) )
						{
							iPlace = j;
						}
					}
					
					if( iPlace == -1 )
					{
						++iElementCounter;
						ppchElementNames = (char**)realloc( ppchElementNames, sizeof( char* ) * iElementCounter );
						ppchElementNames[iElementCounter-1] = (char*)malloc( sizeof( char ) * 2 );
						memcpy( ppchElementNames[iElementCounter-1],pchName, 2 );
						
						qElementEquations->m_iRows = iElementCounter;
						qElementEquations->m_ppdMatrix = (double**)realloc( qElementEquations->m_ppdMatrix, sizeof( double* ) * iElementCounter );
						if( !iPass )
						{
							for( int j = 0; j < iElementCounter; ++j )
							{
								qElementEquations->m_iColumns = iReactantCounter;
								qElementEquations->m_ppdMatrix[j] = (double*)realloc( qElementEquations->m_ppdMatrix[j], sizeof( double ) * iReactantCounter );
								qElementEquations->m_ppdMatrix[j][iReactantCounter-1] = 0;
							}
						}
						else
						{
							qElementEquations->m_iColumns = iReactantCounter;
							qElementEquations->m_ppdMatrix[iElementCounter-1] = (double*)malloc( sizeof( double ) * iReactantCounter );
						}
						memset( qElementEquations->m_ppdMatrix[iElementCounter-1], 0, sizeof( double ) * ( iReactantCounter - 1 ) );
						qElementEquations->m_ppdMatrix[iElementCounter-1][iReactantCounter-1] = ( iMult * iAmount );
					}
					else
					{
						if( !iPass )
						{
							for( int j = 0; j < iElementCounter; ++j )
							{
								qElementEquations->m_iColumns = iReactantCounter;
								qElementEquations->m_ppdMatrix[j] = (double*)realloc( qElementEquations->m_ppdMatrix[j], sizeof( double ) * iReactantCounter );
								qElementEquations->m_ppdMatrix[j][iReactantCounter-1] = 0;
							}
						}
						qElementEquations->m_ppdMatrix[iPlace][iReactantCounter-1] = ( iMult * iAmount );
					}
					
					free( pchName );
				}
			}
			if( pchInput[i] == '(' )
			{
				int iCompoundLength = 1;
				int iParenCounter = 0;
				
				for( int j = 0; j < 64; ++j )
				{
					++iCompoundLength;
					if( pchInput[i+j] == '(' )
					{
						++iParenCounter;
					}
					
					if( pchInput[i+j] == ')' )
					{
						--iParenCounter;
					}
					
					if( iParenCounter == 0 )
					{
						break;
					}
				}
				
				iIncrement += ( iCompoundLength - 2 );
				
				char* pchName = (char*)malloc( sizeof( char ) * iCompoundLength );
				for( int j = 0; j < ( iCompoundLength ); ++j )
				{
					pchName[j] = pchInput[i+j];
				}
				pchName[iCompoundLength-1] = '\0';
				
				int iAmount = 1;
				
				if( ( pchInput[i+iCompoundLength-1] == '(' ) && ( ( pchInput[i+iCompoundLength] >= 48 ) && ( pchInput[i+iCompoundLength] <= 57 ) ) )
				{
					++iIncrement;
					char* chNumberBuffer = (char*)malloc( sizeof( char ) * 10 );
					for( int j = 0; j <= 9; ++j )
					{
						++iIncrement;
						if( pchInput[i+iCompoundLength+j] == ')' )
						{
							break;
						}
						chNumberBuffer[j] = pchInput[i+iCompoundLength+j];
					}
					iAmount = atoi( chNumberBuffer );
					free( chNumberBuffer );
				}
					
				int iPlace = -1;
				for( int j = 0; j < iElementCounter; ++j )
				{
					if( !strcmp( pchName, ppchElementNames[j] ) )
					{
						iPlace = j;
					}
				}

				if( iPlace == -1 )
				{
					++iElementCounter;
					ppchElementNames = (char**)realloc( ppchElementNames, sizeof( char* ) * iElementCounter );
					ppchElementNames[iElementCounter-1] = (char*)malloc( sizeof( char ) * iCompoundLength );
					memcpy( ppchElementNames[iElementCounter-1], pchName, iCompoundLength );
					
					qElementEquations->m_iRows = iElementCounter;
					qElementEquations->m_ppdMatrix = (double**)realloc( qElementEquations->m_ppdMatrix, sizeof( double* ) * iElementCounter );
					if( !iPass )
					{
						for( int j = 0; j < iElementCounter; ++j )
						{
							qElementEquations->m_iColumns = iReactantCounter;
							qElementEquations->m_ppdMatrix[j] = (double*)realloc( qElementEquations->m_ppdMatrix[j], sizeof( double ) * iReactantCounter );
							qElementEquations->m_ppdMatrix[j][iReactantCounter-1] = 0;
						}
					}
					else
					{
						qElementEquations->m_iColumns = iReactantCounter;
						qElementEquations->m_ppdMatrix[iElementCounter-1] = (double*)malloc( sizeof( double ) * iReactantCounter );
					}
					memset( qElementEquations->m_ppdMatrix[iElementCounter-1], 0, sizeof( double ) * ( iReactantCounter - 1 ) );
					qElementEquations->m_ppdMatrix[iElementCounter-1][iReactantCounter-1] = ( iMult * iAmount );
				}
				else
				{
					if( !iPass )
					{
						for( int j = 0; j < iElementCounter; ++j )
						{
							qElementEquations->m_iColumns = iReactantCounter;
							qElementEquations->m_ppdMatrix[j] = (double*)realloc( qElementEquations->m_ppdMatrix[j], sizeof( double ) * iReactantCounter );
							qElementEquations->m_ppdMatrix[j][iReactantCounter-1] = 0;
						}
					}
					qElementEquations->m_ppdMatrix[iPlace][iReactantCounter-1] = ( iMult * iAmount );
				}
				
				free( pchName );
			}
			i+=iIncrement;
			++iPass;
		}
		memset( pchInput, ' ', 64 );
	}
	
	free( pchInput );
	
	qMatrixB->m_iRows = iElementCounter;
	qMatrixB->m_iColumns = 1;
	qMatrixB->m_ppdMatrix = (double**)malloc( sizeof( double* ) * iElementCounter );
	for( int i = 0; i < iElementCounter; ++i )
	{
		qMatrixB->m_ppdMatrix[i] = (double*)malloc( sizeof( double ) * 1 );
		qMatrixB->m_ppdMatrix[i][0] = fabs( qElementEquations->m_ppdMatrix[i][iReactantCounter-1] );
		qElementEquations->m_ppdMatrix[i] = (double*)realloc( qElementEquations->m_ppdMatrix[i], sizeof( double ) * ( iReactantCounter - 1 ) );
	}
	--iReactantCounter;
	--qElementEquations->m_iColumns;
	
	/*
	printf( "\nElement Equation Matrix:\n" );
	for( int i = 0; i < iElementCounter; ++i )
	{
		printf( "%s [", ppchElementNames[i] );
		for( int j = 0; j < ( iReactantCounter + 1 ); ++j )
		{
			if( j == iReactantCounter )
			{
				printf( " = %6.2f ", qMatrixB->m_ppdMatrix[i][0] );
				continue;
			}
			printf( " %6.2f ", qElementEquations->m_ppdMatrix[i][j] );
		}
		printf( "]\n" );
	}
	*/
	
	SMatrix* qMatrixA = SquareMatrix( qElementEquations );
	
	/*
	printf( "\nMatrix A:\n" );
	for( int i = 0; i < qMatrixA->m_iRows; ++i )
	{
		for( int j = 0; j < qMatrixA->m_iRows; ++j )
		{
			printf( "%6.2f", qMatrixA->m_ppdMatrix[i][j] );
		}
		printf( "\n" );
	}
	*/
	
	/*
	printf( "\nMatrix B:\n" );
	for( int i = 0; i < iElementCounter; ++i )
	{
		printf( "%6.2f\n", qMatrixB->m_ppdMatrix[i][0] ); 
	}
	*/
	
	SMatrix* qMatrixAInverse = GetInverseMatrix( qMatrixA );
	
	/*
	printf( "\nMatrix A Inverse:\n" );
	for( int i = 0; i < qMatrixAInverse->m_iRows; ++i )
	{
		for( int j = 0; j < qMatrixAInverse->m_iRows; ++j )
		{
			printf( "%6.2f", qMatrixAInverse->m_ppdMatrix[i][j] );
		}
		printf( "\n" );
	}
	*/
	
	double dDet = (double)DeterminantOfMatrix( qMatrixA );
	
	SMatrix* qFirstMatrix = MultiplyMatrixes( qMatrixAInverse, qMatrixB );
	
	/*
	printf( "\nMatrix A^-1 * Matrix B:\n" );
	for( int i = 0; i < qFirstMatrix->m_iRows; ++i )
	{
		printf( "%6.2f\n", 	qFirstMatrix->m_ppdMatrix[i][0] );
	}
	*/
	
	/*
	printf( "\nDeterminant of Matrix A: %.0f\n", fDet );
	*/

	MultiplyByConstant( qFirstMatrix, dDet );
	
	int iGCDArray[100];
	for( int i = 0; i < ( iReactantCounter + 1 ); ++i )
	{
		if( i != ( iReactantCounter ) )
		{
			iGCDArray[i] = qFirstMatrix->m_ppdMatrix[i][0];
		}
		else
		{
			iGCDArray[i] = dDet;
		}
	}
	
	int iGCD = GreatestCommonDenominatorArray( iGCDArray, ( iReactantCounter + 1 ) );
	
	/*
	printf( "\n( Matrix A^-1 * Matrix B ) * det( Matrix A ):\n" );
	for( int i = 0; i < iSquare; ++i )
	{
		printf( "%6.2f\n", ppdFirstMatrix[i][0] );
	}
	*/
	
	printf( "\nYour final solution is:\n" );
	int iFirst = 1;
	for( int i = 0; i < iChangePoint; ++i )
	{
		if( iFirst )
		{
			printf( "%.0f", fabs( qFirstMatrix->m_ppdMatrix[i][0] / iGCD ) );
			printf( "%s", ppchReactants[i] );
			iFirst = 0;
		}
		else
		{
			printf( " + " );
			printf( "%.0f", fabs( qFirstMatrix->m_ppdMatrix[i][0] / iGCD ) );
			printf( "%s", ppchReactants[i] );
		}
	}
	printf( " -> " );
	iFirst = 1;
	for( int i = iChangePoint; i < (iReactantCounter+1); ++i )
	{
		if( i != ( iReactantCounter ) )
		{
			if( iFirst )
			{
				printf( "%.0f", fabs( qFirstMatrix->m_ppdMatrix[i][0] / iGCD ) );
				printf( "%s", ppchReactants[i] );
				iFirst = 0;
			}
			else
			{
				printf( " + " );
				printf( "%.0f", fabs( qFirstMatrix->m_ppdMatrix[i][0] / iGCD ) );
				printf( "%s", ppchReactants[i] );
			}
		}
		else
		{
			if( iFirst )
			{
				printf( "%.0f", fabs( dDet / iGCD ) );
				printf( "%s", ppchReactants[i] );
			}
			else
			{
				printf( " + " );
				printf( "%.0f", fabs( dDet / iGCD ) );
				printf( "%s", ppchReactants[i] );
			}
		}
	}
	
	FreeMatrix( qElementEquations );
	FreeMatrix( qMatrixB );
	FreeMatrix( qMatrixA );
	FreeMatrix( qMatrixAInverse );
	FreeMatrix( qFirstMatrix );
	
	// ppchElementNames
	for( int i = 0; i < iElementCounter; ++i )
	{
		free( ppchElementNames[i] );
	}
	free( ppchElementNames );
	
	//Free ppchReactants
	for( int i = 0; i < ( iReactantCounter + 1 ); ++i )
	{
		free( ppchReactants[i] );
	}
	free( ppchReactants );
	
	return 0;
}
Ejemplo n.º 28
0
System *CreateSystem(const int dim, 
		     const int nx, 
		     const int ny, 
		     const double Lx, 
		     const double Ly,
		     const double alpha, 
		     const double SpeedOfSound, 
		     const double rho0,
		     const double AdiabaticConstant,
                     const int NearestNeighbor,
		     const int HowManyNeighbors,
		     const int numReps)
{
  System *a = (System *)malloc(sizeof(System));
  memset(a, 0, sizeof(System));
  a->nx = nx;
  a->ny = ny;
  a->Lx = Lx;
  a->Ly = Ly;
  a->dx = Lx / nx;
  a->dy = Ly / ny;
  a->dim = dim;
//   a->ntotal = nx*ny;
  //  a->nvirt = nvirt;
  a->MaxNumberOfParticles = 0.1995 * 0.1995 * 3.14 / (a->dx*a->dy);
  a->MaxNumberOfParticles += 10;
  a->MaxNumberOfParticles *= 2*a->nx*ny;
  a->alpha = alpha;
  a->NearestNeighbor = NearestNeighbor;
  a->zeta = sqrt(NearestNeighbor/(4*M_PI));
  
  a->Position = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->Velocity = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->Velocity_xsph = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->Velocity_min = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->dvdt = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->av = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->dwdx = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->dwdx_r = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->dummyVelocity = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->dummyAcceleration = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->fluctuation = CreateMatrix(a->MaxNumberOfParticles, dim);
  a->temps = CreateMatrix(a->MaxNumberOfParticles, dim);
  
  posix_memalign(&a->Energy, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->hsml, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->Pressure, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->itype, 16, sizeof(int)*a->MaxNumberOfParticles);
  posix_memalign(&a->rho, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->rho_min, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->drhodt, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->mass, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->i_pair, 16, sizeof(int)*a->MaxNumberOfParticles);
  posix_memalign(&a->j_pair, 16, sizeof(int)*a->MaxNumberOfParticles);
  posix_memalign(&a->rij2, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->w, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->w_r, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->i_inflow, 16, sizeof(int)*a->MaxNumberOfParticles);
  posix_memalign(&a->gradVxx, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->gradVxy, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->gradVyx, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->gradVyy, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->strainRatexx, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->strainRatexy, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->strainRateyx, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->strainRateyy, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->deviatoricxx, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->deviatoricxy, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->deviatoricyx, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->deviatoricyy, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->divV, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->KinVisc, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->numberDensity, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->dummyPressure, 16, sizeof(double)*a->MaxNumberOfParticles);
  posix_memalign(&a->vorticity, 16, sizeof(double)*a->MaxNumberOfParticles);
  
  a->alpha_cubic = 0;
  a->alpha_quintic = 0;
  a->alpha_wendland = 0;
  a->SpeedOfSound = SpeedOfSound;
  a->NumberOfInteractingParticles = 0;
  a->CompressionFactor = (1./AdiabaticConstant) * rho0 * SpeedOfSound * SpeedOfSound;
  a->AdiabaticConstant = AdiabaticConstant;
  a->rho0 = rho0;

  
  // We only need to calculate the neighbors of the particles in the box
  a->HowManyNeighbors = HowManyNeighbors;
  a->Neighbors = CreateMatrixInt(a->ntotal, a->HowManyNeighbors);
  a->DistanceNeighbors = CreateMatrixInt(a->ntotal, HowManyNeighbors);
  a->numReps = numReps;
  a->ri = (rep*)calloc( CPAD(a->numReps), sizeof(*a->ri) ); //data struct for RBC
  
  initMat( &a->q, a->ntotal, 2);
  a->q.mat=a->Position[0];
  return a;
}
Ejemplo n.º 29
0
/**
**  Find free building place. (flood fill version)
**
**  @param worker  Worker to build building.
**  @param type    Type of building.
**  @param ox      Original X position to try building
**  @param oy      Original Y position to try building
**  @param dpos    Pointer for position returned.
**
**  @return        True if place found, false if no found.
*/
static int AiFindBuildingPlace2(const CUnit &worker, const CUnitType &type, int ox, int oy, Vec2i *dpos)
{
    const Vec2i offset[] = {{0, -1}, {-1, 0}, {1, 0}, {0, 1}, {-1, -1}, {1, -1}, {-1, 1}, {1, 1}};
    Vec2i *points;
    int size;
    Vec2i pos = {ox, oy};
    Vec2i rpos;
    int mask;
    int wp;
    int rp;
    int ep;
    unsigned char *m;
    Vec2i backupPos = {-1, -1};
    bool backupok;

    //
    // Look if we can build at current place.
    //
    if (CanBuildUnitType(&worker, type, pos, 1) &&
            !AiEnemyUnitsInDistance(worker.Player, NULL, pos, 8)) {
        if (AiCheckSurrounding(worker, type, pos.x, pos.y, backupok)) {
            *dpos = pos;
            return 1;
        } else if (backupok) {
            backupPos = pos;
        }
    }

    size = Map.Info.MapWidth * Map.Info.MapHeight / 4;
    points = new Vec2i[size];

    //
    //  Make movement matrix.
    //
    unsigned char *matrix = CreateMatrix();
    const int w = Map.Info.MapWidth + 2;

    mask = worker.Type->MovementMask;
    // Ignore all possible mobile units.
    mask &= ~(MapFieldLandUnit | MapFieldAirUnit | MapFieldSeaUnit);

    points[0] = pos;
    // also use the bottom right
    if ((type.TileWidth > 1 || type.TileHeight > 1) &&
            pos.x + type.TileWidth - 1 < Map.Info.MapWidth &&
            pos.y + type.TileHeight - 1 < Map.Info.MapHeight) {
        points[1].x = pos.x + type.TileWidth - 1;
        points[1].y = pos.y + type.TileHeight - 1;
        ep = wp = 2; // start with two points
    } else {
        ep = wp = 1; // start with one point
    }
    matrix += w + w + 2;
    rp = 0;
    matrix[pos.x + pos.y * w] = 1; // mark start point

    //
    // Pop a point from stack, push all neighbours which could be entered.
    //
    for (;;) {
        while (rp != ep) {
            rpos = points[rp];
            for (int i = 0; i < 8; ++i) { // mark all neighbors
                pos = rpos + offset[i];
                m = matrix + pos.x + pos.y * w;
                if (*m) { // already checked
                    continue;
                }

                //
                // Look if we can build here and no enemies nearby.
                //
                if (CanBuildUnitType(&worker, type, pos, 1) &&
                        !AiEnemyUnitsInDistance(worker.Player, NULL, pos, 8)) {
                    if (AiCheckSurrounding(worker, type, pos.x, pos.y, backupok)) {
                        *dpos = pos;
                        delete[] points;
                        return 1;
                    } else if (backupok && backupPos.x == -1) {
                        backupPos = pos;
                    }
                }

                if (CanMoveToMask(pos, mask)) { // reachable
                    *m = 1;
                    points[wp] = pos; // push the point
                    if (++wp >= size) { // round about
                        wp = 0;
                    }
                } else { // unreachable
                    *m = 99;
                }
            }

            if (++rp >= size) { // round about
                rp = 0;
            }
        }

        //
        // Continue with next frame.
        //
        if (rp == wp) { // unreachable, no more points available
            break;
        }
        ep = wp;
    }
    delete[] points;

    if (backupPos.x != -1) {
        *dpos = backupPos;
        return 1;
    }
    return 0;
}
Ejemplo n.º 30
0
/// Sets new column and row sizes. Only to be called when doing initial parse or from the render-thread!
void UIMatrix::SetSize(Vector2i newSize)
{
	columns = newSize[0];
	rows = newSize[1];
	CreateMatrix();
}