Exemplo n.º 1
0
// 掛け算
int mat_mul(matrix *mat1, matrix mat2, matrix mat3){
  int i, j, k;
  matrix mat2_w, mat3_w;
  
  if(check_mul(*mat1, mat2, mat3) != 0){
    printf("%s\n", "エラーが発生しました。");
    return -1;
  }

  mat_alloc(&mat2_w, mat2.row, mat2.col);
  mat_alloc(&mat3_w, mat3.row, mat3.col);
  mat_copy(&mat2_w, mat2);
  mat_copy(&mat3_w, mat3);
  
  for(i=0; i < mat1->row; i++){
    for(j=0; j < mat1->col; j++){
      mat1->element[i][j] = 0;

      for(k=0; k<mat2_w.col; k++){
        mat1->element[i][j] += mat2_w.element[i][k] * mat3_w.element[k][j];
      }
    }
  }

  mat_free(&mat2_w);
  mat_free(&mat3_w);
  
  return 0;
}
Exemplo n.º 2
0
//行列からk列のみを取り出す
struct matrix *get_col(struct matrix *p,int k){
  int i;
  struct matrix *v;
  v=mat_alloc(p->row,1);
  for(i=0;i<p->row;i++) *(v->element+i)=*(p->element+k+i*p->col);
  return(v);
}
Exemplo n.º 3
0
//行列からk行のみを取り出す
struct matrix *get_row(struct matrix *p,int k){
  int i;
  struct matrix *v;
  v=mat_alloc(1,p->col);
  for(i=0;i<p->col;i++) *(v->element+i)=*(p->element+i+k*p->col);
  return(v);
}
Exemplo n.º 4
0
void ObjRecICP::doICP(ObjRecRANSAC& objrec, list<PointSetShape*>& detectedShapes)
{
	vtkPoints* scene_points = objrec.getInputScene();
	double p[3], mat[4][4], icp_mat[4][4], **model2scene = mat_alloc(4, 4), **scene2model = mat_alloc(4, 4);
	list<int>::iterator id;
	int i;

#ifdef OBJ_REC_RANSAC_VERBOSE
	printf("ICP refinement "); fflush(stdout);
#endif

	for ( list<PointSetShape*>::iterator it = detectedShapes.begin() ; it != detectedShapes.end() ; ++it )
	{
		// Get the shape
		PointSetShape *shape = *it;
		// This one will contain the shape points
		vtkPoints *shape_points = vtkPoints::New(VTK_DOUBLE), *out = vtkPoints::New(VTK_DOUBLE);
		  shape_points->SetNumberOfPoints((*it)->getScenePointIds().size());

		for ( i = 0, id = shape->getScenePointIds().begin() ; id != shape->getScenePointIds().end() ; ++id, ++i )
		{
			// Get the scene point
			scene_points->GetPoint(*id, p);
			// Insert the scene point to the shape point set
			shape_points->SetPoint(i, p);
		}

		// Invert the model to scene transformation
		shape->getHomogeneousRigidTransform(model2scene);
		mat_invert_rigid_transform4x4((const double**)model2scene, scene2model);

		// Use the model as target
		this->setTarget(shape->getPolyData());
		// Register the shape points to the model
		this->doRegistration(shape_points, out, mat, INT_MAX/*max iterations*/, (const double**)scene2model);

		// Invert the result such that we have again the model to scene transformation
		mat_invert_rigid_transform4x4(mat, icp_mat);
		// Save the result in the shape
		shape->setHomogeneousRigidTransform(icp_mat);

		// Cleanup
		shape_points->Delete();
		out->Delete();

#ifdef OBJ_REC_RANSAC_VERBOSE
		printf("."); fflush(stdout);
#endif
	}
#ifdef OBJ_REC_RANSAC_VERBOSE
	printf(" done\n"); fflush(stdout);
#endif

	// Cleanup
	mat_dealloc(model2scene, 4);
	mat_dealloc(scene2model, 4);
}
Exemplo n.º 5
0
//単位行列を作る(さらにk倍する)
struct matrix *mat_uni(int n,double k){
  struct matrix *p;
  int i;
  p=mat_alloc(n,n);
  for(i=0;i<n;i++){
    *(p->element+i+i*n)=k;
  }
  return(p);
}
Exemplo n.º 6
0
void *replicates(void *param)
{
    Params p;
    memcpy(&p, ((pth*)param)->p, sizeof(Params));

    // get the threads parameters
    //---------------------------
    int poolsize = (p.sizevalues)[(p.pos_var)[0]];
    double fert = (p.fertvalues)[(p.pos_var)[1]];
    int rep = ((pth*)param)->id;
    printf("\n%d",rep);

    // create a subset of the regional pool
    //-------------------------------------
    double **regpool = (double**)mat_alloc(poolsize,21,sizeof(double));
    if(p.pooltype)
    {
        create_assembled_pool(&p,regpool,poolsize,fert);
    }
    else
    {
        create_random_pool(&p,regpool,poolsize);
        interaction_random_pool(regpool,poolsize);
    }

    // print the regional species pool
    //--------------------------------
    char filename1[100];
    sprintf(filename1, "%s/S%d_F%.2f_REP%d_regpool.txt",p.folder,poolsize,fert,rep);
    print_regional_pool(regpool,poolsize,21,filename1);


    // run the assembly sequence replication (with print outputs)
    //-----------------------------------------------------------
    for(int seq = 1 ; seq <= p.nseq ; ++seq)
    {
        // create the filename parameter part
        //-----------------------------------
	char filename2[100];
	sprintf(filename2,"%s/S%d_F%.2f_REP%d_SEQ%d",p.folder,poolsize,fert,rep,seq);

	// run the assembly sequence (and print the outputs)
	//--------------------------------------------------
	assembly_run(&p,fert,regpool,poolsize,filename2);
    }


    // Free the memory
    //----------------
    mat_free((void**)regpool,poolsize);
    free(param);

    return NULL;

}
Exemplo n.º 7
0
int main(void){
  int i,j,k,step;
  char filename[20]="matrix1.txt";
  struct matrix *p,*q,*r;
  double err;
  FILE *gp;
  srand((unsigned)time(NULL));
  r=mat_read(filename);
  M=r->row;N=r->col;
  p=mat_test(mat_alloc(M,K),0,1,10000);
  q=mat_test(mat_alloc(K,N),0,1,10000);

  printf("R\n");mat_print(r);
  printf("P\n");mat_print(p);
  printf("Q\n");mat_print(q);

  for(step=0;step<STEP;step++){
    for(i=0;i<M;i++){
      for(j=0;j<N;j++){
	if(*(r->element+j+i*r->col)==0)continue;
	err=rating_er(*(r->element+j+i*r->col),p,q,i,j);
	for(k=0;k<K;k++){
	  *(p->element+k+i*p->col)
	    +=ALPHA*(2*err* *(q->element+j+k*q->col)-BETA* *(p->element+k+i*p->col));
	  *(q->element+j+k*q->col)
	    +=ALPHA*(2*err* *(p->element+k+i*p->col)-BETA* *(q->element+j+k*q->col));
	}
      }
    }
    if((step%100)==0){
      //printf("%f \n",get_er(r,p,q));
      if(get_er(r,p,q)<THT){printf("step %d\n",step);break;}
    }
  }
  printf("========================\n");
  printf("error=%f\n",get_er(r,p,q));
  printf("P\n"); mat_print(p);
  printf("Q\n");mat_print(q);
  printf("P*Q\n");mat_print(mat_mul(p,q));

  return(0);
}
Exemplo n.º 8
0
void ObjRecRANSAC::sampleOrientedPointPairs(OctreeNode** leaves1, int numOfLeaves, list<OrientedPair>& pairs)
{
	OctreeNode *leaf2;
	ORROctreeNodeData *data1, *data2;
	const double *point1, *point2, *normal1, *normal2;

	// Compute the maximal number of neighbor leaves:
	int tmp = 2*mNormalEstimationNeighRadius + 1;
	int i, maxNumOfNeighbours = tmp*tmp*tmp;
	// Reserve memory for the max number of neighbors
	double** pca_pts = mat_alloc(3, maxNumOfNeighbours);

#ifdef OBJ_REC_RANSAC_VERBOSE
	printf("ObjRecRANSAC::%s(): sample pairs ... ", __func__); fflush(stdout);
#endif

	for ( i = 0 ; i < numOfLeaves ; ++i )
	{
		// Get the first leaf (from the randomly sampled array of leaves)
		data1 = (ORROctreeNodeData*)leaves1[i]->getData();

		// Estimate the node normal if necessary
		normal1 = this->estimateNodeNormal(pca_pts, leaves1[i], data1);

		if ( !normal1 )
			continue;
		// Get the node point
		point1 = data1->getPoint();

		// Randomly select a leaf at the right distance
		leaf2 = mSceneOctree->getRandomFullLeafOnSphere(point1, mPairWidth);
		if ( !leaf2 )
			continue;
		data2 = (ORROctreeNodeData*)leaf2->getData();

		// Estimate the node normal if necessary
		normal2 = this->estimateNodeNormal(pca_pts, leaf2, data2);

		if ( !normal2 )
			continue;
		// Get the node point
		point2 = data2->getPoint();

		// Save the sampled point pair
		pairs.push_back(OrientedPair(point1, normal1, point2, normal2));
	}

#ifdef OBJ_REC_RANSAC_VERBOSE
	printf("done.\n"); fflush(stdout);
#endif

	// Cleanup
	mat_dealloc(pca_pts, 3);
}
Exemplo n.º 9
0
/* matrix mathematical operations */
mat mat_trn(mat m)
{
    unsigned i, j;
    mat t;
    t=mat_alloc(m.c, m.r);
    t.r=m.c;
    t.c=m.r;
    for(i=0; i<m.r; ++i)
        for(j=0; j<m.c; ++j)
            *mat_indx(t, j, i)=*mat_indx(m, i, j);
    return t;
}
Exemplo n.º 10
0
mat mat_cpy(mat m)
{
    unsigned i, j;
    mat t;
    if(!(t=mat_alloc(m.r, m.c)).r) return t;
    t.r=m.r;
    t.c=m.c;
    for(i=0; i<m.r; ++i)
        for(j=0; j<m.c; ++j)
            *mat_indx(t, i, j)=*mat_indx(m, i, j);
    return t;
}
Exemplo n.º 11
0
mat mat_realloc(mat m, unsigned r, unsigned c)
{
    unsigned i, j;
    mat t;
    if(!(t=mat_alloc(r, c)).r) return t;
    t.r=r;
    t.c=c;
    for(i=0; i<m.r && i<r; ++i)
        for(j=0; j<m.c && j<c; ++j)
            *mat_indx(t, i, j)=*mat_indx(m, i, j);
    mat_free(m);
    return t;
}
Exemplo n.º 12
0
//転置行列
struct matrix *mat_trans(struct matrix *a){
  int i,j;
  struct matrix *a_tra;

