コード例 #1
0
ファイル: test_files.c プロジェクト: balhar-jakub/LLS
void testSaveMatrix(void) {
    FILE *matrixFile = fopen("test/matrix_to_save","wb");
    if(matrixFile == NULL) {
        return;
    } 
    
    size_t columns = 3;
    size_t rows = 3;
    floattype **matrix = AllocMatrix(rows, columns);
    floattype **expected = AllocMatrix(rows, columns);
    
    CU_ASSERT(CODE_OK == saveMatrix(matrix, matrixFile, rows, columns));
    FreeMatrix(matrix, rows);
    fclose(matrixFile);
    
    Matrix *matrixLoaded;
    FILE *loadFile = fopen("test/matrix_to_save","rb");
    matrixLoaded = loadMatrix(loadFile);
    fclose(loadFile);
    
    CU_ASSERT(NULL != matrixLoaded);
    if(NULL == matrixLoaded) {
        FreeMatrix(expected, rows);
        return;
    }
    
    CU_ASSERT(3 == matrixLoaded->header.colcount);
    CU_ASSERT(3 == matrixLoaded->header.rowcount);
    
    assertMatricesAreSame(expected, matrixLoaded->matrix, &(matrixLoaded->header));
    
    FreeMatrix(matrixLoaded->matrix, matrixLoaded->header.rowcount);
    free(matrixLoaded);
    FreeMatrix(expected, rows);
}
コード例 #2
0
ファイル: DEC_FIXP_LDPC_BIN.cpp プロジェクト: brleinad/tesi
void DEC_FIXP_LDPC_BIN::Free()
{
    FreeMatrix(ptChkMess);  // extrinsic messages from check to variable nodes
    FreeMatrix(ptVarMess);  // extrinsic messages from variable to check nodes
    FreeArray(ptPostInfo);  // store the pseudo-posterior log-likelihood ratios (LLR)
    FreePointer(ptFixp);    // pointer to fixed-point arithmetic class

}   // end of 'Free' method
コード例 #3
0
ファイル: rand.c プロジェクト: nickbloom/MNP
void rWish(                  
	   double **Sample,        /* The matrix with to hold the sample */
	   double **S,             /* The parameter */
	   int df,                 /* the degrees of freedom */
	   int size)               /* The dimension */
{
  int i,j,k;
  double *V = doubleArray(size);
  double **B = doubleMatrix(size, size);
  double **C = doubleMatrix(size, size);
  double **N = doubleMatrix(size, size);
  double **mtemp = doubleMatrix(size, size);
  
  for(i=0;i<size;i++) {
    V[i]=rchisq((double) df-i-1);
    B[i][i]=V[i];
    for(j=(i+1);j<size;j++)
      N[i][j]=norm_rand();
  }

  for(i=0;i<size;i++) {
    for(j=i;j<size;j++) {
      Sample[i][j]=0;
      Sample[j][i]=0;
      mtemp[i][j]=0;
      mtemp[j][i]=0;
      if(i==j) {
	if(i>0)
	  for(k=0;k<j;k++)
	    B[j][j]+=N[k][j]*N[k][j];
      }
      else { 
	B[i][j]=N[i][j]*sqrt(V[i]);
	if(i>0)
	  for(k=0;k<i;k++)
	    B[i][j]+=N[k][i]*N[k][j];
      }
      B[j][i]=B[i][j];
    }
  }
  
  dcholdc(S, size, C);
  for(i=0;i<size;i++)
    for(j=0;j<size;j++)
      for(k=0;k<size;k++)
	mtemp[i][j]+=C[i][k]*B[k][j];
  for(i=0;i<size;i++)
    for(j=0;j<size;j++)
      for(k=0;k<size;k++)
	Sample[i][j]+=mtemp[i][k]*C[j][k];

  free(V);
  FreeMatrix(B, size);
  FreeMatrix(C, size);
  FreeMatrix(N, size);
  FreeMatrix(mtemp, size);
}
コード例 #4
0
ファイル: ParkingLot.c プロジェクト: jsmvalente/projectoaed
ParkingLot * InitParkingLot( FILE * mapconfig, int col, int row, int floors, int accesses )
{
    char *** matrix;
    int *vertices, *ramps;
    ParkingLot * parkinglot;

    vertices = (int*)malloc(sizeof(int));
    VerifyMalloc( (Item) vertices );

    ramps = (int*)malloc(sizeof(int));
    VerifyMalloc( (Item) ramps );

    parkinglot = (ParkingLot*) malloc( sizeof(ParkingLot) );
    VerifyMalloc((Item) parkinglot);
    parkinglot->freespots = 0;
    matrix = MatrixInit(vertices, ramps, mapconfig, col, row, floors); /*Creates string cointaining the map - its a 3d string */
    parkinglot->graphdecoder = GraphDecoderInit(matrix, col, row, floors, *vertices, &(parkinglot->freespots) ); /*Creates array cointaining the Decoder for the graph positions*/
    parkinglot->g = GraphInit(*vertices, matrix, parkinglot->graphdecoder, col, row);
    parkinglot->accesseshead = InitAccesses(accesses, parkinglot->graphdecoder, *vertices);
    parkinglot->parkedcarshead = ListInit();
    parkinglot->queuehead = ListInit();

    /**PrintGraph(GetGraph(parkinglot), *vertices); */ /*prints the graph in the parkinglot */
    FreeMatrix(matrix, col, row);
    free(vertices);
    free(ramps);

    return (parkinglot);
}
コード例 #5
0
ファイル: rand.c プロジェクト: nickbloom/MNP
/* Sample from the MVN dist */
void rMVN(                      
	  double *Sample,         /* Vector for the sample */
	  double *mean,           /* The vector of means */
	  double **Var,           /* The matrix Variance */
	  int size)               /* The dimension */
{
  int j,k;
  double **Model = doubleMatrix(size+1, size+1);
  double cond_mean;
    
  /* draw from mult. normal using SWP */
  for(j=1;j<=size;j++){       
    for(k=1;k<=size;k++)
      Model[j][k]=Var[j-1][k-1];
    Model[0][j]=mean[j-1];
    Model[j][0]=mean[j-1];
  }
  Model[0][0]=-1;
  Sample[0]=(double)norm_rand()*sqrt(Model[1][1])+Model[0][1];
  for(j=2;j<=size;j++){
    SWP(Model,j-1,size+1);
    cond_mean=Model[j][0];
    for(k=1;k<j;k++) cond_mean+=Sample[k-1]*Model[j][k];
    Sample[j-1]=(double)norm_rand()*sqrt(Model[j][j])+cond_mean;
  }
  
  FreeMatrix(Model,size+1);
}
コード例 #6
0
ファイル: CPlaceableSA.cpp プロジェクト: qaisjp/green-candy
/*=========================================================
    CPlaceableSAInterface::destructor

    Binary offsets:
        (1.0 US and 1.0 EU): 0x0054F490
=========================================================*/
CPlaceableSAInterface::~CPlaceableSAInterface( void )
{
    FreeMatrix();

    // I do not know what this is. Entity count?
    (*(unsigned int*)0x00B74238)--;

    //m_matrix = &transformIdentity;
}
コード例 #7
0
ファイル: mdd_function.c プロジェクト: parb220/dsmh_package
TElliptical* CreateEllipticalFromPosterior_Gaussian(TVector R, int dim, TVector center, TMatrix scale)
{
  TElliptical *elliptical=(TElliptical*)NULL;
  TMatrix variance;
  if (dim > 0)
    {
      elliptical=CreateElliptical_Gaussian(dim,center,variance=ProductTransposeMM((TMatrix)NULL,scale,scale));
      FreeMatrix(variance);
    }
  return elliptical;
}
コード例 #8
0
ファイル: mchem.c プロジェクト: rfinkelnburg/MetPhoMod
Matrix AdjustJacob(Matrix m, int n)
/* Kreiert eine Matrix oder vergroessert sie falls noetig auf die Groesse n*/
{
  static int size;
  if (m)  {
    if (n > size)  FreeMatrix(m);
    else	   return (m);
  }
  size = n;
  return (AllocateMatrix(n, n));
}
コード例 #9
0
float
CRebuildGraph::compareMatrix(gsl_matrix* matrixA, gsl_matrix*matrixB){

    
    float delta;
    gsl_vector *work ,*s;
    
    
    if (matrixA->size1 != matrixB->size1)
        throw runtime_error(" size 1 and size 2 are different");
    
    gsl_matrix *U1, *U2,*V1,*V2;
    
    InitMatrix((int)matrixA->size1,&work,&s,&U1,&U2,&V1,&V2);

    gsl_matrix_memcpy (U1, matrixA);
    //gsl_linalg_SV_decomp (gsl_matrix * A, gsl_matrix * V, gsl_vector * S, gsl_vector * work)
    //La matriu A es substitueix per U a la sortida
    gsl_linalg_SV_decomp(U1,V1,s,work);

    gsl_matrix_memcpy (U2, matrixB);
    gsl_linalg_SV_decomp(U2,V2,s,work);

    //F = U1 VS2 V1^T = U1 U2^T A2 V2 V1^T
    gsl_matrix *F=gsl_matrix_alloc(matrixA->size1,matrixA->size1);
    gsl_matrix_transpose(U2);
    multiplica(F,U1,U2);
    multiplica(F,F,matrixB);
    multiplica(F,F,V2);
    gsl_matrix_transpose(V1);
    multiplica(F,F,V1);

    //F ja esta calculada. Calculem la norma.
    delta=0;
    for(int i=0; i<matrixA->size1; i++){
    for(int j=0; j<matrixA->size1; j++){
        delta+=pow(gsl_matrix_get(matrixA,i,j)-gsl_matrix_get(F,i,j),2);
    }
    }
    delta=std::pow(delta,0.5f);
    delta/=matrixA->size1;

    printingCompareMatrixResults(delta,F,matrixA);
    FreeMatrix(&work,
               &s,
              &U1,
               &U2,
               &V1,
               &V2,
               &F );

    return delta;
}
コード例 #10
0
ファイル: matgen.cpp プロジェクト: chrislupo/matgen
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv) {
  Matrix  M;
  Matrix  N;
  char *str;

  if(argc == 5) {
    // Allocate and initialize the matrices
    srand(time(0));
    M  = AllocateMatrix(strtol(argv[1],&str,10), strtol(argv[2],&str,10), 1);
    N  = AllocateMatrix(strtol(argv[3],&str,10), strtol(argv[4],&str,10), 1);
    WriteFile(M, (char *)"m1.in");
    WriteFile(N, (char *)"m2.in");
    FreeMatrix(&M);
    FreeMatrix(&N);
    return 0;
  }
  else {
    printf("Incorrect number of arguments\n");
    exit(1);
  }
  return 0;
}
コード例 #11
0
/* 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);
      }
   }
}
コード例 #12
0
ファイル: plp.cpp プロジェクト: alongwithyou/PhnRec
void PLPCoefs::Free()
{
   if(mpEnergies != 0)
   {
      delete [] mpEnergies;
      mpEnergies = 0;   
      FreeMatrix(mppIDFTBases, mLPCOrder + 1);
      delete [] mpAutocorrCoefs;
      delete [] mpLPC;
      delete [] mpTmp;
      delete [] mpCepst; 
      delete [] mpLifteringWindow;    
   }

   MelBanks::Free();

}
コード例 #13
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;
}
コード例 #14
0
/* Function: GetCoFactorMatrix
 * -----------------
 *		Description: Returns the cofactor matrix of a square matrix
 *
 *		Arguments:
 *			Arg1: (SMatrix) Matrix with which to find cofactor matrix
 *
 *		Returns: (SMatrix) Cofactor matrix
 *
 *		Author: Jacob Hull
 */