  if(a==NULL){printf("error at mat_trans:input is NULL");return NULL;}
  a_tra=mat_alloc(a->col,a->row);

  for(i=0;i<a->row;i++){
    for(j=0;j<a->col;j++){
      *(a_tra->element+i+j*a->row)=*(a->element+j+i*a->col);
    }
  }
  return(a_tra);
}
Exemplo n.º 13
0
//行列をコピー
struct matrix *mat_copy(struct matrix *a){
  struct matrix *p;
  int i,j;

  p=mat_alloc(a->row,a->col);
  p->row=a->row;
  p->col=p->col;
  for(i=0;i<a->row;i++){
    for(j=0;j<a->col;j++){
      *(p->element+j+i*a->col)=*(a->element+j+i*a->col);
    }
  }
  return(p);
}
Exemplo n.º 14
0
//引き算 aからbを引く
struct matrix *mat_sub(struct matrix *a,struct matrix *b){
  int i,j;
  struct matrix *c;
  if(a->row!=b->row){printf("error at mat_sub:row ab\n");return NULL;}
  if(a->col!=b->col){printf("error at mat_sub:col ab\n");return NULL;}
  c=mat_alloc(a->row,a->col);

  for(i=0;i<a->row;i++){
    for(j=0;j<a->col;j++){
      *(c->element+j+i*a->col) = 
	*(a->element+j+i*a->col) - *(b->element+j+i*a->col);
    }
  }
  return(c);
}
Exemplo n.º 15
0
mat mat_mul(mat m1, mat m2)
{
    unsigned i, j, k;
    mat t;
    if(m1.c!=m2.r){
        t.r=t.c=0;
        return t;
    }
    if(!(t=mat_alloc(m1.r, m2.c)).r) return t;
    for(i=0; i<m1.r; ++i)
        for(j=0; j<m2.c; ++j)
            for(k=*mat_indx(t, i, j)=0; k<m2.r; ++k)
                *mat_indx(t, i, j)+=*mat_indx(m1, i, k)**mat_indx(m2, k, j);
    return t;
}
Exemplo n.º 16
0
mat mat_sub(mat m1, mat m2)
{
    unsigned i, j;
    mat t;
    if(m1.r!=m2.r || m1.c!=m2.c){
        t.r=t.c=0;
        return t;
    }
    t=mat_alloc(m1.r, m1.c);
    t.r=m1.r;
    t.c=m1.c;
    for(i=0; i<m1.r; ++i)
        for(j=0; j<m1.c; ++j)
            *mat_indx(t, i, j)=*mat_indx(m1, i, j)-*mat_indx(m2, i, j);
    return t;
}
Exemplo n.º 17
0
int mat_inverse(matrix *mat1, matrix mat2){
  matrix square;

  if(check_square(mat2) != 0 || check_square(*mat1) != 0){
    return -1;
  }

  mat_alloc(&square, mat2.row, mat2.col);
  mat_unit(&square);

  mat_solve(mat1, mat2, square);

  mat_print(square);
  mat_print(mat2);
  mat_print(*mat1);

  return 0;
}
Exemplo n.º 18
0
//掛け算 a,bを掛ける
struct matrix *mat_mul(struct matrix *a,struct matrix *b){
  int i,j,k;
  double temp=0;
  struct matrix *c;