SMatrix* GetCoFactorMatrix( SMatrix* qMatrix )
{
	SMatrix* qReturnMatrix;
	if( qMatrix->m_iRows != qMatrix->m_iColumns )
	{
		return NULL;
	}
	
	qReturnMatrix = CreateMatrix( qMatrix->m_iRows, qMatrix->m_iColumns );
	
	SMatrix* qSubMatrix = CreateMatrix( qMatrix->m_iRows - 1, qMatrix->m_iColumns - 1 );
	
	for( int i = 0; i < qMatrix->m_iRows; ++i )
	{	
		for( int j = 0; j < qMatrix->m_iRows; ++j )
		{
			int iXSpace = 0;
			
			for( int x = 0; x < ( qMatrix->m_iRows - 1 ); ++x )
			{
				if( i == x )
				{
					iXSpace = 1;
				}
				
				int iYSpace = 0;
				for( int y = 0; y < ( qMatrix->m_iRows - 1 ); ++y )
				{	
					if( j == y )
					{
						iYSpace = 1;
					}
					qSubMatrix->m_ppdMatrix[x][y] = qMatrix->m_ppdMatrix[iXSpace+x][iYSpace+y];
				}
			}
			int iMult = ( pow( -1, i ) / pow( -1, j ) );
			qReturnMatrix->m_ppdMatrix[i][j] = iMult * DeterminantOfMatrix( qSubMatrix );
		}
	}
	
	FreeMatrix( qSubMatrix );
	
	return qReturnMatrix;
}
コード例 #15
0
ファイル: Matrix.cpp プロジェクト: kulhanek/scimafic
void CMatrix::CreateMatrix(long unsigned int rows,long unsigned int columns)
{
    if( (rows < 0) || (columns < 0) ){
        INVALID_ARGUMENT("(rows < 0) || (columns < 0)");
    }

    if(Rows > 0) {
        FreeMatrix();
    }
    if( (rows == 0) || (columns == 0) ) return;

    RowVectors = new CVector[rows];

    for(long unsigned int i=0; i < rows; i++ ) {
        RowVectors[i].CreateVector(columns);
    }

    Rows = rows;
    Columns = columns;
}
コード例 #16
0
ファイル: mdd_function.c プロジェクト: parb220/dsmh_package
TElliptical* CreateEllipticalFromPosterior_TruncatedGaussian(TVector R, int dim, TVector center, TMatrix scale, PRECISION p_lo, PRECISION p_hi)
{
  TElliptical *elliptical=(TElliptical*)NULL;
  PRECISION a, b;
  TMatrix V;
  int i;

  if (dim > 0)
    {
      SortVectorAscending(R,R);

      i=floor(p_lo*(PRECISION)(DimV(R)-1));
      a=(i < DimV(R)-1) ? 0.5*(ElementV(R,i+1) + ElementV(R,i)) : ElementV(R,i);
      i=floor(p_hi*(PRECISION)(DimV(R)-1));
      b=(i < DimV(R)-1) ? 0.5*(ElementV(R,i+1) + ElementV(R,i)) : ElementV(R,i);

      V=ProductTransposeMM((TMatrix)NULL,scale,scale);
      elliptical=CreateElliptical_TruncatedGaussian(dim,center,V,a,b);
      FreeMatrix(V);
    }

  return elliptical;
}
コード例 #17
0
ファイル: DosageCalculator.cpp プロジェクト: amarawi/gotcloud
DosageCalculator::~DosageCalculator()
   {
   switch (wordSize)
      {
      case 1 :
         if (cDosage != NULL) FreeMatrix(cDosage, genotypes);
         if (cTwo != NULL) FreeMatrix(cTwo, genotypes);
         break;
      case 2 :
         if (sDosage != NULL) FreeMatrix(sDosage, genotypes);
         if (sTwo != NULL) FreeMatrix(sTwo, genotypes);
         break;
      case 4 :
         if (iDosage != NULL) FreeMatrix(iDosage, genotypes);
         if (iTwo != NULL) FreeMatrix(iTwo, genotypes);
         break;
      }
   }
コード例 #18
0
ファイル: vector.c プロジェクト: SensitiveQuestions/list
void Free3DMatrix(double ***Matrix, int index, int row) {
  int i;
  for (i = 0; i < index; i++)
    FreeMatrix(Matrix[i], row);
  free(Matrix);
}
コード例 #19
0
ファイル: elm.c プロジェクト: linuxfl/ELM_C_S
/**
     * Construct an ELM
     * @param
     * elm_type              - 0 for regression; 1 for (both binary and multi-classes) classification
     */
void ELMTrain(int elm_type)
{
	double starttime,endtime;
	double TrainingAccuracy;
	int i,j,k = 0;
	float **input,**weight,*biase,**tranpI,**tempH,**H;
	float **PIMatrix;
	float **train_set;
	float **T,**Y;
	float **out;
	
	train_set = (float **)calloc(DATASET,sizeof(float *));
	tranpI = (float **)calloc(INPUT_NEURONS,sizeof(float *));
	input = (float **)calloc(DATASET,sizeof(float *));        		/*datasize * INPUT_NEURONS*/
	weight = (float **)calloc(HIDDEN_NEURONS,sizeof(float *));		/*HIDDEN_NEURONS * INPUT_NEURONS*/
	biase = (float *)calloc(HIDDEN_NEURONS,sizeof(float)); 			/*HIDDEN_NEURONS*/
	tempH = (float **)calloc(HIDDEN_NEURONS,sizeof(float *)); 		/*HIDDEN_NEURONS * datasize*/
	PIMatrix = (float **)calloc(HIDDEN_NEURONS,sizeof(float *));
	H = (float **)calloc(DATASET,sizeof(float *));
	T = (float **)calloc(DATASET,sizeof(float *));
	Y = (float **)calloc(DATASET,sizeof(float *));
	out = (float **)calloc(HIDDEN_NEURONS,sizeof(float *));
	
	for(i=0;i<DATASET;i++){
		train_set[i] = (float *)calloc(NUMROWS,sizeof(float));
		input[i] = (float *)calloc(INPUT_NEURONS,sizeof(float));
		H[i] = (float *)calloc(HIDDEN_NEURONS,sizeof(float));
	}
	for(i=0;i<DATASET;i++)
	{
		T[i] = (float *)calloc(OUTPUT_NEURONS,sizeof(float));
		Y[i] = (float *)calloc(OUTPUT_NEURONS,sizeof(float));
	}
	for(i=0;i<INPUT_NEURONS;i++)
		tranpI[i] = (float *)calloc(DATASET,sizeof(float));
	
	for(i=0;i<HIDDEN_NEURONS;i++)
	{
		weight[i] = (float *)calloc(INPUT_NEURONS,sizeof(float));
		tempH[i] = (float *)calloc(DATASET,sizeof(float));
		out[i] = (float *)calloc(OUTPUT_NEURONS,sizeof(float));
		PIMatrix[i] = (float *)calloc(DATASET,sizeof(float));
	}
	
	printf("begin to random weight and biase...\n");
	/*得到随机的偏置和权重*/
	RandomWeight(weight,HIDDEN_NEURONS,INPUT_NEURONS);
	RandomBiase(biase,HIDDEN_NEURONS);
	SaveMatrix(weight,"./result/weight",HIDDEN_NEURONS,INPUT_NEURONS);
	SaveMatrix_s(biase,"./result/biase",1,HIDDEN_NEURONS);
	/*加载数据集到内存*/
	printf("begin to load input from the file...\n");
	if(LoadMatrix(train_set,"./sample/frieman",DATASET,NUMROWS) == 0){
		printf("load input file error!!!\n");	
		return;
	}
	
	/*将数据集划分成输入和输出*/
	if(elm_type == 0){ 	//regression
		/*
			the first column is the output of the dataset
		*/
		for(i = 0;i < DATASET ;i++)
		{
			T[k++][0] = train_set[i][0];
			for(j = 1;j <= INPUT_NEURONS;j++)
			{
				input[i][j-1] = train_set[i][j];
			}
		}
	}else{				//classification
		/*
			the last column is the lable of class of the dataset
		*/
		InitMatrix(T,DATASET,OUTPUT_NEURONS,-1);
		for(i = 0;i < DATASET ;i++)
		{
			//get the last column
			T[k++][0] = train_set[i][0] - 1;//class label starts from 0,so minus one
			for(j = 1;j <= INPUT_NEURONS;j++)
			{
				input[i][j-1] = train_set[i][j];
			}
		}
		for(i = 0;i < DATASET ;i++)
		{
			for(j = 0;j < OUTPUT_NEURONS;j++)
			{
				k =  T[i][0];
				if(k < OUTPUT_NEURONS && k >= 0){
					T[i][k] = 1;
				}
				if(k != 0){
					T[i][0] = -1;
				}
			}
		}
	}
	/*ELM*/
	printf("begin to compute...\n");
	starttime = omp_get_wtime();	
	TranspositionMatrix(input,tranpI,DATASET,INPUT_NEURONS);
	printf("begin to compute step 1...\n");
	MultiplyMatrix(weight,HIDDEN_NEURONS,INPUT_NEURONS, tranpI,INPUT_NEURONS,DATASET,tempH);
	printf("begin to compute setp 2...\n");
	AddMatrix_bais(tempH,biase,HIDDEN_NEURONS,DATASET);
	printf("begin to compute step 3...\n");
	SigmoidHandle(tempH,HIDDEN_NEURONS,DATASET);
	printf("begin to compute step 4...\n");
	TranspositionMatrix(tempH,H,HIDDEN_NEURONS,DATASET);
	PseudoInverseMatrix(H,DATASET,HIDDEN_NEURONS,PIMatrix);
	MultiplyMatrix(PIMatrix,HIDDEN_NEURONS,DATASET,T,DATASET,OUTPUT_NEURONS,out);

	//SaveMatrix(H,"./result/H",DATASET,HIDDEN_NEURONS);
	//SaveMatrix(PIMatrix,"./result/PIMatrix",HIDDEN_NEURONS,DATASET);
	printf("begin to compute step 5...\n");
	endtime = omp_get_wtime();
	//保存输出权值
	SaveMatrix(out,"./result/result",HIDDEN_NEURONS,OUTPUT_NEURONS);
	MultiplyMatrix(H,DATASET,HIDDEN_NEURONS,out,HIDDEN_NEURONS,OUTPUT_NEURONS,Y);
	printf("use time :%f\n",endtime - starttime);
	printf("train complete...\n");

	if(elm_type == 0){
	//检测准确率
		double MSE = 0;
		for(i = 0;i< DATASET;i++)
		{
			MSE += (Y[i][0] - T[i][0])*(Y[i][0] - T[i][0]);
		}
		TrainingAccuracy = sqrt(MSE/DATASET);
		printf("Regression/trainning accuracy :%f\n",TrainingAccuracy);
	}else{
		float MissClassificationRate_Training=0;
		double maxtag1,maxtag2;
		int tag1 = 0,tag2 = 0;
		for (i = 0; i < DATASET; i++) {
				maxtag1 = Y[i][0];
				tag1 = 0;
				maxtag2 = T[i][0];
				tag2 = 0;
		    	for (j = 1; j < OUTPUT_NEURONS; j++) {
					if(Y[i][j] > maxtag1){
						maxtag1 = Y[i][j];
						tag1 = j;
					}
					if(T[i][j] > maxtag2){
						maxtag2 = T[i][j];
						tag2 = j;
					}
				}
		    	if(tag1 != tag2)
		    		MissClassificationRate_Training ++;
			}
		    TrainingAccuracy = 1 - MissClassificationRate_Training*1.0f/DATASET;
			printf("Classification/training accuracy :%f\n",TrainingAccuracy);
	}
	FreeMatrix(train_set,DATASET);
	FreeMatrix(tranpI,INPUT_NEURONS);
	FreeMatrix(input,DATASET);
	FreeMatrix(weight,HIDDEN_NEURONS);
	free(biase);
	FreeMatrix(tempH,HIDDEN_NEURONS);
	FreeMatrix(PIMatrix,HIDDEN_NEURONS);
	FreeMatrix(H,DATASET);
	FreeMatrix(T,DATASET);
	FreeMatrix(Y,DATASET);
	FreeMatrix(out,HIDDEN_NEURONS);
}
コード例 #20
0
ファイル: main.cpp プロジェクト: ljaljushkin/NumMethods
int main(int argc, char *argv[]) {
    FILE *input_file, *output_file, *time_file;
    if (argc < 4) {
        fprintf(stderr, "Invalid input parameters\n");
        fprintf(stderr, "Usage: %s inputfile outputfile timefile \n", argv[0]);
        exit(1);
    }
    else {
        input_file = fopen(argv[1], "r");
        output_file = fopen(argv[2], "w");
        time_file = fopen(argv[3], "w");
        if (!input_file || !output_file || !time_file)
            exit(1);
    }

    MM_typecode matcode;
    if (mm_read_banner(input_file, &matcode) != 0) {
        printf("Could not process Matrix Market banner.\n");
        exit(1);
    }

    if (!mm_is_matrix(matcode) || !mm_is_real(matcode) || !mm_is_coordinate(matcode)) {
        printf("Sorry, this application does not support ");
        printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode));
        exit(1);
    }

    mtxMatrix inputMatrix, fullMatrix, LMatrix, UMatrix, UMatrixTranspose, MMatrix;
    ReadMatrix(inputMatrix, input_file);

    Timer timer;

    getRowIndex(&inputMatrix, inputMatrix.RowIndex);
    inputMatrix.RowIndex[inputMatrix.N] = inputMatrix.NZ;

	int diagNum = 0;
	for (int i = 0; i < inputMatrix.N; i++) {
        for (int j = inputMatrix.RowIndex[i]; j < inputMatrix.RowIndex[i + 1]; j++) {
            if (i == inputMatrix.Col[j]) diagNum++;
        }
    }

    if (mm_is_symmetric(matcode)) {
        InitializeMatrix(inputMatrix.N, 2 * inputMatrix.NZ - diagNum, fullMatrix);
        TriangleToFull(&inputMatrix, &fullMatrix);
        FreeMatrix(inputMatrix);
    }
    else {
        fullMatrix = inputMatrix;
    }

    int *diag = new int[fullMatrix.N];

    for (int i = 0; i < fullMatrix.N; i++) {
        for (int j = fullMatrix.RowIndex[i]; j < fullMatrix.RowIndex[i + 1]; j++) {
            if (i == fullMatrix.Col[j]) diag[i] = j;
        }
    }

//    for (int i = 0; i < fullMatrix.N + 1; i++) {
//        printf("RowIndex[%i] = %i\n", i, fullMatrix.RowIndex[i]);
//    }
//
//
//    for (int i = 0; i < fullMatrix.N; i++) {
//        printf("input[%i]= %lf\n", i, fullMatrix.Value[inputMatrix.RowIndex[i]]);
//    }
//
//    for (int i = 0; i < fullMatrix.N; i++) {
//        printf("diag[%i]= %d\n", i, diag[i]);
//    }

    timer.start();
    ilu0(fullMatrix, fullMatrix.Value, diag);
	LUmatrixSeparation(fullMatrix, diag, LMatrix, UMatrix);
	Transpose(UMatrix, UMatrixTranspose);
	Multiplicate(LMatrix, UMatrixTranspose, MMatrix);
    timer.stop();

    std::ofstream timeLog;
    timeLog.open(argv[3]);
    timeLog << timer.getElapsed();

    WriteFullMatrix(MMatrix, output_file, matcode);

    FreeMatrix(fullMatrix);

    return 0;
}
コード例 #21
0
ファイル: main.cpp プロジェクト: nikkrasn/NumMethods
int main(int argc, char *argv[])
{
  if (argc < 3)
  {
    printf("Invalid input parameters\n");
    return 1;
  }
  
  int N = atoi(argv[1]);
  int NZ = atoi(argv[2]);
  char *mtxFileName = NULL;
  char *vecFileName = NULL;
  if (argc > 3 && argc < 6)
  {
      mtxFileName = argv[3];
      vecFileName = argv[4];
  }

  if ((NZ > N) || (N <= 0) || (NZ <= 0))
  {
    printf("Incorrect arguments of main\n");
    return 1;
  }

  crsMatrix A;
  double *x, *b, *bm;
  double timeM=0, timeM1=0, diff=0;

  if (ReadMatrix(A, mtxFileName) != 0)
  {
    GenerateRegularCRS(1, N, NZ, A);
    WriteMatrix(A, "mtx.txt");
  }
  if (ReadVector(&x, N, vecFileName) != 0)
  {
    GenerateVector(2, N, &x);
    WriteVector(x, N, "vec.txt");
  }

  InitializeVector(N, &b);
  Multiplicate(A, x, b, timeM);

  InitializeVector(N, &bm);
  SparseMKLMult(A, x, bm, timeM1);

  CompareVectors(b, bm, N, diff);

  if (diff < EPSILON)
    printf("OK\n");
  else
    printf("not OK\n");
  printf("%d %d\n", A.N, A.NZ);
  printf("%.3f %.3f\n", timeM, timeM1);

  FreeMatrix(A);
  FreeVector(&b);
  FreeVector(&bm);
  FreeVector(&x);

  return 0;
}
コード例 #22
0
ファイル: registration.c プロジェクト: Kinect5/ICP
/*
 * Perfrom a fine registration using the ICP algorithm
 */
void FineRegistration(void)
{
  int         i, j, count;
  int         num_p, num_q;
  point_xyz   *p, *q, cp;
  matrix      *R;
  vector      *t;
  double      Mf[16];

  // compute total number of points
  num_p = num_q = 0;
  for (i=0; i<num_rdata_anc; i++) num_q += rd_anc[i].num_pt;
  for (i=0; i<num_rdata_mov; i++) num_p += rd_mov[i].num_pt;

  // allocate memory
  R = AllocateMatrix(3, 3);
  t = AllocateVector(3);
  p = (point_xyz *) malloc (num_p * sizeof(point_xyz));
  q = (point_xyz *) malloc (num_q * sizeof(point_xyz));

  // copy xyz values
  count = 0;
  for (i=0; i<num_rdata_anc; i++) {
    
    for (j=0; j<rd_anc[i].num_pt; j++) {
      cp.x = rd_anc[i].xyz[3*j];
      cp.y = rd_anc[i].xyz[3*j+1];
      cp.z = rd_anc[i].xyz[3*j+2];
      // transform with its modeling transformation matrix
      q[count].x = cp.x * rd_anc[i].M[0] + cp.y * rd_anc[i].M[4] +
                   cp.z * rd_anc[i].M[8] + rd_anc[i].M[12];
      q[count].y = cp.x * rd_anc[i].M[1] + cp.y * rd_anc[i].M[5] +
                   cp.z * rd_anc[i].M[9] + rd_anc[i].M[13];
      q[count].z = cp.x * rd_anc[i].M[2] + cp.y * rd_anc[i].M[6] +
                   cp.z * rd_anc[i].M[10] + rd_anc[i].M[14]; 
      count++;
    }
  }
  count = 0;
  for (i=0; i<num_rdata_mov; i++) {
    // use modelview just for matrix multiplication
    
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    glMultMatrixd(new_M);
    glMultMatrixd(rd_mov[i].M);
    glGetDoublev(GL_MODELVIEW_MATRIX, Mf);
    glPopMatrix();

    for (j=0; j<rd_mov[i].num_pt; j++) {
      // transform 
      cp.x = rd_mov[i].xyz[3*j];
      cp.y = rd_mov[i].xyz[3*j+1];
      cp.z = rd_mov[i].xyz[3*j+2];
      
      p[count].x = cp.x*Mf[0] + cp.y*Mf[4] + cp.z*Mf[8] + Mf[12];
      p[count].y = cp.x*Mf[1] + cp.y*Mf[5] + cp.z*Mf[9] + Mf[13];
      p[count].z = cp.x*Mf[2] + cp.y*Mf[6] + cp.z*Mf[10] + Mf[14]; 
      count++;
    }
  }

  // perform ICP
  //ICPalgorithm(R, t, p, num_p, q, num_q, 5, 5.0, 100, 0.10, 0.0005);
  ICPalgorithm(R, t, p, num_p, q, num_q, 5, 5.0, 1000, 0.010, 0.000005);
  Mf[0] = R->entry[0][0]; Mf[4] = R->entry[0][1]; Mf[8] = R->entry[0][2];
  Mf[1] = R->entry[1][0]; Mf[5] = R->entry[1][1]; Mf[9] = R->entry[1][2];
  Mf[2] = R->entry[2][0]; Mf[6] = R->entry[2][1]; Mf[10] = R->entry[2][2];
  Mf[12] = t->entry[0];   Mf[13] = t->entry[1];   Mf[14] = t->entry[2];
  Mf[3] = Mf[7] = Mf[11] = 0; Mf[15] = 1;

  // update new_M
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  glMultMatrixd(Mf);
  glMultMatrixd(new_M);
  glGetDoublev(GL_MODELVIEW_MATRIX, new_M);
  glPopMatrix();

  // free memory
  FreeMatrix(R); FreeVector(t);
  free(p); free(q);
}
コード例 #23
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;
}
コード例 #24
0
ファイル: registration.c プロジェクト: Kinect5/ICP
/*
 * Peform a course registration using selected corresponding points by user
 */