  if((a==NULL)||(b==NULL))
    {printf("error at mat_mul;input is NULL\n");return NULL;}
  if(a->col!=b->row){printf("error at mat_mul;a->col!=b->row\n");return NULL;}
  c=mat_alloc(a->row,b->col);

  for(i=0;i<a->row;i++){
    for(j=0;j<b->col;j++){
      for(k=0;k<a->col;k++){
	temp+=*(a->element+k+i*a->col) * *(b->element+j+k*b->col);
      }
      *(c->element+j+i*c->col)=temp;
      temp=0;
    }
  }
  return(c);
}
Exemplo n.º 19
0
//行列をファイルから読み込み
struct matrix *mat_read(char *filename){
  FILE *fp;
  int m,n,k;
  double d;
  struct matrix *p;

  if((fp=fopen(filename,"r"))==NULL){
    fprintf(stderr,"can't open %s\n",filename);
    return(NULL);
  }
  fscanf(fp,"%d %d",&m,&n);
  p=mat_alloc(m,n);

  k=0;
  while(fgetc(fp)!=EOF){
    if(k>=m*n)break;
    fscanf(fp,"%lf",&d);
    *(p->element+k)=d;
    k++;
  }
  return(p);
}
Exemplo n.º 20
0
// 転置行列を返す
int mat_trans(matrix *mat1, matrix mat2){
  int i, j;
  matrix mat2_w;

  if(check_trans(*mat1, mat2) != 0){
    printf("%s\n", "エラーが発生しました。");
    return -1;
  }

  mat_alloc(&mat2_w, mat2.row, mat2.col);
  mat_copy(&mat2_w, mat2);
  
  for(i=0; i < mat1->row; i++){
    for(j=0; j < mat1->col; j++){
      mat1->element[i][j] = mat2_w.element[j][i];
    }
  }

  mat_free(&mat2_w);

  return 0;
}
Exemplo n.º 21
0
//逆行列(はき出し法)a_oriの逆行列
struct matrix *mat_inv(struct matrix *a_ori){
  int i,j,k,m,n;
  double d,dd;
  struct matrix *a;
  struct matrix *a_inv;

  if(a_ori==NULL){ printf("error at mat_inv:input is NULL\n");return NULL;}
  if(a_ori->row!=a_ori->col){printf("error at mat_inv:a_ori\n");return NULL;}
  a_inv=mat_alloc(a_ori->row,a_ori->col);

  a=mat_copy(a_ori);
  for(i=0;i<a->row;i++){
    for(j=0;j<a->row;j++){
      if(i==j)*(a_inv->element+j+i*a->col)=1;
      else *(a_inv->element+j+i*a->col)=0;
    }
  }

  for(i=0;i<a->row;i++){
    d=*(a->element+i+i*a->col);
    for(j=0;j<a->row;j++){
      *(a->element+j+i*a->col)=(1/d)* *(a->element+j+i*a->col);
      *(a_inv->element+j+i*a->col)=(1/d)* *(a_inv->element+j+i*a->col);
    }
    for(k=0;k<a->row;k++){
      if(i!=k){
	dd=*(a->element+i+k*a->col);
	for(n=0;n<a->row;n++){
          *(a->element+n+k*a->col)=
	    *(a->element+n+k*a->col)- dd * *(a->element+n+i*a->col);
	  *(a_inv->element+n+k*a->col)=
	    *(a_inv->element+n+k*a->col)-dd * *(a_inv->element+n+i*a->col);
	}
      }
    }
  }
  return(a_inv);
}
Exemplo n.º 22
0
void assembly_run(Params *p, double nfert, double **regpool, int poolsize, char *folder, char *replicate_identity)
{
    // Define and initialize the history and ecosystem lists
    //------------------------------------------------------
    sll history;
    sll_init(&history,(void*)free_seq);
    sll ecosys;
    sll_init(&ecosys,(void*)free_species);

    // create the basal resources
    //---------------------------
    basal(p,&ecosys,nfert);


    // create and initialize the presence matrix (ne pas oublier de mettre les espèces au minimum pour l'invasion)
    //------------------------------------------
    unsigned int **presence = (unsigned int**)mat_alloc(2,poolsize,sizeof(unsigned int));
    for(int i = 0 ; i < poolsize ; ++i)
    {
        presence[0][i] = regpool[i][1];
        presence[1][i] = 0;
    }

    // get the initial values of the sequence
    //---------------------------------------
    seqlevel *seq0 = fill_seq(&ecosys,0,0);
    seq0->success = 0;
    sll_add_head(&history,seq0);

    // assemble until any species can install (or all are already installed)
    //----------------------------------------------------------------------
    int a = poolsize + EAM_NBNUT + EAM_NBDET;                              /* expected ecosystem size */
    int stop_endcycles = poolsize * EAM_STOP_ENDCYCLE;                     /* variable to stop the sequence if infinite */
    int endcycles = 0;                                                     /* 0 if endpoint / 1 if endcycle */ 
    int unsucc = EAM_STOP;                                                 /* check the success of the invader */
    int invasion = 1;                                                      /* invasion number */

    while(ecosys.length != a)
    {
        int b = get_int(p->rng,0,poolsize);                                /* select randomly the number of the species in the regional pool */
        if(presence[1][b] == 0)                                            /* if the species is not already in the ecosystem */
	{
	    ParamSP *sp = (ParamSP*)malloc(sizeof(ParamSP));
	    tr_sp_struct(regpool[b],sp);
	    install_process(p,&ecosys,sp);                                  /* install the species */
	    seqlevel *seq = fill_seq(&ecosys,invasion,presence[0][b]);      /* create and initialize a sequence node */
	    sll_rm(&ecosys,extinct_condition);                              /* remove the extincted species */
	    presence_absence(&ecosys,presence,poolsize);                    /* fill the presence-absence matrix */
	    unsucc = (presence[1][b] == 0) ? unsucc-1 : EAM_STOP;          /* upgrade the counter of unsuccessfull installations */
	    seq->success =  presence[1][b];                                /* fill the success of invader installation in the sequence node */
	    sll_add_head(&history,seq);                                    /* add the sequence node to the assembly history */
	    ++invasion;                                                    /* upgrade the invasion number */
	    --stop_endcycles;                                              /* upgrade the endcycle detector */
	}
	if(unsucc == 0) break;
        if(stop_endcycles == 0)                                              /* break the loop if its an endcycle */
	{
	    endcycles = 1;
	    break;
	}
    }


    // print the outputs : subpool / final community / sequence / abundances history / identity history
    //------------------
    print_final_community(&ecosys,folder,replicate_identity);
    print_id_history(&history,poolsize,folder,replicate_identity);
    print_final_biomasses_history(&history,poolsize,folder,replicate_identity);
    print_sequence(&history,folder,replicate_identity);
    char *buffer = (char*)malloc(100);
    sprintf(buffer, "%s/%s_endcycle.txt",folder,replicate_identity);
    FILE *out = fopen(buffer,"w");
    fprintf(out,"%d",endcycles);
    fclose(out);

    // free the memory
    //----------------
    mat_free((void**)presence,2);
    sll_rm_all(&history);
    sll_rm_all(&ecosys);
    free(buffer);

}
Exemplo n.º 23
0
/*Command line entry point of the program*/
int main (int argc, char* argv[]){
    
    /*getopt() variables */
    int   opt;
	char* optarg_dup = NULL;
    
    /*Command line options*/
	uchar cflg=0,gflg=0,kflg=0,lflg=0,mflg=0,oflg=0, sflg=0;
	uchar pflg=0,tflg=0,vflg=0,xflg=0,zflg=0;
    InputParams* inputParams = NULL;

    /*Working variables */
	int            i,m;
	int            nbPriors;
    int            nbNodes;
	int            nbClass;
	int            nbLabeled;
	int            nbUnlabeled;
	int			   nbSimParams;
	int            actualWlen;
	int            start_cpu,stop_cpu;
	real           tmp;
	uchar*         absorbing     = NULL;
	char*          labels        = NULL;
	char*          featLabels    = NULL;
	char*          targets       = NULL;
	char*		   preds         = NULL;
	int**          classes       = NULL;
	real**         N             = NULL;
	real*          gram          = NULL;
    real**         latF          = NULL;
    real**         latB          = NULL;
	real**		   kernel		 = NULL;
	SparseMatrix*  spmat         = NULL;
	SparseMatrix*  dataset       = NULL;
	DataStat*      graphStat     = NULL;
	DataStat*      featuresStat  = NULL;
	DWInfo*        dwInfo        = NULL;
	OptiLen*       optiLen       = NULL;
	PerfMeasures*  unlabeledPerf = NULL;
	LSVMDataInfo*  dataInfo      = NULL;
	
	/*Print the program banner*/
	printBanner();

    /*Scan the command line*/
	inputParams = malloc(sizeof(InputParams));
	init_InputParams(inputParams);
	while ((opt = getopt(argc,argv,"c:g:l:xms:k:o:p:rt:v:z:h")) != EOF){
        switch(opt){
	        case 'c':
	            cflg++;
				inputParams->nbFolds = atoi(optarg);
	            break;
            case 'g':
                gflg++;
				inputParams->graphFname = (char*)malloc(FNAME_LEN*sizeof(char));
				strncpy(inputParams->graphFname,optarg,FNAME_LEN);
                break;
            case 'k':
				kflg++;
				inputParams->gramFname = (char*)malloc(FNAME_LEN*sizeof(char));
				strncpy(inputParams->gramFname,optarg,FNAME_LEN);
                break;
			case 's':
                sflg++;
                optarg_dup  = (char*)__strdup(optarg);
				nbSimParams = getNbTokens(optarg,",");
				inputParams->simParams = vec_alloc(nbSimParams+1);
				tokenizeReals(optarg_dup,",",inputParams->simParams);
				break;
            case 'l':
                lflg++;
                inputParams->wlen = atoi(optarg);
                break;
			case 'm':
				mflg++;
				break;
            case 'o':
                oflg++;
				inputParams->outFname = (char*)malloc(FNAME_LEN*sizeof(char));
				strncpy(inputParams->outFname,optarg,FNAME_LEN);
				inputParams->outPRED  = (char*)malloc(FNAME_LEN*sizeof(char));
				inputParams->outLEN   = (char*)malloc(FNAME_LEN*sizeof(char));
                addExtension(inputParams->outFname,"pred",inputParams->outPRED);
				addExtension(inputParams->outFname,"len",inputParams->outLEN);
                break;
            case 'p':
                pflg++;
                optarg_dup = (char*)__strdup(optarg);
				nbPriors   = getNbTokens(optarg,"#");
                inputParams->priors = vec_alloc(nbPriors+1);
				tokenizeReals(optarg_dup,"#",inputParams->priors);
                break;
			case 't':
				tflg++;
				inputParams->tarFname = (char*)malloc(FNAME_LEN*sizeof(char));
				strncpy(inputParams->tarFname,optarg,FNAME_LEN);
				break;
            case 'v':
                vflg++;
                inputParams->verbose = atoi(optarg);
                break;
			case 'x':
				xflg++;
				inputParams->crossWalks = 1;
				break;
			case 'z':
				zflg++;
				inputParams->cvSeed = atoi(optarg);
				break;
            case 'h':
                printHelp();
                exit(EXIT_FAILURE);
                break;
        }
    }
    
    /*Check mandatory arguments*/
    if(!gflg || !lflg || (!oflg && !mflg)){
        fprintf(stderr,"Mandatory argument(s) missing\n");
        printHelp();
        exit(EXIT_FAILURE);
    }

	if( (kflg && !sflg) || (!kflg && sflg)){
		fprintf(stderr, "Error with 'k' and 's' parameters\n");
		printHelp();
		exit(EXIT_FAILURE);
	}

	/*Check that the walk length is greater than 2*/
	if(inputParams->wlen < 2){
		fprintf(stderr,"The walkLen must be >= 2\n");
		exit(EXIT_FAILURE);
	}

	/*Check that there are the right number of similarity parameters*/
	if (kflg && sflg){
		if(inputParams->simParams){
			switch((int)inputParams->simParams[1]){
				case 1 :
					if((int)inputParams->simParams[0] != 1){
						fprintf(stderr,"The similarity type 1 must have no parameters\n");
						exit(EXIT_FAILURE);	
					}
					break;
				case 2 :
					if((int)inputParams->simParams[0] != 2){
						fprintf(stderr,"The similarity type 2 must have exactly 1 parameter\n");
						exit(EXIT_FAILURE);	
					}
					break;
				case 3 :
					if((int)inputParams->simParams[0] != 4){
						fprintf(stderr,"The similarity type 3 must have exactly 3 parameters\n");
						exit(EXIT_FAILURE);	
					}
					break;
				case 4 :
					if((int)inputParams->simParams[0] != 2){
						fprintf(stderr,"The similarity type 4 must have exactly 1 parameter\n");
						exit(EXIT_FAILURE);	
					}
					break;
				default :
					fprintf(stderr,"Unrecognized similarity type\n");
					exit(EXIT_FAILURE);	
			}
		}
	}

    /*Get the number of nodes in the graph*/
    nbNodes = readNbNodes(inputParams->graphFname);
    
	/*Get the number of distinct classes*/
	nbClass = readNbClass(inputParams->graphFname);

	/*Get info from the LIBSVM data*/
	if (kflg){
		dataInfo = malloc(sizeof(LSVMDataInfo));
		getLSVMDataInfo(inputParams->gramFname,dataInfo);
		dataset = spmat_alloc(dataInfo->nbLines,dataInfo->nbFeatures,0);
		init_SparseMat(dataset);
		featuresStat = DataStat_alloc(dataInfo->nbClass);
		featLabels = char_vec_alloc(nbNodes);
	}
	
	/*Check if the number of nodes does not exceed the limitation*/
	if(nbNodes > MAX_NODES){
		fprintf(stderr,"This version is limited to maximum %i nodes\n",MAX_NODES);
		exit(EXIT_FAILURE);
	}

	/*Check that the number of classes is lower than 128*/
	if(nbClass > 127){
		fprintf(stderr,"The number of classes must be <= 127\n");
		exit(EXIT_FAILURE);		
	}

	/*Check that the number of folds is between 2 and nbNodes*/
	if(cflg){
		if(inputParams->nbFolds == 1 || inputParams->nbFolds > nbNodes){
			fprintf(stderr,"The number of folds must be > 1 and <= number of nodes\n");
			exit(EXIT_FAILURE);
		}
	}

    /*Allocate data structure*/
    latF             = mat_alloc(inputParams->wlen+1,nbNodes);
    latB             = mat_alloc(inputParams->wlen+1,nbNodes);
	kernel			 = mat_alloc(nbNodes, nbNodes);
	classes          = (int**)malloc(sizeof(int*)*(nbClass+1));
	labels           = char_vec_alloc(nbNodes);
	absorbing        = uchar_vec_alloc(nbNodes);
	if(kflg) gram    = vec_alloc((nbNodes*(nbNodes+1))/2);
	dwInfo           = malloc(sizeof(DWInfo));
	dwInfo->mass_abs = vec_alloc(nbClass);
	spmat            = spmat_alloc(nbNodes,nbNodes,1);
	graphStat        = DataStat_alloc(nbClass+1);
	optiLen          = malloc(sizeof(OptiLen));
	
    /*Initialize the sparse transition matrix and the dataset if required*/
	init_SparseMat(spmat);

    /*Read the adjacency matrix*/
    readMat(inputParams->graphFname,spmat,labels,graphStat,inputParams->verbose);
    isSymmetric(spmat);

	/*Get the indices of the nodes in each class */
	getClasses(labels,nbNodes,classes,nbClass);

	/*Get the number of labeled nodes*/
	nbUnlabeled = classes[0][0];
	nbLabeled   = nbNodes - nbUnlabeled;

	/*If provided, check that the priors match the number of classes*/
	if(pflg){
		if(nbClass != nbPriors){
			printf("The number of priors does not match with the number of classes\n");
			exit(EXIT_FAILURE);			
		}
		/*Check that the priors sum up to 1*/
		else{
			tmp=0.0;
			for(i=1;i<=inputParams->priors[0];i++){
				tmp += inputParams->priors[i];
			}
			if(ABS(tmp-1.0) > PROB_EPS){
				textcolor(BRIGHT,RED,BLACK);
	            printf("WARNING: The class priors do not sum up to 1\n");
				textcolor(RESET,WHITE,BLACK);
			}
		}
	}
	/*If no priors provided, use empirical priors */
	else{
		inputParams->priors = vec_alloc(nbClass+1);
		inputParams->priors[0] = (real)nbClass;
		tmp = 0.0;
		for(i=1;i<=inputParams->priors[0];i++)
			tmp += graphStat->classCount[i];
		for(i=1;i<=inputParams->priors[0];i++)
			inputParams->priors[i] = (real)graphStat->classCount[i]/tmp;
	}

	/*If provided read the LIBSVM feature matrix*/
	if(kflg){
		m = readLSVMData(inputParams->gramFname,dataInfo,dataset,featLabels,featuresStat,inputParams->verbose);
		if (dataInfo->nbLines != nbNodes){
			fprintf(stderr,"Number of line on the LIBSVM (%i) file doesn't match the number of nodes (%i)\n", dataInfo->nbLines, nbNodes);
			exit(EXIT_FAILURE);
		}
		
		/* Multiply a kernel matrix based on the dataset*/
		/* TO DO : define a parameters to lower the importance of the features*/
		buildKernel2(spmat, dataset, 0.1, inputParams);
		/*Multiply adjacency matrix*/
	}

	
    
    /*Print statistics about the graph, classes, and run-mode*/
    if (inputParams->verbose > 0)
		printInputInfo(spmat,graphStat,nbClass,inputParams);               
    
	/*Minimum Covering Length mode*/
	if (mflg){
		computeMCL(spmat,absorbing,labels,classes,nbClass,latF,latB,inputParams);
		/*Exit after displaying the statistics*/
		exit(EXIT_SUCCESS);		
	}

	 /*Start the CPU chronometer*/
    start_cpu = clock();

	/*If required tune the maximum walk length by cross-validation*/
	if(cflg){
		crossValidateLength(spmat,absorbing,labels,classes,nbClass,NULL,latF,latB,inputParams,optiLen);
		actualWlen = optiLen->len;
	}
	/*Otherwise use the prescribed length*/
	else
		actualWlen = inputParams->wlen;

	/************************ALGORITHM STARTS HERE****************************/

	if(inputParams->verbose >= 1){
		textcolor(BRIGHT,RED,BLACK);
		printf("Performing discriminative walks up to length %i on full data\n",actualWlen);
		textcolor(RESET,WHITE,BLACK);
	}

	/*Allocate data structure*/
    N     = mat_alloc(nbUnlabeled,nbClass);
	preds = char_vec_alloc(nbUnlabeled);
    init_mat(N,nbUnlabeled,nbClass);

	/*Launch the D-walks*/
	dwalk(spmat,absorbing,classes,nbClass,N,latF,latB,actualWlen,inputParams->crossWalks,dwInfo,inputParams->verbose);

	/************************ALGORITHM STOPS HERE****************************/

    /*Stop the CPU chronometer*/
    stop_cpu = clock();
    
	/*Compute the predictions as the argmax on classes for each unlabeled node*/
	computePredictions(N,preds,inputParams->priors,nbUnlabeled,nbClass);

	/*Write the model predictions*/
	writePredictions_unlabeled(inputParams->outPRED,preds,N,nbClass,classes[0]);

	/*Write the class betweeness */


	/*If a target file is provided compare predictions and targets*/
	if(tflg){
		unlabeledPerf = PerfMeasures_alloc(nbClass+1);
		computeUnlabeledPerf(preds,classes[0],nbUnlabeled,nbClass,inputParams,unlabeledPerf,inputParams->verbose);
		free_PerfMeasures(unlabeledPerf,nbClass+1);
	}
    /*Print informations*/
    if (inputParams->verbose >= 1){
		for(i=0;i<nbClass;i++)
			printf("Exploration rate in class %2i : %1.2f %%\n",i+1,100*dwInfo->mass_abs[i]);
		printf("CPU Time (sec)               : %1.4f\n",((double)(stop_cpu - start_cpu)/CLOCKS_PER_SEC));
		printLineDelim();	
    }

	/*Optionally release memory here*/
	#ifdef FREE_MEMORY_AT_END
		free_classes(classes,nbClass+1);
		free_InputParams(inputParams);
		free_DataStat(graphStat);
		free_DWInfo(dwInfo);
		free(absorbing);
		free(labels);
		free_mat(N,nbUnlabeled);
		free_mat(latF,inputParams->wlen+1);
		free_mat(latB,inputParams->wlen+1);
		free_SparseMatrix(spmat);
		free(optiLen);
		free(preds);
		if(kflg) free(gram);
	#endif

    /*Exit successfully :-)*/
    exit(EXIT_SUCCESS);
}
Exemplo n.º 24
0
int main()
{
    unsigned r1, c1, r2, c2, ch;
    mat m1, m2, t;

    puts("Enter row and column numbers of matrices 1 and 2:");
    scanf(" %u %u %u %u%*c", &r1, &c1, &r2, &c2);
    putchar('\n');

    m1=mat_alloc(r1, c1);
    m2=mat_alloc(r2, c2);

    printf("Enter value of Matrix 1 (%ux%u):\n", r1, c1);
    mat_read(m1);
    putchar('\n');
    printf("Enter value of Matrix 2 (%ux%u):\n", r2, c2);
    mat_read(m2);
    putchar('\n');

    do{
        puts("What would you like to do?");
        puts(" ( 0) Exit");
        puts(" ( 1) Display");
        puts(" ( 2) Transpose");
        puts(" ( 3) Sum");
        puts(" ( 4) Difference");
        puts(" ( 5) Product");
        puts(" ( 6) Greatest Element of Rows");
        puts(" ( 7) Sum of Major Diagonal");
        puts(" ( 8) Sum of Minor Diagonal");
        puts(" ( 9) Check Symmetricity");
        puts(" (10) Upper-Triangular Matrix");
        puts(" (11) Lower-Triangular Matrix");
        scanf(" %u%*c", &ch);
        switch(ch){
        case 0:
            puts("Bye!");
            break;
        case 1:
            puts("Matrix 1:");
            mat_write(m1);
            putchar('\n');
            puts("Matrix 2:");
            mat_write(m2);
            break;
        case 2:
            t=mat_trn(m1);
            mat_write(t);
            mat_free(t);
            break;
        case 3:
            if((t=mat_add(m1, m2)).r){
                mat_write(t);
                mat_free(t);
            }
            else puts("Not Possible");
            break;
        case 4:
            if((t=mat_sub(m1, m2)).r){
                mat_write(t);
                mat_free(t);
            }
            else puts("Not Possible");
            break;
        case 5:
            if((t=mat_mul(m1, m2)).r){
                mat_write(t);
                mat_free(t);
            }
            else puts("Not Possible");
            break;
        case 6:
            row_great(m1);
            break;
        case 7:
            add_major(m1);
            break;
        case 8:
            add_minor(m1);
            break;
        case 9:
            if(issymm(m1)) puts("Symmetric");
            else puts("Unsymmetric");
            break;
        case 10:
            up_tri(m1);
            break;
        case 11:
            lo_tri(m1);
            break;
        default:
            puts("Incorrect Choice!");
            break;
        }
        putchar('\n');
    } while(ch);

    mat_free(m1);
    mat_free(m2);
    return 0;
}
Exemplo n.º 25
0
// アレする
int mat_solve(matrix *mat1, matrix mat2, matrix mat3){
  int i, j, k, l;
  double multiplier, divisor;
  matrix a, b;

  if(check_square(mat2) != 0 || mat2.row != mat3.row || mat1->row != mat3.row || mat1->col != mat3.col ){
    return -1;
  }
  
  mat_alloc(&a, mat2.row, mat2.col);
  mat_alloc(&b, mat3.row, mat3.col);

  mat_copy(&a, mat2);
  mat_copy(&b, mat3);

  mat_print(a);
  mat_print(b);


// Gaussの消去法
  for(i=0; i<a.row; i++){
    // i+1行目以降のi列目を消す(i=0のとき、2行目〜最終行の1列目を消去)
    for(j=i+1; j<a.row; j++){
      // j行目に、i行目を何倍したら、i列目が消えるか(例えば、i=0のとき、2行目以降の行全体に、何倍すれば、1列目が0になるか)
      multiplier = a.element[j][i] / a.element[i][i];
      for(k=0; k<a.col; k++){
        a.element[j][k] = a.element[j][k] - a.element[i][k] * multiplier;
      }

      for(l=0; l<b.col; l++){
        b.element[j][l] = b.element[j][l] - b.element[i][l] * multiplier;
      }
    }

  }

// 後退代入

  // 最終行以前の行に対して
  for(i=a.row-1; i>=0; i--){

    // 例えば、今2行目なら、3列目〜最終列に対して処理を行う
    for(j=a.row-1; j>i; j--){
      divisor = a.element[i][j];
      a.element[i][j] = a.element[i][j] - divisor * a.element[j][j];
      for(l=0; l<b.col; l++){
        b.element[i][l] = b.element[i][l] - divisor * b.element[j][l];
      }
    }

    for(l=0; l<b.col; l++){
      b.element[i][l] = b.element[i][l] / a.element[i][i];
    }
    a.element[i][i] = 1.0;
  }
  mat_copy(mat1, b);

  mat_free(&a);
  mat_free(&b);

  return 0;
}
Exemplo n.º 26
0
void treatments(void *param, unsigned long s)
{
    //------------//
    // LOCAL COPY //
    //------------//
    Params *P = (Params*)param;


    //------------------------------------------------------//
    // OPEN A NEW FOLDER AND SAVE THE REGIONAL POOL SPECIES //
    //------------------------------------------------------//
    char *buffer = (char*)malloc(100);
    sprintf(buffer, "SIMU_%lu",s);
    mkdir(buffer, S_IRWXU); // S_IRWXU is the mode, it give read/write/search access to the user.
    print_global_parameters(P, s,buffer);

    //-----------------//
    // TREATMENT LOOPS //
    //-----------------//

    char buffer2[100];

    for(int i = 0 ; i < P->nsize ; ++i) // SIZE POOL LOOP
    {
        for(int j = 0 ; j < P->nfert ; ++j) // FERTILITY LOOP
	{
	    for(int k = 1 ; k <= P->nrep ; ++k) // REPLICATE LOOP
	    {
		// create a subset of the regional pool
	        //-------------------------------------
		double **regpool = (double**)mat_alloc((P->sizevalues)[i],21,sizeof(double));
		if(P->pooltype)
		{
		    create_assembled_pool(P,regpool,(P->sizevalues)[i],(P->fertvalues)[j]);
		}
		else
		{
		    create_random_pool(P,regpool,(P->sizevalues)[i]);
		    interaction_random_pool(regpool,(P->sizevalues)[i]);
		}


		// print the regional species pool
		//--------------------------------
      		char filename1[100];
		sprintf(filename1, "%s/S%d_F%.2f_REP%d_regpool.txt",buffer,(P->sizevalues)[i],(P->fertvalues)[j],k);
		print_regional_pool(regpool,(P->sizevalues)[i],21,filename1);


		// run the assembly sequence replication (with print outputs)
		//-----------------------------------------------------------
		for(int seq = 1 ; seq <= P->nseq ; ++seq)
		{
		    // create the filename parameter part
		    //-----------------------------------
		    char filename2[100];
		    sprintf(filename2,"%s/S%d_F%.2f_REP%d_SEQ%d",buffer,(P->sizevalues)[i],(P->fertvalues)[j],k,seq);

		    // run the assembly sequence (and print the outputs)
		    //--------------------------------------------------
		    assembly_run(P,(P->fertvalues)[j],regpool,(P->sizevalues)[i],filename2);
		}


		// Free the memory
		//----------------
		mat_free((void**)regpool,(P->sizevalues)[i]);

	    } // END REPLICATE LOOP
	} // END FERTILITY LOOP
    } // END SIZE POOL LOOP


    //-----------------//
    // Free the memory //
    //-----------------//
    free(buffer);

}
Exemplo n.º 27
0
matrix_t * mpi_mat_rand(
  idx_t const mode,
  idx_t const nfactors,
  permutation_t const * const perm,
  rank_info * const rinfo)
{
  idx_t const localdim = rinfo->mat_end[mode] - rinfo->mat_start[mode];
  matrix_t * mymat = mat_alloc(localdim, nfactors);

  MPI_Status status;

  /* figure out buffer sizes */
  idx_t maxlocaldim = localdim;
  if(rinfo->rank == 0) {
    MPI_Reduce(MPI_IN_PLACE, &maxlocaldim, 1, SPLATT_MPI_IDX, MPI_MAX, 0,
      rinfo->comm_3d);
  } else {
    MPI_Reduce(&maxlocaldim, NULL, 1, SPLATT_MPI_IDX, MPI_MAX, 0,
      rinfo->comm_3d);
  }

  /* root rank does the heavy lifting */
  if(rinfo->rank == 0) {
    /* allocate buffers */
    idx_t * loc_perm = splatt_malloc(maxlocaldim * sizeof(*loc_perm));
    val_t * vbuf = splatt_malloc(maxlocaldim * nfactors * sizeof(*vbuf));

    /* allocate initial factor */
    matrix_t * full_factor = mat_rand(rinfo->global_dims[mode], nfactors);

    /* copy root's own matrix to output */
    #pragma omp parallel for schedule(static)
    for(idx_t i=0; i < localdim; ++i) {
      idx_t const gi = rinfo->mat_start[mode] + perm->iperms[mode][i];
      for(idx_t f=0; f < nfactors; ++f) {
       mymat->vals[f + (i*nfactors)] = full_factor->vals[f+(gi*nfactors)];
      }
    }

    /* communicate! */
    for(int p=1; p < rinfo->npes; ++p) {
      /* first receive layer start and permutation info */
      idx_t layerstart;
      idx_t nrows;
      MPI_Recv(&layerstart, 1, SPLATT_MPI_IDX, p, 0, rinfo->comm_3d, &status);
      MPI_Recv(&nrows, 1, SPLATT_MPI_IDX, p, 1, rinfo->comm_3d, &status);
      MPI_Recv(loc_perm, nrows, SPLATT_MPI_IDX, p, 2, rinfo->comm_3d, &status);

      /* fill buffer */
      #pragma omp parallel for schedule(static)
      for(idx_t i=0; i < nrows; ++i) {
        idx_t const gi = layerstart + loc_perm[i];
        for(idx_t f=0; f < nfactors; ++f) {
          vbuf[f + (i*nfactors)] = full_factor->vals[f+(gi*nfactors)];
        }
      }

      /* send to rank p */
      MPI_Send(vbuf, nrows * nfactors, SPLATT_MPI_VAL, p, 3, rinfo->comm_3d);
    }

    mat_free(full_factor);
    splatt_free(loc_perm);
    splatt_free(vbuf);

  /* other ranks just send/recv */
  } else {
    /* send permutation info to root */
    MPI_Send(&(rinfo->layer_starts[mode]), 1, SPLATT_MPI_IDX, 0, 0, rinfo->comm_3d);
    MPI_Send(&localdim, 1, SPLATT_MPI_IDX, 0, 1, rinfo->comm_3d);
    MPI_Send(perm->iperms[mode] + rinfo->mat_start[mode], localdim,
        SPLATT_MPI_IDX, 0, 2, rinfo->comm_3d);

    /* receive factor */
    MPI_Recv(mymat->vals, mymat->I * mymat->J, SPLATT_MPI_VAL, 0, 3,
        rinfo->comm_3d, &status);
  }

  return mymat;
}
Exemplo n.º 28
0
void mpi_write_mats(
  matrix_t ** mats,
  permutation_t const * const perm,
  rank_info const * const rinfo,
  char const * const basename,
  idx_t const nmodes)
{
  char * fname;
  idx_t const nfactors = mats[0]->J;

  MPI_Status status;

  idx_t maxdim = 0;
  idx_t maxlocaldim = 0;
  matrix_t * matbuf = NULL;
  val_t * vbuf = NULL;
  idx_t * loc_iperm = NULL;

  for(idx_t m=0; m < nmodes; ++m) {
    maxdim = SS_MAX(maxdim, rinfo->global_dims[m]);
    maxlocaldim = SS_MAX(maxlocaldim, mats[m]->I);
  }

  /* get the largest local dim */
  if(rinfo->rank == 0) {
    MPI_Reduce(MPI_IN_PLACE, &maxlocaldim, 1, SPLATT_MPI_IDX, MPI_MAX, 0,
      rinfo->comm_3d);
  } else {
    MPI_Reduce(&maxlocaldim, NULL, 1, SPLATT_MPI_IDX, MPI_MAX, 0,
      rinfo->comm_3d);
  }

  if(rinfo->rank == 0) {
    matbuf = mat_alloc(maxdim, nfactors);
    loc_iperm = (idx_t *) splatt_malloc(maxdim * sizeof(idx_t));
    vbuf = (val_t *) splatt_malloc(maxdim * nfactors * sizeof(val_t));
  }

  for(idx_t m=0; m < nmodes; ++m) {
    /* root handles the writing */
    if(rinfo->rank == 0) {
      asprintf(&fname, "%s%"SPLATT_PF_IDX".mat", basename, m+1);
      matbuf->I = rinfo->global_dims[m];

      /* copy root's matrix to buffer */
      for(idx_t i=0; i < mats[m]->I; ++i) {
        idx_t const gi = rinfo->layer_starts[m] + perm->iperms[m][i];
        for(idx_t f=0; f < nfactors; ++f) {
          matbuf->vals[f + (gi*nfactors)] = mats[m]->vals[f+(i*nfactors)];
        }
      }

      /* receive matrix from each rank */
      for(int p=1; p < rinfo->npes; ++p) {
        idx_t layerstart;
        idx_t nrows;
        MPI_Recv(&layerstart, 1, SPLATT_MPI_IDX, p, 0, rinfo->comm_3d, &status);
        MPI_Recv(&nrows, 1, SPLATT_MPI_IDX, p, 0, rinfo->comm_3d, &status);
        MPI_Recv(vbuf, nrows * nfactors, SPLATT_MPI_VAL, p, 0, rinfo->comm_3d,
            &status);
        MPI_Recv(loc_iperm, nrows, SPLATT_MPI_IDX, p, 0, rinfo->comm_3d, &status);

        /* permute buffer and copy into matbuf */
        for(idx_t i=0; i < nrows; ++i) {
          idx_t const gi = layerstart + loc_iperm[i];
          for(idx_t f=0; f < nfactors; ++f) {
            matbuf->vals[f + (gi*nfactors)] = vbuf[f+(i*nfactors)];
          }
        }
      }

      /* write the factor matrix to disk */
      mat_write(matbuf, fname);

      /* clean up */
      free(fname);
    } else {
      /* send matrix to root */
      MPI_Send(&(rinfo->layer_starts[m]), 1, SPLATT_MPI_IDX, 0, 0, rinfo->comm_3d);
      MPI_Send(&(mats[m]->I), 1, SPLATT_MPI_IDX, 0, 0, rinfo->comm_3d);
      MPI_Send(mats[m]->vals, mats[m]->I * mats[m]->J, SPLATT_MPI_VAL, 0, 0,
          rinfo->comm_3d);
      MPI_Send(perm->iperms[m] + rinfo->mat_start[m], mats[m]->I, SPLATT_MPI_IDX,
          0, 0, rinfo->comm_3d);
    }
  } /* foreach mode */


  if(rinfo->rank == 0) {
    mat_free(matbuf);
    free(vbuf);
    free(loc_iperm);
  }
}