void CourseRegistration(void)
{
  register int  i;
  double        Sxx, Sxy, Sxz,
                Syx, Syy, Syz,
                Szx, Szy, Szz; 
  double        max_eval;
  point_xyz     *p, *q;
  point_xyz     mean_corres_p,
                mean_corres_q;  
  int           num_corres; 
  matrix        *Q, *R;
  vector        *max_evec, *t;

  // initialize values
  Sxx = Sxy = Sxz = Syx = Syy = Syz = Szx = Szy = Szz = 0.0;
  mean_corres_p.x = mean_corres_p.y = mean_corres_p.z = 0.0;
  mean_corres_q.x = mean_corres_q.y = mean_corres_q.z = 0.0;

  // take the smaller one
  num_corres = (num_corres_anc<num_corres_mov)?num_corres_anc:num_corres_mov;

  // allocate memory
  Q = AllocateMatrix(4, 4);
  R = AllocateMatrix(3, 3);
  max_evec = AllocateVector(4);
  t = AllocateVector(3);
  p = (point_xyz *) malloc (num_corres * sizeof(point_xyz));
  q = (point_xyz *) malloc (num_corres * sizeof(point_xyz));
  
  // transform
  for (i=0; i<num_corres; i++) {
    p[i].x = (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]] *
              rd_mov[corres_rd_mov[i]].M[0]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+1] *
              rd_mov[corres_rd_mov[i]].M[4]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+2] *
              rd_mov[corres_rd_mov[i]].M[8]) +
              rd_mov[corres_rd_mov[i]].M[12];
    p[i].y = (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]] *
              rd_mov[corres_rd_mov[i]].M[1]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+1] *
              rd_mov[corres_rd_mov[i]].M[5]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+2] *
              rd_mov[corres_rd_mov[i]].M[9]) +
              rd_mov[corres_rd_mov[i]].M[13];
    p[i].z = (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]] *
              rd_mov[corres_rd_mov[i]].M[2]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+1] *
              rd_mov[corres_rd_mov[i]].M[6]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+2] *
              rd_mov[corres_rd_mov[i]].M[10]) +
              rd_mov[corres_rd_mov[i]].M[14];

    q[i].x = (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]] *
              rd_anc[corres_rd_anc[i]].M[0]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+1] *
              rd_anc[corres_rd_anc[i]].M[4]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+2] *
              rd_anc[corres_rd_anc[i]].M[8]) +
              rd_anc[corres_rd_anc[i]].M[12];
    q[i].y = (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]] *
              rd_anc[corres_rd_anc[i]].M[1]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+1] *
              rd_anc[corres_rd_anc[i]].M[5]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+2] *
              rd_anc[corres_rd_anc[i]].M[9]) +
              rd_anc[corres_rd_anc[i]].M[13];
    q[i].z = (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]] *
              rd_anc[corres_rd_anc[i]].M[2]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+1] *
              rd_anc[corres_rd_anc[i]].M[6]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+2] *
              rd_anc[corres_rd_anc[i]].M[10]) +
              rd_anc[corres_rd_anc[i]].M[14];

    //printf("%d: %f %f %f\n", i, q[i].x, q[i].y, q[i].z);
  }
 
  
  for (i=0; i<num_corres; i++) {
    mean_corres_p.x += p[i].x;
    mean_corres_p.y += p[i].y;
    mean_corres_p.z += p[i].z;
      
    mean_corres_q.x += q[i].x;
    mean_corres_q.y += q[i].y;
    mean_corres_q.z += q[i].z;
  }
  mean_corres_p.x /= (double)num_corres;
  mean_corres_p.y /= (double)num_corres;
  mean_corres_p.z /= (double)num_corres;
  mean_corres_q.x /= (double)num_corres;
  mean_corres_q.y /= (double)num_corres;
  mean_corres_q.z /= (double)num_corres;

     
  for (i=0; i<num_corres; i++) {
    Sxx += p[i].x * q[i].x;
    Sxy += p[i].x * q[i].y;
    Sxz += p[i].x * q[i].z;
    Syx += p[i].y * q[i].x;
    Syy += p[i].y * q[i].y;
    Syz += p[i].y * q[i].z;
    Szx += p[i].z * q[i].x;
    Szy += p[i].z * q[i].y;
    Szz += p[i].z * q[i].z;
  }

  Sxx = Sxx / (double)num_corres - (mean_corres_p.x * mean_corres_q.x);
  Sxy = Sxy / (double)num_corres - (mean_corres_p.x * mean_corres_q.y);
  Sxz = Sxz / (double)num_corres - (mean_corres_p.x * mean_corres_q.z);
  Syx = Syx / (double)num_corres - (mean_corres_p.y * mean_corres_q.x);
  Syy = Syy / (double)num_corres - (mean_corres_p.y * mean_corres_q.y);
  Syz = Syz / (double)num_corres - (mean_corres_p.y * mean_corres_q.z);
  Szx = Szx / (double)num_corres - (mean_corres_p.z * mean_corres_q.x);
  Szy = Szy / (double)num_corres - (mean_corres_p.z * mean_corres_q.y);
  Szz = Szz / (double)num_corres - (mean_corres_p.z * mean_corres_q.z);

  // construct N
  Q->entry[0][0] = Sxx + Syy + Szz;
  Q->entry[1][0] = Q->entry[0][1] = Syz - Szy;
  Q->entry[2][0] = Q->entry[0][2] = Szx - Sxz;
  Q->entry[3][0] = Q->entry[0][3] = Sxy - Syx;
  Q->entry[1][1] = Sxx - Syy - Szz;
  Q->entry[1][2] = Q->entry[2][1] = Sxy + Syx;
  Q->entry[1][3] = Q->entry[3][1] = Szx + Sxz;
  Q->entry[2][2] = -Sxx + Syy - Szz;
  Q->entry[2][3] = Q->entry[3][2] = Syz + Szy;
  Q->entry[3][3] = -Sxx - Syy + Szz;

  // --- compute largest eigenvalues and eigenvectors of Q ---
  SymmetricLargestEigens(Q, max_evec, &max_eval); 
  // make sure max_evec[0] > 0
  if (max_evec->entry[0] < 0) {
    for (i=0; i<4; i++) max_evec->entry[i] *= -1.0;
  }
  // --- compute rotation matrix ---
  RotationQuaternion(max_evec, R);
 
  // --- compute translation vector ---
  t->entry[0] = mean_corres_q.x - 
                R->entry[0][0] * mean_corres_p.x -
                R->entry[0][1] * mean_corres_p.y -
                R->entry[0][2] * mean_corres_p.z;
  t->entry[1] = mean_corres_q.y - 
                R->entry[1][0] * mean_corres_p.x -
                R->entry[1][1] * mean_corres_p.y -
                R->entry[1][2] * mean_corres_p.z;
  t->entry[2] = mean_corres_q.z - 
                R->entry[2][0] * mean_corres_p.x -
                R->entry[2][1] * mean_corres_p.y -
                R->entry[2][2] * mean_corres_p.z;

  //PrintMatrix(R);
  //PrintVector(t);

  new_M[0] = R->entry[0][0]; new_M[4] = R->entry[0][1]; new_M[8] = R->entry[0][2];
  new_M[1] = R->entry[1][0]; new_M[5] = R->entry[1][1]; new_M[9] = R->entry[1][2];
  new_M[2] = R->entry[2][0]; new_M[6] = R->entry[2][1]; new_M[10] = R->entry[2][2];
  new_M[12] = t->entry[0];   new_M[13] = t->entry[1];   new_M[14] = t->entry[2];
  new_M[3] = new_M[7] = new_M[11] = 0; new_M[15] = 1;

  // free memory
  FreeMatrix(Q); FreeMatrix(R);
  FreeVector(max_evec); FreeVector(t);
  free(p); free(q);
}
コード例 #25
0
ファイル: MARnoncomp.c プロジェクト: cran/experiment
void MARprobit(int *Y, /* binary outcome variable */ 
	       int *Ymiss, /* missingness indicator for Y */
	       int *iYmax,  /* maximum value of Y; 0,1,...,Ymax */
	       int *Z, /* treatment assignment */
	       int *D, /* treatment status */ 
	       int *C, /* compliance status */
	       double *dX, double *dXo, /* covariates */
	       double *dBeta, double *dGamma,    /* coefficients */
	       int *iNsamp, int *iNgen, int *iNcov, int *iNcovo,
	       int *iNcovoX, int *iN11, 
	       /* counters */
	       double *beta0, double *gamma0, double *dA, double *dAo, /*prior */
	       int *insample, /* 1: insample inference, 2: conditional inference */
	       int *smooth,   
	       int *param, int *mda, int *iBurnin, 
	       int *iKeep, int *verbose, /* options */
	       double *pdStore
	       ) {
  
  /*** counters ***/
  int n_samp = *iNsamp;   /* sample size */
  int n_gen = *iNgen;     /* number of gibbs draws */
  int n_cov = *iNcov;     /* number of covariates */
  int n_covo = *iNcovo;   /* number of all covariates for outcome model */
  int n_covoX = *iNcovoX; /* number of covariates excluding smooth
			     terms */
  int n11 = *iN11;        /* number of compliers in the treament group */
  
  /*** data ***/
  double **X;     /* covariates for the compliance model */
  double **Xo;    /* covariates for the outcome model */
  double *W;      /* latent variable */
  int Ymax = *iYmax;

  /*** model parameters ***/
  double *beta;   /* coef for compliance model */
  double *gamma;  /* coef for outcomme model */
  double *q;      /* some parameters for sampling C */
  double *pc; 
  double *pn;
  double pcmean;
  double pnmean;
  double **SS;    /* matrix folders for SWEEP */
  double **SSo; 
  // HJ commented it out on April 17, 2018
  // double **SSr;
  double *meanb;  /* means for beta and gamma */
  double *meano;
  double *meanr;
  double **V;     /* variances for beta and gamma */
  double **Vo;
  double **Vr;
  double **A;
  double **Ao;
  double *tau;    /* thresholds: tau_0, ..., tau_{Ymax-1} */
  double *taumax; /* corresponding max and min for tau */
  double *taumin; /* tau_0 is fixed to 0 */
  double *treat;  /* smooth function for treat */

  /*** quantities of interest ***/
  int n_comp, n_compC, n_ncompC; 
  double *ITTc;
  double *base;

  /*** storage parameters and loop counters **/
  int progress = 1;
  int keep = 1;
  int i, j, k, main_loop;  
  int itemp, itempP = ftrunc((double) n_gen/10);
  double dtemp, ndraw, cdraw;
  double *vtemp;
  double **mtemp, **mtempo;

  /*** marginal data augmentation ***/
  double sig2 = 1;
  int nu0 = 1;
  double s0 = 1;

  /*** get random seed **/
  GetRNGstate();


  /*** define vectors and matricies **/
  X = doubleMatrix(n_samp+n_cov, n_cov+1);
  Xo = doubleMatrix(n_samp+n_covo, n_covo+1);
  W = doubleArray(n_samp);
  tau = doubleArray(Ymax);
  taumax = doubleArray(Ymax);
  taumin = doubleArray(Ymax);
  SS = doubleMatrix(n_cov+1, n_cov+1);
  SSo = doubleMatrix(n_covo+1, n_covo+1);
  // HJ commented it out on April 17, 2018
  // SSr = doubleMatrix(4, 4);
  V = doubleMatrix(n_cov, n_cov);
  Vo = doubleMatrix(n_covo, n_covo);
  Vr = doubleMatrix(3, 3);
  beta = doubleArray(n_cov); 
  gamma = doubleArray(n_covo); 
  meanb = doubleArray(n_cov); 
  meano = doubleArray(n_covo); 
  meanr = doubleArray(3); 
  q = doubleArray(n_samp); 
  pc = doubleArray(n_samp); 
  pn = doubleArray(n_samp); 
  A = doubleMatrix(n_cov, n_cov);
  Ao = doubleMatrix(n_covo, n_covo);
  vtemp = doubleArray(n_samp);
  mtemp = doubleMatrix(n_cov, n_cov);
  mtempo = doubleMatrix(n_covo, n_covo);
  ITTc = doubleArray(Ymax+1);
  treat = doubleArray(n11);
  base = doubleArray(2);

  /*** read the data ***/
  itemp = 0;
  for (j =0; j < n_cov; j++)
    for (i = 0; i < n_samp; i++)
      X[i][j] = dX[itemp++];

  itemp = 0;
  for (j =0; j < n_covo; j++)
    for (i = 0; i < n_samp; i++)
      Xo[i][j] = dXo[itemp++];
  
  /*** read the prior and it as additional data points ***/ 
  itemp = 0;
  for (k = 0; k < n_cov; k++)
    for (j = 0; j < n_cov; j++)
      A[j][k] = dA[itemp++];

  itemp = 0;
  for (k = 0; k < n_covo; k++)
    for (j = 0; j < n_covo; j++)
      Ao[j][k] = dAo[itemp++];

  dcholdc(A, n_cov, mtemp);
  for(i = 0; i < n_cov; i++) {
    X[n_samp+i][n_cov]=0;
    for(j = 0; j < n_cov; j++) {
      X[n_samp+i][n_cov] += mtemp[i][j]*beta0[j];
      X[n_samp+i][j] = mtemp[i][j];
    }
  }

  dcholdc(Ao, n_covo, mtempo);
  for(i = 0; i < n_covo; i++) {
    Xo[n_samp+i][n_covo]=0;
    for(j = 0; j < n_covo; j++) {
      Xo[n_samp+i][n_covo] += mtempo[i][j]*gamma0[j];
      Xo[n_samp+i][j] = mtempo[i][j];
    }
  }

  /*** starting values ***/
  for (i = 0; i < n_cov; i++) 
    beta[i] = dBeta[i];
  for (i = 0; i < n_covo; i++)
    gamma[i] = dGamma[i];
  
  if (Ymax > 1) {
    tau[0] = 0.0;
    taumax[0] = 0.0;
    taumin[0] = 0.0;
    for (i = 1; i < Ymax; i++)
      tau[i] = tau[i-1]+2/(double)(Ymax-1);
  }
  for (i = 0; i < n_samp; i++) {
    pc[i] = unif_rand(); 
    pn[i] = unif_rand();
  }

  /*** Gibbs Sampler! ***/
  itemp=0;     
  for(main_loop = 1; main_loop <= n_gen; main_loop++){

    /** COMPLIANCE MODEL **/    
    if (*mda) sig2 = s0/rchisq((double)nu0);
    /* Draw complier status for control group */
    for(i = 0; i < n_samp; i++){
      dtemp = 0;
      for(j = 0; j < n_cov; j++) 
	dtemp += X[i][j]*beta[j];
      if(Z[i] == 0){
	q[i] = pnorm(dtemp, 0, 1, 1, 0);
	if(unif_rand() < (q[i]*pc[i]/(q[i]*pc[i]+(1-q[i])*pn[i]))) { 
	  C[i] = 1; Xo[i][1] = 1; 
	}
	else {
	  C[i] = 0; Xo[i][1] = 0;
	}
      }
      /* Sample W */
      if(C[i]==0) 
	W[i] = TruncNorm(dtemp-100,0,dtemp,1,0);
      else 
	W[i] = TruncNorm(0,dtemp+100,dtemp,1,0);
      X[i][n_cov] = W[i]*sqrt(sig2);
      W[i] *= sqrt(sig2);
    }

    /* SS matrix */
    for(j = 0; j <= n_cov; j++)
      for(k = 0; k <= n_cov; k++)
	SS[j][k]=0;
    for(i = 0; i < n_samp+n_cov; i++)
      for(j = 0; j <= n_cov; j++)
	for(k = 0; k <= n_cov; k++) 
	  SS[j][k] += X[i][j]*X[i][k];
    /* SWEEP SS matrix */
    for(j = 0; j < n_cov; j++)
      SWP(SS, j, n_cov+1);
    /* draw beta */    
    for(j = 0; j < n_cov; j++)
      meanb[j] = SS[j][n_cov];
    if (*mda) 
      sig2=(SS[n_cov][n_cov]+s0)/rchisq((double)n_samp+nu0);
    for(j = 0; j < n_cov; j++)
      for(k = 0; k < n_cov; k++) V[j][k] = -SS[j][k]*sig2;
    rMVN(beta, meanb, V, n_cov);

    /* rescale the parameters */
    if(*mda) {
      for (i = 0; i < n_cov; i++) beta[i] /= sqrt(sig2);
    }

    /** OUTCOME MODEL **/
    /* Sample W */
    if (Ymax > 1) { /* tau_0=0, tau_1, ... */
      for (j = 1; j < (Ymax - 1); j++) {
	taumax[j] = tau[j+1];
	taumin[j] = tau[j-1];
      }
      taumax[Ymax-1] = tau[Ymax-1]+100;
      taumin[Ymax-1] = tau[Ymax-2];
    }
    if (*mda) sig2 = s0/rchisq((double)nu0);
    for (i = 0; i < n_samp; i++){
      dtemp = 0;
      for (j = 0; j < n_covo; j++) dtemp += Xo[i][j]*gamma[j];
      if (Ymiss[i] == 1) {
	W[i] = dtemp + norm_rand();
	if (Ymax == 1) { /* binary probit */
	  if (W[i] > 0) Y[i] = 1;
	  else Y[i] = 0;
	}
	else { /* ordered probit */
	  if (W[i] >= tau[Ymax-1])
	    Y[i] = Ymax;
	  else {
	    j = 0;
	    while (W[i] > tau[j] && j < Ymax) j++;
	    Y[i] = j;
	  }
	}
      }
      else {
	if(Ymax == 1) { /* binary probit */
	  if(Y[i] == 0) W[i] = TruncNorm(dtemp-100,0,dtemp,1,0);
	  else W[i] = TruncNorm(0,dtemp+100,dtemp,1,0);
	}
	else {         /* ordered probit */
	  if (Y[i] == 0) 
	    W[i] = TruncNorm(dtemp-100, 0, dtemp, 1, 0);
	  else if (Y[i] == Ymax) {
	    W[i] = TruncNorm(tau[Ymax-1], dtemp+100, dtemp, 1, 0);
	    if (W[i] < taumax[Ymax-1]) taumax[Ymax-1] = W[i];
	  }
	  else {
	    W[i] = TruncNorm(tau[Y[i]-1], tau[Y[i]], dtemp, 1, 0);
	    if (W[i] > taumin[Y[i]]) taumin[Y[i]] = W[i];
	    if (W[i] < taumax[Y[i]-1]) taumax[Y[i]-1] = W[i];
	  }
	}
      }
      Xo[i][n_covo] = W[i]*sqrt(sig2);
      W[i] *= sqrt(sig2);
    }
    /* draw tau */
    if (Ymax > 1) 
      for (j = 1; j < Ymax; j++) 
	tau[j] = runif(taumin[j], taumax[j])*sqrt(sig2);
    /* SS matrix */
    for(j = 0; j <= n_covo; j++)
      for(k = 0; k <= n_covo; k++)
	SSo[j][k]=0;
    for(i = 0;i < n_samp+n_covo; i++)
      for(j = 0;j <= n_covo; j++)
	for(k = 0; k <= n_covo; k++) 
	  SSo[j][k] += Xo[i][j]*Xo[i][k];
    /* SWEEP SS matrix */
    for(j = 0; j < n_covo; j++)
      SWP(SSo, j, n_covo+1);

    /* draw gamma */    
    for(j = 0; j < n_covo; j++)
      meano[j] = SSo[j][n_covo];
    if (*mda) 
      sig2=(SSo[n_covo][n_covo]+s0)/rchisq((double)n_samp+nu0);
    for(j = 0; j < n_covo; j++)
      for(k = 0; k < n_covo; k++) Vo[j][k]=-SSo[j][k]*sig2;
    rMVN(gamma, meano, Vo, n_covo); 
    
    /* rescaling the parameters */
    if(*mda) {
      for (i = 0; i < n_covo; i++) gamma[i] /= sqrt(sig2);
      if (Ymax > 1)
	for (i = 1; i < Ymax; i++)
	  tau[i] /= sqrt(sig2);
    }

    /* computing smooth terms */
    if (*smooth) {
      for (i = 0; i < n11; i++) {
	treat[i] = 0;
	for (j = n_covoX; j < n_covo; j++)
	  treat[i] += Xo[i][j]*gamma[j]; 
      }
    }

    /** Compute probabilities **/ 
    for(i = 0; i < n_samp; i++){
      vtemp[i] = 0;
      for(j = 0; j < n_covo; j++)
	vtemp[i] += Xo[i][j]*gamma[j];
    }

    for(i = 0; i < n_samp; i++){
      if(Z[i]==0){
	if (C[i] == 1) {
	  pcmean = vtemp[i];
	  if (*smooth)
	    pnmean = vtemp[i]-gamma[0];
	  else
	    pnmean = vtemp[i]-gamma[1];
	}
	else {
	  if (*smooth)
	    pcmean = vtemp[i]+gamma[0];
	  else
	    pcmean = vtemp[i]+gamma[1];
	  pnmean = vtemp[i];
	}
	if (Y[i] == 0){
	  pc[i] = pnorm(0, pcmean, 1, 1, 0);
	  pn[i] = pnorm(0, pnmean, 1, 1, 0);
	}
	else {
	  if (Ymax == 1) { /* binary probit */
	    pc[i] = pnorm(0, pcmean, 1, 0, 0);
	    pn[i] = pnorm(0, pnmean, 1, 0, 0);
	  }
	  else { /* ordered probit */
	    if (Y[i] == Ymax) {
	      pc[i] = pnorm(tau[Ymax-1], pcmean, 1, 0, 0);
	      pn[i] = pnorm(tau[Ymax-1], pnmean, 1, 0, 0);
	    }
	    else {
	      pc[i] = pnorm(tau[Y[i]], pcmean, 1, 1, 0) -
		pnorm(tau[Y[i]-1], pcmean, 1, 1, 0);
	      pn[i] = pnorm(tau[Y[i]], pnmean, 1, 1, 0) - 
		pnorm(tau[Y[i]-1], pnmean, 1, 1, 0);
	    }
	  }
	}
      } 
    }

    /** Compute quantities of interest **/
    n_comp = 0; n_compC = 0; n_ncompC = 0; base[0] = 0; base[1] = 0; 
    for (i = 0; i <= Ymax; i++)
      ITTc[i] = 0;
    if (*smooth) {
      for(i = 0; i < n11; i++){
	if(C[i] == 1) {
	  n_comp++;
	  if (Z[i] == 0) {
	    n_compC++;
	    base[0] += (double)Y[i];
	  }
	  pcmean = vtemp[i];
	  pnmean = vtemp[i]-treat[i]+gamma[0];
	  ndraw = rnorm(pnmean, 1);
	  cdraw = rnorm(pcmean, 1);
	  if (*insample && Ymiss[i]==0) 
	    dtemp = (double)(Y[i]==0) - (double)(ndraw < 0);
	  else
	    dtemp = pnorm(0, pcmean, 1, 1, 0) - pnorm(0, pnmean, 1, 1, 0);
	  ITTc[0] += dtemp;
	  if (Ymax == 1) { /* binary probit */
	    if (*insample && Ymiss[i]==0) 
	      dtemp = (double)Y[i] - (double)(ndraw > 0);
	    else
	      dtemp = pnorm(0, pcmean, 1, 0, 0) - pnorm(0, pnmean, 1, 0, 0);
	    ITTc[1] += dtemp;
	  }
	  else { /* ordered probit */
	    if (*insample && Ymiss[i]==0) 
	      dtemp = (double)(Y[i]==Ymax) - (double)(ndraw > tau[Ymax-1]);
	    else
	      dtemp = pnorm(tau[Ymax-1], pcmean, 1, 0, 0) -
		pnorm(tau[Ymax-1], pnmean, 1, 0, 0);
	    ITTc[Ymax] += dtemp; 
	    for (j = 1; j < Ymax; j++) {
	      if (*insample && Ymiss[i]==0)
		  dtemp = (double)(Y[i]==j) - (double)(ndraw < tau[j] &&
						       ndraw > tau[j-1]);
	      else
		dtemp = (pnorm(tau[j], pcmean, 1, 1, 0) - 
			 pnorm(tau[j-1], pcmean, 1, 1, 0)) 
		  - (pnorm(tau[j], pnmean, 1, 1, 0) - 
		     pnorm(tau[j-1], pnmean, 1, 1, 0));
	      ITTc[j] += dtemp;
	    }
	  }
	}
	else
	  if (Z[i] == 0) {
	    n_ncompC++;
	    base[1] += (double)Y[i];
	  } 
      }
    }
    else {
      for(i = 0; i < n_samp; i++){
	if(C[i] == 1) {
	  n_comp++;
	  if (Z[i] == 1) {
	    pcmean = vtemp[i];
	    pnmean = vtemp[i]-gamma[0]+gamma[1];
	  }
	  else {
	    n_compC++;
	    base[0] += (double)Y[i];
	    pcmean = vtemp[i]+gamma[0]-gamma[1];
	    pnmean = vtemp[i];
	  }
	  ndraw = rnorm(pnmean, 1);
	  cdraw = rnorm(pcmean, 1);
	  if (*insample && Ymiss[i]==0) {
	    if (Z[i] == 1)
	      dtemp = (double)(Y[i]==0) - (double)(ndraw < 0);
	    else
	      dtemp = (double)(cdraw < 0) - (double)(Y[i]==0);
	  }
	  else 
	    dtemp = pnorm(0, pcmean, 1, 1, 0) - pnorm(0, pnmean, 1, 1, 0);
	  ITTc[0] += dtemp;
	  if (Ymax == 1) { /* binary probit */
	    if (*insample && Ymiss[i]==0) {
	      if (Z[i] == 1)
		dtemp = (double)Y[i] - (double)(ndraw > 0);
	      else
		dtemp = (double)(cdraw > 0) - (double)Y[i];
	    }
	    else
	      dtemp = pnorm(0, pcmean, 1, 0, 0) - pnorm(0, pnmean, 1, 0, 0);
	    ITTc[1] += dtemp;
	  }
	  else { /* ordered probit */
	    if (*insample && Ymiss[i]==0) {
	      if (Z[i] == 1)
		dtemp = (double)(Y[i]==Ymax) - (double)(ndraw > tau[Ymax-1]);
	      else
		dtemp = (double)(cdraw > tau[Ymax-1]) - (double)(Y[i]==Ymax);
	    }
	    else 
	      dtemp = pnorm(tau[Ymax-1], pcmean, 1, 0, 0) -
		pnorm(tau[Ymax-1], pnmean, 1, 0, 0);
	    ITTc[Ymax] += dtemp; 
	    for (j = 1; j < Ymax; j++) {
	      if (*insample && Ymiss[i]==0) {
		if (Z[i] == 1)
		  dtemp = (double)(Y[i]==j) - (double)(ndraw < tau[j] && ndraw > tau[j-1]);
		else
		  dtemp = (pnorm(tau[j], pcmean, 1, 1, 0) - 
			   pnorm(tau[j-1], pcmean, 1, 1, 0)) - (double)(Y[i]==j);
	      }
	      else
		dtemp = (pnorm(tau[j], pcmean, 1, 1, 0) - 
			 pnorm(tau[j-1], pcmean, 1, 1, 0)) 
		  - (pnorm(tau[j], pnmean, 1, 1, 0) - 
		     pnorm(tau[j-1], pnmean, 1, 1, 0));
	      ITTc[j] += dtemp;
	    }
	  }
	}
	else
	  if (Z[i] == 0) {
	    n_ncompC++;
	    base[1] += (double)Y[i];
	  }
      } 
    }
    
    /** storing the results **/
    if (main_loop > *iBurnin) {
      if (keep == *iKeep) {
	pdStore[itemp++]=(double)n_comp/(double)n_samp;
	if (Ymax == 1) {
	  pdStore[itemp++]=ITTc[1]/(double)n_comp;
	  pdStore[itemp++]=ITTc[1]/(double)n_samp;
	  pdStore[itemp++] = base[0]/(double)n_compC;
	  pdStore[itemp++] = base[1]/(double)n_ncompC;
	  pdStore[itemp++] = (base[0]+base[1])/(double)(n_compC+n_ncompC);
	}
	else {
	  for (i = 0; i <= Ymax; i++) 
	    pdStore[itemp++]=ITTc[i]/(double)n_comp;
	  for (i = 0; i <= Ymax; i++) 
	    pdStore[itemp++]=ITTc[i]/(double)n_samp;
	}
	if (*param) {
	  for(i = 0; i < n_cov; i++) 
	    pdStore[itemp++]=beta[i];
	  if (*smooth) {
	    for(i = 0; i < n_covoX; i++)
	      pdStore[itemp++]=gamma[i];
	    for(i = 0; i < n11; i++)
	      pdStore[itemp++]=treat[i];
	  }
	  else
	    for(i = 0; i < n_covo; i++)
	      pdStore[itemp++]=gamma[i];
	  if (Ymax > 1)
	    for (i = 0; i < Ymax; i++)
	      pdStore[itemp++]=tau[i];
	}
	keep = 1;
      }
      else
	keep++;
    }

    if(*verbose) {
      if(main_loop == itempP) {
	Rprintf("%3d percent done.\n", progress*10);
	itempP += ftrunc((double) n_gen/10); 
	progress++;
	R_FlushConsole(); 
      }
    }
    R_FlushConsole();
    R_CheckUserInterrupt();
  } /* end of Gibbs sampler */

  /** write out the random seed **/
  PutRNGstate();

  /** freeing memory **/
  FreeMatrix(X, n_samp+n_cov);
  FreeMatrix(Xo, n_samp+n_covo);
  free(W);
  free(beta);
  free(gamma);
  free(q);
  free(pc);
  free(pn);
  FreeMatrix(SS, n_cov+1);
  FreeMatrix(SSo, n_covo+1);
  free(meanb);
  free(meano);
  free(meanr);
  FreeMatrix(V, n_cov);
  FreeMatrix(Vo, n_covo);
  FreeMatrix(Vr, 3);
  FreeMatrix(A, n_cov);
  FreeMatrix(Ao, n_covo);
  free(tau);
  free(taumax);
  free(taumin);
  free(ITTc);
  free(vtemp);
  free(treat);
  free(base);
  FreeMatrix(mtemp, n_cov);
  FreeMatrix(mtempo, n_covo);

} /* main */
コード例 #26
0
int main(int argc, char *argv[]) {

    unsigned int processes = 8u;
    unsigned int N = 1024u;
    if (argc > 1) {
        processes = (unsigned int) atoi(argv[1]);
    }
    if (argc > 2) {
        N = (unsigned int) atoi(argv[2]);
    }
    processes = N * N < processes ? N * N : processes;
    unsigned int n = N * N / processes;

    srand((unsigned int) time(NULL));

    pthread_t *threads;
    struct Task *tasks;
    threads = (pthread_t *) malloc(processes * sizeof(pthread_t));
    tasks = (struct Task *) malloc(processes * sizeof(struct Task));

    //Map tasks
    double **A;
    double **B;
    double **C;
    A = AllocateRandomMatrix(N);
    B = AllocateRandomMatrix(N);
    C = AllocateValueMatrix(N, 0.0);
    for (unsigned int p = 0; p < processes; ++p) {
        tasks[p].A = A;
        tasks[p].B = B;
        tasks[p].C = AllocateValueMatrix(N, 0.0);
        for (unsigned int i = 0; i < N; ++i) {
            for (int j = 0; j < N; ++j) {
                if (i * N + j >= n * (p) && i * N + j < n * (p + 1)) {
                    tasks[p].C[i][j] = 1.0;
                } else {
                    tasks[p].C[i][j] = 0.0;
                }
            }
        }
        tasks[p].N = N;
        if (pthread_create(&threads[p], NULL, PartialMM, (void *) &tasks[p])) {
            perror("pthread_create() failed");
            return EXIT_FAILURE;
        }
    }

    //Reduce results
    for (int p = 0; p < processes; ++p) {
        pthread_join(threads[p], NULL);
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < N; ++j) {
                C[i][j] += tasks[p].C[i][j];
            }
        }
        FreeMatrix(tasks[p].C, N);
    }
    printf("Processes\t%d\n", processes);
    printf("Size\t\t%dx%d\n", N, N);
    //printf("Result\n");
    //PrintMatrix(C, N);
    FreeMatrix(A, N);
    FreeMatrix(B, N);
    FreeMatrix(C, N);
    free(threads);
    free(tasks);
    return EXIT_SUCCESS;
}
コード例 #27
0
ファイル: NIstandard.c プロジェクト: cran/experiment
void NIbprobitMixed(int *Y,         /* binary outcome variable */ 
		    int *R,         /* recording indicator for Y */
		    int *grp,       /* group indicator */
		    int *in_grp,    /* number of groups */
		    int *max_samp_grp, /* max # of obs within group */
		    double *dXo,    /* fixed effects covariates */
		    double *dXr,    /* fixed effects covariates */
		    double *dZo,    /* random effects covariates */
		    double *dZr,    /* random effects  covariates */
		    double *beta,   /* coefficients */
		    double *delta,  /* coefficients */
		    double *dPsio,  /* random effects variance */
		    double *dPsir,  /* random effects variance */
		    int *insamp,    /* # of obs */ 
		    int *incovo,    /* # of fixed effects */
		    int *incovr,    /* # of fixed effects */
		    int *incovoR,   /* # of random effects */
		    int *incovrR,   /* # of random effects */
		    int *intreat,   /* # of treatments */
		    double *beta0,  /* prior mean */
		    double *delta0, /* prior mean */
		    double *dAo,    /* prior precision */
		    double *dAr,    /* prior precision */
		    int *dfo,       /* prior degrees of freedom */
		    int *dfr,       /* prior degrees of freedom */
		    double *dS0o, /* prior scale */
		    double *dS0r, /* prior scale */
		    int *Insample,  /* insample QoI */
		    int *param,     /* store parameters? */ 
		    int *mda,       /* marginal data augmentation? */ 
		    int *ndraws,    /* # of gibbs draws */
		    int *iBurnin,   /* # of burnin */
		    int *iKeep,     /* every ?th draws to keep */
		    int *verbose,  
		    double *coefo,  /* storage for coefficients */ 
		    double *coefr,  /* storage for coefficients */ 
		    double *sPsiO,   /* storage for variance */
		    double *sPsiR,   /* storage for variance */
		    double *ATE,     /* storage for ATE */
		    double *BASE    /* storage for baseline */
		    ) {
  
  /*** counters ***/
  int n_samp = *insamp;      /* sample size */
  int n_gen = *ndraws;       /* number of gibbs draws */
  int n_grp = *in_grp;       /* number of groups */
  int n_covo = *incovo;      /* number of fixed effects */
  int n_covr = *incovr;      /* number of fixed effects */
  int n_covoR = *incovoR;    /* number of random effects */
  int n_covrR = *incovrR;    /* number of random effects */
  int n_treat = *intreat;    /* number of treatments */

  /*** data ***/
  /* covariates for the response model */
  double **Xr = doubleMatrix(n_samp+n_covr, n_covr+1);
  /* covariates for the outcome model */     
  double **Xo = doubleMatrix(n_samp+n_covo, n_covo+1);
  /* random effects covariates */
  double ***Zo = doubleMatrix3D(n_grp, *max_samp_grp + n_covoR,
				n_covoR + 1);
  double ***Zr = doubleMatrix3D(n_grp, *max_samp_grp + n_covrR,
				n_covrR + 1);

  /*** model parameters ***/
  double **PsiO = doubleMatrix(n_covoR, n_covoR);
  double **PsiR = doubleMatrix(n_covrR, n_covrR);
  double **xiO = doubleMatrix(n_grp, n_covoR);
  double **xiR = doubleMatrix(n_grp, n_covrR);
  double **S0o = doubleMatrix(n_covoR, n_covoR);
  double **S0r = doubleMatrix(n_covrR, n_covrR);
  double **Ao = doubleMatrix(n_covo, n_covo);
  double **Ar = doubleMatrix(n_covr, n_covr);
  double **mtemp1 = doubleMatrix(n_covo, n_covo);
  double **mtemp2 = doubleMatrix(n_covr, n_covr);

  /*** QoIs ***/
  double *base = doubleArray(n_treat);
  double *cATE = doubleArray(n_treat);

  /*** storage parameters and loop counters **/
  int progress = 1;
  int keep = 1;
  int i, j, k, main_loop;  
  int itemp, itemp0, itemp1, itemp2, itemp3 = 0, itempP = ftrunc((double) n_gen/10);
  int *vitemp = intArray(n_grp);
  double dtemp, pj, r0, r1;

  /*** get random seed **/
  GetRNGstate();

  /*** fixed effects ***/
  itemp = 0;
  for (j = 0; j < n_covo; j++)
    for (i = 0; i < n_samp; i++) 
      Xo[i][j] = dXo[itemp++];
  itemp = 0;
  for (j = 0; j < n_covr; j++)
    for (i = 0; i < n_samp; i++) 
      Xr[i][j] = dXr[itemp++];
  
  /* prior */
  itemp = 0;
  for (k = 0; k < n_covo; k++)
    for (j = 0; j < n_covo; j++)
      Ao[j][k] = dAo[itemp++];

  itemp = 0;
  for (k = 0; k < n_covr; k++)
    for (j = 0; j < n_covr; j++)
      Ar[j][k] = dAr[itemp++];

  dcholdc(Ao, n_covo, mtemp1);
  for(i = 0; i < n_covo; i++) {
    Xo[n_samp+i][n_covo] = 0;
    for(j = 0; j < n_covo; j++) {
      Xo[n_samp+i][n_covo] += mtemp1[i][j]*beta0[j];
      Xo[n_samp+i][j] = mtemp1[i][j];
    }
  }

  dcholdc(Ar, n_covr, mtemp2);
  for(i = 0; i < n_covr; i++) {
    Xr[n_samp+i][n_covr] = 0;
    for(j = 0; j < n_covr; j++) {
      Xr[n_samp+i][n_covr] += mtemp2[i][j]*delta0[j];
      Xr[n_samp+i][j] = mtemp2[i][j];
    }
  }

  /* random effects */
  itemp = 0;
  for (j = 0; j < n_grp; j++)
    vitemp[j] = 0;
  for (i = 0; i < n_samp; i++) {
    for (j = 0; j < n_covoR; j++)
      Zo[grp[i]][vitemp[grp[i]]][j] = dZo[itemp++];
    vitemp[grp[i]]++;
  }

  itemp = 0;
  for (j = 0; j < n_grp; j++)
    vitemp[j] = 0;
  for (i = 0; i < n_samp; i++) {
    for (j = 0; j < n_covrR; j++)
      Zr[grp[i]][vitemp[grp[i]]][j] = dZr[itemp++];
    vitemp[grp[i]]++;
  }

  /* prior variance for random effects */
  itemp = 0;
  for (k = 0; k < n_covoR; k++)
    for (j = 0; j < n_covoR; j++) 
      PsiO[j][k] = dPsio[itemp++];

  itemp = 0;
  for (k = 0; k < n_covrR; k++)
    for (j = 0; j < n_covrR; j++) 
      PsiR[j][k] = dPsir[itemp++];

  itemp = 0;
  for (k = 0; k < n_covoR; k++)
    for (j = 0; j < n_grp; j++)
      xiO[j][k] = norm_rand();

  itemp = 0;
  for (k = 0; k < n_covrR; k++)
    for (j = 0; j < n_grp; j++)
      xiR[j][k] = norm_rand();

  /* hyper prior scale parameter for random effects */
  itemp = 0;
  for (k = 0; k < n_covoR; k++)
    for (j = 0; j < n_covoR; j++)
      S0o[j][k] = dS0o[itemp++];

  itemp = 0;
  for (k = 0; k < n_covrR; k++)
    for (j = 0; j < n_covrR; j++)
      S0r[j][k] = dS0r[itemp++];

  /*** Gibbs Sampler! ***/
  itemp = 0; itemp0 = 0; itemp1 = 0; itemp2 = 0;     
  for(main_loop = 1; main_loop <= n_gen; main_loop++){

    /** Response Model: binary Probit **/    
    bprobitMixedGibbs(R, Xr, Zr, grp, delta, xiR, PsiR, n_samp,
		      n_covr, n_covrR, n_grp, 0, delta0, Ar, *dfr, S0r,
		      1);
      
    /** Outcome Model: binary probit **/
    bprobitMixedGibbs(Y, Xo, Zr, grp, beta, xiO, PsiO, n_samp, n_covo,
		      n_covoR, n_grp, 0, beta0, Ao, *dfo, S0o, 1);

    /** Imputing the missing data **/
    for (j = 0; j < n_grp; j++)
      vitemp[j] = 0;
    for (i = 0; i < n_samp; i++) {
      if (R[i] == 0) {
	pj = 0;
	r0 = delta[0];
	r1 = delta[1];
	for (j = 0; j < n_covo; j++) 
	  pj += Xo[i][j]*beta[j];
	for (j = 2; j < n_covr; j++) {
	  r0 += Xr[i][j]*delta[j];
	  r1 += Xr[i][j]*delta[j];
	}
	for (j = 0; j < n_covoR; j++)
	  pj += Zo[grp[i]][vitemp[grp[i]]][j]*xiO[grp[i]][j];
	for (j = 0; j < n_covrR; j++) {
	  r0 += Zr[grp[i]][vitemp[grp[i]]][j]*xiR[grp[i]][j];
	  r1 += Zr[grp[i]][vitemp[grp[i]]][j]*xiR[grp[i]][j];
	}
	pj = pnorm(0, pj, 1, 0, 0);
	r0 = pnorm(0, r0, 1, 0, 0);
	r1 = pnorm(0, r1, 1, 0, 0);
	if (unif_rand() < ((1-r1)*pj/((1-r1)*pj+(1-r0)*(1-pj)))) {
	  Y[i] = 1;
	  Xr[i][0] = 0;
	  Xr[i][1] = 1;
	} else {
	  Y[i] = 0;
	  Xr[i][0] = 1;
	  Xr[i][1] = 0;
	} 
      }
      vitemp[grp[i]]++;
    }
    
    /** Compute quantities of interest **/
    for (j = 0; j < n_grp; j++)
      vitemp[j] = 0;
    for (j = 0; j < n_treat; j++) 
      base[j] = 0;
    for (i = 0; i < n_samp; i++) {
      dtemp = 0; 
      for (j = n_treat; j < n_covo; j++) 
	dtemp += Xo[i][j]*beta[j];
      for (j = 0; j < n_covoR; j++)
	dtemp += Zo[grp[i]][vitemp[grp[i]]][j]*xiO[grp[i]][j];
      for (j = 0; j < n_treat; j++) {
	if (*Insample) {
	  if (Xo[i][j] == 1)
	    base[j] += (double)Y[i];
	  else
	    base[j] += (double)((dtemp+beta[j]+norm_rand()) > 0);
	} else
	  base[j] += pnorm(0, dtemp+beta[j], 1, 0, 0);
      }
      vitemp[grp[i]]++;
    }
    for (j = 0; j < n_treat; j++) 
      base[j] /= (double)n_samp;
    
    /** Storing the results **/
    if (main_loop > *iBurnin) {
      if (keep == *iKeep) {
	for (j = 0; j < (n_treat-1); j++)
	  ATE[itemp0++] = base[j+1] - base[0];
	for (j = 0; j < n_treat; j++)
	  BASE[itemp++] = base[j];
	if (*param) {
	  for (i = 0; i < n_covo; i++) 
	    coefo[itemp1++] = beta[i];
	  for (i = 0; i < n_covr; i++) 
	    coefr[itemp2++] = delta[i];
	  for (i = 0; i < n_covoR; i++)
	    for (j = i; j < n_covoR; j++)
	      sPsiO[itemp3++] = PsiO[i][j];
	  for (i = 0; i < n_covrR; i++)
	    for (j = i; j < n_covrR; j++)
	      sPsiR[itemp3++] = PsiR[i][j];
	}
	keep = 1;
      }
      else
	keep++;
    }

    if(*verbose) {
      if(main_loop == itempP) {
	Rprintf("%3d percent done.\n", progress*10);
	itempP += ftrunc((double) n_gen/10); 
	progress++;
	R_FlushConsole(); 
      }
    }
    R_CheckUserInterrupt();
  } /* end of Gibbs sampler */

  /** write out the random seed **/
  PutRNGstate();

  /** freeing memory **/
  FreeMatrix(Xr, n_samp+n_covr);
  FreeMatrix(Xo, n_samp+n_covo);
  Free3DMatrix(Zo, n_grp, *max_samp_grp + n_covoR);
  Free3DMatrix(Zr, n_grp, *max_samp_grp + n_covrR);
  FreeMatrix(PsiO, n_covoR);
  FreeMatrix(PsiR, n_covrR);
  FreeMatrix(xiO, n_grp);
  FreeMatrix(xiR, n_grp);
  FreeMatrix(S0o, n_covoR);
  FreeMatrix(S0r, n_covrR);
  FreeMatrix(Ao, n_covo);
  FreeMatrix(Ar, n_covr);
  FreeMatrix(mtemp1, n_covo);
  FreeMatrix(mtemp2, n_covr);
  free(base);
  free(cATE);
  free(vitemp);
} /* NIbprobitMixed */
コード例 #28
0
ファイル: NIstandard.c プロジェクト: cran/experiment
void NIbprobit(int *Y,         /* binary outcome variable */ 
	       int *R,         /* recording indicator for Y */
	       double *dXo,    /* covariates */
	       double *dXr,    /* covariates */
	       double *beta,   /* coefficients */
	       double *delta,  /* coefficients */
	       int *insamp,    /* # of obs */ 
	       int *incovo,    /* # of covariates */
	       int *incovr,    /* # of covariates */
	       int *intreat,   /* # of treatments */
	       double *beta0,  /* prior mean */
	       double *delta0, /* prior mean */
	       double *dAo,    /* prior precision */
	       double *dAr,    /* prior precision */
	       int *Insample,  /* insample QoI */
	       int *param,     /* store parameters? */ 
	       int *mda,       /* marginal data augmentation? */ 
	       int *ndraws,    /* # of gibbs draws */
	       int *iBurnin,   /* # of burnin */
	       int *iKeep,     /* every ?th draws to keep */
	       int *verbose,  
	       double *coefo,  /* storage for coefficients */ 
	       double *coefr,  /* storage for coefficients */ 
	       double *ATE,     /* storage for ATE */
	       double *BASE    /* storage for baseline */
	       ) {
  
  /*** counters ***/
  int n_samp = *insamp;      /* sample size */
  int n_gen = *ndraws;       /* number of gibbs draws */
  int n_covo = *incovo;      /* number of covariates */
  int n_covr = *incovr;      /* number of covariates */
  int n_treat = *intreat;    /* number of treatments */

  /*** data ***/
  /* covariates for the response model */
  double **Xr = doubleMatrix(n_samp+n_covr, n_covr+1);
  /* covariates for the outcome model */     
  double **Xo = doubleMatrix(n_samp+n_covo, n_covo+1);

  /*** model parameters ***/
  double **Ao = doubleMatrix(n_covo, n_covo);
  double **Ar = doubleMatrix(n_covr, n_covr);
  double **mtemp1 = doubleMatrix(n_covo, n_covo);
  double **mtemp2 = doubleMatrix(n_covr, n_covr);

  /*** QoIs ***/
  double *base = doubleArray(n_treat);
  double *cATE = doubleArray(n_treat);

  /*** storage parameters and loop counters **/
  int progress = 1;
  int keep = 1;
  int i, j, k, main_loop;  
  int itemp, itemp0, itemp1, itemp2, itempP = ftrunc((double) n_gen/10);
  double dtemp, pj, r0, r1;

  /*** get random seed **/
  GetRNGstate();

  /*** read the data ***/
  itemp = 0;
  for (j = 0; j < n_covo; j++)
    for (i = 0; i < n_samp; i++) 
      Xo[i][j] = dXo[itemp++];
  itemp = 0;
  for (j = 0; j < n_covr; j++)
    for (i = 0; i < n_samp; i++) 
      Xr[i][j] = dXr[itemp++];
  
  /*** read the prior and it as additional data points ***/ 
  itemp = 0;
  for (k = 0; k < n_covo; k++)
    for (j = 0; j < n_covo; j++)
      Ao[j][k] = dAo[itemp++];

  itemp = 0;
  for (k = 0; k < n_covr; k++)
    for (j = 0; j < n_covr; j++)
      Ar[j][k] = dAr[itemp++];

  dcholdc(Ao, n_covo, mtemp1);
  for(i = 0; i < n_covo; i++) {
    Xo[n_samp+i][n_covo] = 0;
    for(j = 0; j < n_covo; j++) {
      Xo[n_samp+i][n_covo] += mtemp1[i][j]*beta0[j];
      Xo[n_samp+i][j] = mtemp1[i][j];
    }
  }

  dcholdc(Ar, n_covr, mtemp2);
  for(i = 0; i < n_covr; i++) {
    Xr[n_samp+i][n_covr] = 0;
    for(j = 0; j < n_covr; j++) {
      Xr[n_samp+i][n_covr] += mtemp2[i][j]*delta0[j];
      Xr[n_samp+i][j] = mtemp2[i][j];
    }
  }

  /*** Gibbs Sampler! ***/
  itemp = 0; itemp0 = 0; itemp1 = 0; itemp2 = 0;     
  for(main_loop = 1; main_loop <= n_gen; main_loop++){

    /** Response Model: binary Probit **/    
    bprobitGibbs(R, Xr, delta, n_samp, n_covr, 0, delta0, Ar, *mda, 1);
      
    /** Outcome Model: binary probit **/
    bprobitGibbs(Y, Xo, beta, n_samp, n_covo, 0, beta0, Ao, *mda, 1);

    /** Imputing the missing data **/
    for (i = 0; i < n_samp; i++) {
      if (R[i] == 0) {
	pj = 0;
	r0 = delta[0];
	r1 = delta[1];
	for (j = 0; j < n_covo; j++) 
	  pj += Xo[i][j]*beta[j];
	for (j = 2; j < n_covr; j++) {
	  r0 += Xr[i][j]*delta[j];
	  r1 += Xr[i][j]*delta[j];
	}
	pj = pnorm(0, pj, 1, 0, 0);
	r0 = pnorm(0, r0, 1, 0, 0);
	r1 = pnorm(0, r1, 1, 0, 0);
	if (unif_rand() < ((1-r1)*pj/((1-r1)*pj+(1-r0)*(1-pj)))) {
	  Y[i] = 1;
	  Xr[i][0] = 0;
	  Xr[i][1] = 1;
	} else {
	  Y[i] = 0;
	  Xr[i][0] = 1;
	  Xr[i][1] = 0;
	} 
      }
    }
    
    /** Compute quantities of interest **/
    for (j = 0; j < n_treat; j++) 
      base[j] = 0;
    for (i = 0; i < n_samp; i++) {
      dtemp = 0; 
      for (j = n_treat; j < n_covo; j++) 
	dtemp += Xo[i][j]*beta[j];
      for (j = 0; j < n_treat; j++) {
	if (*Insample) {
	  if (Xo[i][j] == 1)
	    base[j] += (double)Y[i];
	  else
	    base[j] += (double)((dtemp+beta[j]+norm_rand()) > 0);
	} else
	  base[j] += pnorm(0, dtemp+beta[j], 1, 0, 0);
      }
    }
    for (j = 0; j < n_treat; j++) 
      base[j] /= (double)n_samp;
    
    /** Storing the results **/
    if (main_loop > *iBurnin) {
      if (keep == *iKeep) {
	for (j = 0; j < (n_treat-1); j++)
	  ATE[itemp0++] = base[j+1] - base[0];
	for (j = 0; j < n_treat; j++)
	  BASE[itemp++] = base[j];
	if (*param) {
	  for (i = 0; i < n_covo; i++) 
	    coefo[itemp1++] = beta[i];
	  for (i = 0; i < n_covr; i++) 
	    coefr[itemp2++] = delta[i];
	}
	keep = 1;
      }
      else
	keep++;
    }

    if(*verbose) {
      if(main_loop == itempP) {
	Rprintf("%3d percent done.\n", progress*10);
	itempP += ftrunc((double) n_gen/10); 
	progress++;
	R_FlushConsole(); 
      }
    }
    R_CheckUserInterrupt();
  } /* end of Gibbs sampler */

  /** write out the random seed **/
  PutRNGstate();

  /** freeing memory **/
  FreeMatrix(Xr, n_samp+n_covr);
  FreeMatrix(Xo, n_samp+n_covo);
  FreeMatrix(Ao, n_covo);
  FreeMatrix(Ar, n_covr);
  FreeMatrix(mtemp1, n_covo);
  FreeMatrix(mtemp2, n_covr);
  free(base);
  free(cATE);
} /* NIbprobit */
コード例 #29
0
ファイル: GMMMapScore2.cpp プロジェクト: kkskipper/KNOWME
//信道自适应,特征域
bool GMMMapScore::LFACompensateFeat(float * &p_pfSrcDesFeatBuf,int p_nFrmNum,
									  GMMStatistic &p_Statistic,
									  float *p_pfProbBuf,float **p_ppfProbBufBuf,float *p_pfIPPBuf_VecSize4)
{
	if(p_nFrmNum<=0||p_pfSrcDesFeatBuf==NULL)
	{
		return false;
	}

	// 分配空间
	FMatrix			AMatrix;							// m_nRankNum*m_nRankNum
	FVector			BVector,xVector;					// m_nRankNum*1
	FVector			UxVector;

	if (!AllocMatrix(AMatrix,m_nRankNum,m_nRankNum))	
		return false;
	if (!AllocVector(xVector,m_nRankNum))
	{
		FreeMatrix(AMatrix);	
		return false;
	}
	if (!AllocVector(BVector,m_nRankNum))
	{
		FreeMatrix(AMatrix);			
		FreeVector(xVector);
		return false;
	}
	if (!AllocVector(UxVector,m_nVecSize))
	{
		FreeMatrix(AMatrix);			
		FreeVector(xVector);
		FreeVector(BVector);
		return false;
	}

	ZeroMatrix(AMatrix);
	ZeroVector(BVector);
	for (int nn=0;nn<m_nRankNum;nn++)	// 初始化为I矩阵
		AMatrix.pBuf[nn*m_nRankNum+nn] = m_D.pBuf[nn];
	ResetStatisticBuf(p_Statistic);
	printf("Prob before LFA : ");
	// 计算统计量
	if (!ComputeStatistic_LFA(p_pfSrcDesFeatBuf,p_nFrmNum,p_Statistic,p_pfProbBuf,p_ppfProbBufBuf,p_pfIPPBuf_VecSize4,AMatrix,BVector))
	{
		FreeMatrix(AMatrix);
		FreeVector(BVector);
		FreeVector(xVector);
		FreeVector(UxVector);
		return false;
	}
	
	// 计算信道因子
	if (!Compute_X(AMatrix,BVector,xVector))
	{
		FreeMatrix(AMatrix);
		FreeVector(BVector);
		FreeVector(xVector);
		FreeVector(UxVector);
		return false;
	}

	// 特征转换
	for(int m=0;m<m_nMixNum;m++)
	{
		ZeroVector(UxVector);
		for(int d=0;d<m_nVecSize;d++)
		{
			for(int r=0;r<m_nRankNum;r++)
				UxVector.pBuf[d] += m_V.pBlockBuf[m][d*m_nRankNum+r]*xVector.pBuf[r];
		}
		for(int t=0;t<p_nFrmNum;t++)
		{
			if (p_ppfProbBufBuf[m][t]<1.0e-5)	continue;
			
			for(int d=0;d<m_nVecSize;d++)
			{
				p_pfSrcDesFeatBuf[t*m_nVecSizeStore+d] -= p_ppfProbBufBuf[m][t]*UxVector.pBuf[d];
			}
		}
	}
	printf("Prob after LFA : ");
	//xxiao add for debug
//	ComputeStatistic_LFA(p_pfSrcDesFeatBuf,p_nFrmNum,p_Statistic,p_pfProbBuf,p_ppfProbBufBuf,p_pfIPPBuf_VecSize4,AMatrix,BVector);
	// 释放空间
	FreeMatrix(AMatrix);
	FreeVector(BVector);
	FreeVector(xVector);
	FreeVector(UxVector);

	return true;
}
コード例 #30
0
SMatrix ReadSparse(char *name, char *probName)
{
	FILE *fp;
	long n, m, i, j;
	long n_rows, tmp;
	long numer_lines;
	long colnum, colsize, rownum, rowsize;
	char buf[100], type[4];
	SMatrix M, F;

	if (!name || name[0] == 0) {
		fp = stdin;
	} else {
		fp = fopen(name, "r");
	}

	if (!fp) {
		Error("Error opening file\n");
	}

	fscanf(fp, "%72c", buf);

	fscanf(fp, "%8c", probName);
	probName[8] = 0;
	DumpLine(fp);

	for (i=0; i<5; i++) {
	  fscanf(fp, "%14c", buf);
	  sscanf(buf, "%ld", &tmp);
	  if (i == 3)
	    numer_lines = tmp;
	}
	DumpLine(fp);

	fscanf(fp, "%3c", type);
	type[3] = 0;
	if (!(type[0] != 'C' && type[1] == 'S' && type[2] == 'A')) {
	  fprintf(stderr, "Wrong type: %s\n", type);
	  exit(0);
	}

	fscanf(fp, "%11c", buf); /* pad */

	fscanf(fp, "%14c", buf); sscanf(buf, "%ld", &n_rows);

	fscanf(fp, "%14c", buf); sscanf(buf, "%ld", &n);

	fscanf(fp, "%14c", buf); sscanf(buf, "%ld", &m);

	fscanf(fp, "%14c", buf); sscanf(buf, "%ld", &tmp);
	if (tmp != 0)
	  printf("This is not an assembled matrix!\n");
	if (n_rows != n)
	  printf("Matrix is not symmetric\n");
	DumpLine(fp);

	fscanf(fp, "%16c", buf);
	ParseIntFormat(buf, &colnum, &colsize);
	fscanf(fp, "%16c", buf);
	ParseIntFormat(buf, &rownum, &rowsize);
	fscanf(fp, "%20c", buf);
	fscanf(fp, "%20c", buf);
		
	DumpLine(fp); /* format statement */

	M = NewMatrix(n, m, 0);

	ReadVector(fp, n+1, M.col, colnum, colsize);

	ReadVector(fp, m, M.row, rownum, rowsize);

	for (i=0; i<numer_lines; i++) /* dump numeric values */
	  DumpLine(fp);

	for (i=0; i<n; i++)
		ISort(M, i);

	for (i=0; i<=n; i++)
	  M.startrow[i] = M.col[i];

	fclose(fp);

	F = LowerToFull(M);

	maxm = 0;
	for (i=0; i<n; i++)
	  if (F.col[i+1]-F.col[i] > maxm)
	    maxm = F.col[i+1]-F.col[i];

	if (F.nz) {
	  for (j=0; j<n; j++)
	    for (i=F.col[j]; i<F.col[j+1]; i++)
	      F.nz[i] = Value(F.row[i], j);
	}

	FreeMatrix(M);

	return(F);
}