Example #1
0
/*** DEFINITIONS ***/
int main(int argc, char **argv)
{

/* local variables */
  FILE *problem_input, *problem_output;
  FILE *interactive_input, *interactive_output;
  FILE *grains;
  char grains_name[200];
  char problem_input_name[300], problem_output_name[300];
  char interactive_input_name[300];
  char interactive_output_name[300], tmp[100];
  char field_name[300];
  int problem_id;
  char c, arg[100], arg2[100], arg3[100]; /* string variable to read menu */
  int i, j,k, iaux, jaux, iprob, icount;
  int lel[100], nreq, iel, base_q;
  int field_id, mesh_id;
  double daux, eaux, t_wall, t_wall2, t_wall3;
  int max_gen, max_gen_diff;
  int nrno, nmno, nred, nmed, nrfa, nmfa, nrel, nmel;
  int indeks=0;
  int licznik,nel,nmaxel;
  double *x,*y,*z,*xa,*ya,*za;
  int *nrgrain,*elemgr;
  int *tmpfer,liczfer;
  double tmpx,tmpy,tmpz;
  int el_nodes[MMC_MAXELVNO+1];        // list of nodes of El
  double node_coor[3*MMC_MAXELVNO];  // coord of nodes of El
  double p[3];
  int spr,spr2,flag;
  double hsize, min, mn;
  int neig[6],neig2[6],matl,tmpnel,matl2,max,*counter,anc;
  double xs,ys,zs;
  int zxs,zys,zzs,zxa,zya,zza;
#ifdef PARALLEL
  int info;
#endif

   //arrays for grains

   x=(double *)calloc(1000000,sizeof(double));
   y=(double *)calloc(1000000,sizeof(double));
   z=(double *)calloc(1000000,sizeof(double));
   xa=(double *)calloc(1000000,sizeof(double));
   ya=(double *)calloc(1000000,sizeof(double));
   za=(double *)calloc(1000000,sizeof(double));
   nrgrain=(int *)calloc(1000000,sizeof(int));
   tmpfer=(int *)calloc(1000000,sizeof(int));

  /*++++++++++++++++ executable statements ++++++++++++++++*/

    /* very simple - for the beginning instead of GUI */
    if(argv[1]==NULL){
  	strcpy(work_dir,".");
    } else {
  	sprintf(work_dir,"%s",argv[1]);
    }

    utr_set_interactive(work_dir, argc, argv,
			&interactive_input, &interactive_output);

  #ifdef DEBUG
    fprintf(interactive_output,"Starting program in debug mode.\n");
  #endif
  #ifdef DEBUG_MMM
    fprintf(interactive_output,"Starting mesh module in debug mode.\n");
  #endif
  #ifdef DEBUG_APM
    fprintf(interactive_output,"Starting approximation module in debug mode.\n");
  #endif
  #ifdef DEBUG_SIM
    fprintf(interactive_output,"Starting solver interface in debug mode.\n");
  #endif
  #ifdef DEBUG_LSM
    fprintf(interactive_output,"Starting linear solver (adapter) module in debug mode.\n");
  #endif

  /*++++ initialization of problem, mesh and field data ++++*/
    problem_id=pdr_init_problem(work_dir, interactive_input, interactive_output);

  /*++++++++++++ main menu loop ++++++++++++++++++++++++++++*/
  do {

#ifdef PARALLEL
    if(pcr_my_proc_id()==pcr_print_master()){
#endif

    if(interactive_input == stdin){


      do {
	/* define a menu */
	printf("\nChoose a command from the menu:\n");
	printf("\ts - solve test problem - Laplace's quation \n");
	printf("\tp - postprocessing\n");
	printf("\te - compute error\n");
	printf("\tm - perform manual mesh adaptation \n");
	printf("\ta - perform automatic mesh adaptation \n");
	printf("\td - dump out data \n");
	printf("\tr - perform random test of h-adaptivity\n");
	if(pdv_problem.gr.en==1)
		printf("\tg - solve grains\n");
	printf("\tq - exit the program\n");

	scanf(" %c",&c);
      } while ( c != 'm' && c != 'd' && c != 'r' && c != 'g'
		&& c != 's' && c != 'e' && c != 'p'
		&& c != 'a' && c != 'q' && c != 'q' );

    } else{

      // read control data from interactive_input file
      fscanf(interactive_input,"%c\n",&c);

    }

#ifdef PARALLEL
    }

    pcr_bcast_char(pcr_print_master(),1,&c);
    //printf("After BCAST %c\n",c);

#endif


    if(c=='g'){

		j=0;

#ifdef PARALLEL
    if(pcr_my_proc_id()==pcr_print_master()){
#endif
		printf("Compute grains\n");
#ifdef PARALLEL
    }
#endif
		k=0;
		for(licznik=0;licznik<680;licznik+=10)
		{
				//problem_id=pdr_init_problem(work_dir, interactive_input, interactive_output);
#ifdef PARALLEL
    if(pcr_my_proc_id()==pcr_print_master()){
#endif
				printf("\nIteration=%d\n",licznik);
#ifdef PARALLEL
    }
#endif
				sprintf(grains_name,"%s/przemiana/iteration_%d.txti", work_dir,licznik);
//				grains = fopen(grains_name,"r");
//
//				if(grains==NULL)
//				{
//					printf("Unable to open grains file for %d iteration - make sure that you have 'przemiana' directory!!\n",licznik);
//					exit(-1);
//				}
//
//				utr_skip_rest_of_line(grains);//
//
//				for(i=0;i<90000;i++)
//					fscanf(grains,"%d %d %d %d\n",&tmpx,&tmpy,&nrgrain[i],&tmpfer);
//
//				fclose(grains);
//
//				max=nrgrain[0];
//				for(i=0;i<90000;i++)
//				{
//					if(nrgrain[i]>=max)
//						max=nrgrain[i];
//				}
//				//printf("max=%d\n",max);
//				counter=(int *)calloc(max+2,sizeof(int));
//				for(i=0;i<90000;i++)
//				{
//					counter[nrgrain[i]]++;
//				}
//				for(i=1;i<=max;i++)
//				{
//					printf("ziarno %d wystepuje %d razy\n",i,counter[i]);
//				}


				grains = fopen(grains_name,"r");
				if(grains==NULL)
				{
					printf("Unable to open grains file for %d iteration - make sure that you have 'przemiana' directory!!\n",licznik);
					exit(-1);
				}
				utr_skip_rest_of_line(grains);
				mn=pdv_problem.gr.multip;

				liczfer=0;
				for(i=0;i<90000;i++)
				{
						fscanf(grains,"%lf %lf %d %d\n",&tmpx,&tmpy,&nrgrain[i],&tmpfer[i]);
						if((tmpfer[i]==0))//&&(counter[nrgrain[i]]>4))
						{
							x[liczfer]=tmpx/mn;
							y[liczfer]=299/mn-tmpy/mn;
							liczfer++;
						}
						xa[i]=tmpx/mn;
						ya[i]=299/mn-tmpy/mn;
				}
				//printf("Ferrite grains for iteration %d - %d\n",licznik,liczfer);

				fclose(grains);

				elemgr=(int *)calloc(mmr_get_max_elem_id(mesh_id)+1,sizeof(int));

				nel=0;
				spr=0;
				while((nel=mmr_get_next_act_elem(mesh_id, nel))!=0)
				{
						mmr_el_node_coor(mesh_id,nel,el_nodes,node_coor);
						flag=0;
						for(i=0;i<liczfer;i++)
						{
							p[0]=x[i];
							p[1]=y[i];
							p[2]=0;
							spr=pointintriangle(p,&node_coor[0],&node_coor[3],&node_coor[6]);
							if(spr==1)
							{
								flag=1;
							}
						}
						if(flag==0)
						{
							spr=0;
							for(i=0;i<90000;i++)
							{
								p[0]=xa[i];
								p[1]=ya[i];
								p[2]=0;
								spr+=pointintriangle(p,&node_coor[0],&node_coor[3],&node_coor[6]);
							}
							if(spr==0)
							{
								flag=3;
							}
						}

						if(flag==1)
						{
							mmr_el_set_mate(mesh_id,nel,2);
						}
						else if(flag==0)
						{
							mmr_el_set_mate(mesh_id,nel,1);
						}
						else
						{
							xs=node_coor[0]+node_coor[3]+node_coor[6];
							xs=xs/3;
							xs=xs*mn;
							ys=node_coor[1]+node_coor[4]+node_coor[7];
							ys=ys/3;
							ys=ys*mn;
							zxs=round(xs);
							zys=round(ys);
							for(i=0;i<90000;i++)
							{
								zxa=round(xa[i]*mn);
								zya=round(ya[i]*mn);
								if((zxa==zxs)&&(zya==zys))
								{
									//printf("xa[%d]=%lf ya[%d]=%lf\n",zxa,xa[i],zya,ya[i]);
									if(tmpfer[i]==1)
										mmr_el_set_mate(mesh_id,nel,1);
									else
										mmr_el_set_mate(mesh_id,nel,2);
								}
							}

						}

						for(i=0;i<90000;i++)
						{
							p[0]=xa[i];
							p[1]=ya[i];
							p[2]=0;
							spr=pointintriangle(p,&node_coor[0],&node_coor[3],&node_coor[6]);
							if(spr==1)
							{
								elemgr[nel]=nrgrain[i];
							}
						}
						/*
						if(k==0)
							min=mmr_el_hsize(mesh_id,nel,NULL,NULL,NULL);
						hsize=mmr_el_hsize(mesh_id,nel,NULL,NULL,NULL);
						if(hsize<min)
							min=hsize;
						//printf("Element %d nalezy do ziarna %d\n",nel,elemgr[nel]);
						k++;
						/**/
				}
				/*
				printf("Min=%lf\n",min);
				getchar();
				/**/

				//solve
				sprintf(arg,"%s/solver.dat", work_dir);
				if(licznik==0)
				{
					 //t_wall2=time_clock();
					 sir_solve_lin_sys(problem_id, SIC_SEQUENTIAL, arg, -2, -2, -2, 2);
					 //t_wall2=time_clock()-t_wall2;
					 if(pdv_problem.gr.err==1)
					 {
						 pdr_get_zzhu_error(field_id);
					 	 pdr_free_list();
					 }
					 if(pdv_problem.gr.save==2||(pdv_problem.gr.save%10)==2||(pdv_problem.gr.save/10)==2)
					 {
						 sprintf(arg3, "%s/all_merged_grains_%d.vtu", work_dir,licznik);
						 utr_write_paraview_std_lin(mesh_id, field_id, arg3);
						 //mergeParaviewMeshAndField(mesh_id, field_id, arg3);
					 }
					 if(pdv_problem.gr.save==3||(pdv_problem.gr.save%10)==3||(pdv_problem.gr.save/10)==3)
					 {
						 sprintf(arg3, "%s/grains_%d.mesh", work_dir,licznik);
						 writeGrains(mesh_id,field_id,elemgr,licznik,arg3);
					 }

				}
				if(j!=liczfer&&licznik!=0)
				{
					 //t_wall2=time_clock();
					printf("wejście=%d\n",licznik);
					 sir_solve_lin_sys(problem_id, SIC_SEQUENTIAL, arg, -2, -2, -2, 2);
					 printf("wyjście!!\n");

					 //t_wall2=time_clock()-t_wall2;

					 if(pdv_problem.gr.err==1)
					 {
						 pdr_get_zzhu_error(field_id);
						 pdr_free_list();
					 }
					 if(pdv_problem.gr.save==2||(pdv_problem.gr.save%10)==2||(pdv_problem.gr.save/10)==2)
					 {
						 sprintf(arg3, "%s/all_merged_grains_%d.vtu", work_dir,licznik);
						 utr_write_paraview_std_lin(mesh_id, field_id, arg3);
						 //mergeParaviewMeshAndField(mesh_id, field_id, arg3);
					 }
					 if(pdv_problem.gr.save==3||(pdv_problem.gr.save%10)==3||(pdv_problem.gr.save/10)==3)
					 {
						 sprintf(arg3, "%s/grains_%d.mesh", work_dir,licznik);
						 writeGrains(mesh_id,field_id,elemgr,licznik,arg3);
					 }
					 if(pdv_problem.gr.adpt==1)
					 {
						 //t_wall=t_wall3=time_clock();
						 	 pdr_adapt(field_id);
						 //t_wall=time_clock()-t_wall;
						 pdr_free_list();
						 while(pdr_constr(field_id)!=5);
						 //t_wall3=time_clock()-t_wall3;
					 }
					 if(pdv_problem.gr.adpt==2)
					 {
						 pdr_adapt2(field_id);
						 pdr_free_list();

						 /*Adaptacja wielokrotna*/
						 /*
						 int nrbef=mmr_get_nr_node(mesh_id);
						 //printf("nrbef=%d\n",nrbef);
						 int nrafter=0;
						 while(nrafter!=nrbef)
						 {
							 nrbef=mmr_get_nr_node(mesh_id);
							 pdr_adapt2(field_id);
							 pdr_free_list();
							 sir_solve_lin_sys(problem_id, SIC_SEQUENTIAL, arg);
							 nrafter=mmr_get_nr_node(mesh_id);
							 //printf("nrafter=%d\n",nrafter);
							 //getchar();
						 }
						 /**/
						 //if(licznik==670)
						 while(pdr_constr(field_id)!=5);
					 }
					 if(pdv_problem.gr.adpt==3)
					 {
						 pdr_adapt2(field_id);
						 pdr_free_list();
						 sir_solve_lin_sys(problem_id, SIC_SEQUENTIAL, arg, -2, -2, -2, 2);
						 pdr_adapt(field_id);
						 pdr_free_list();
						 while(pdr_constr(field_id)!=5);
				 }
				}
				else if(j==liczfer)
				{
					 t_wall2=time_clock();
					 printf("wejście2=%d\n",licznik);
					 sir_solve_lin_sys(problem_id, SIC_SEQUENTIAL, arg, -2, -2, -2, 2);
					 t_wall2=time_clock()-t_wall2;

					 if(pdv_problem.gr.err==1)
					 {
						 pdr_get_zzhu_error(field_id);
					 	 pdr_free_list();
					 }
					 if(pdv_problem.gr.save==2||(pdv_problem.gr.save%10)==2||(pdv_problem.gr.save/10)==2)
					 {
						 sprintf(arg3, "%s/all_merged_grains_%d.vtu", work_dir,licznik);
						 utr_write_paraview_std_lin(mesh_id, field_id, arg3);
						 //mergeParaviewMeshAndField(mesh_id, field_id, arg3);
					 }
					 if(pdv_problem.gr.save==3||(pdv_problem.gr.save%10)==3||(pdv_problem.gr.save/10)==3)
					 {
						 sprintf(arg3, "%s/grains_%d.mesh", work_dir,licznik);
						 writeGrains(mesh_id,field_id,elemgr,licznik,arg3);
					 }
				}

				j=liczfer;
				//printf("\nCzas adaptacji: %lf\nCzas adaptacji z usuwaniem constr: %lf\nCzas obliczen: %lf\n",t_wall,t_wall3,t_wall2);
		}//licznik

    }
    else if(c=='d'){

      sprintf(arg,"%s/mesh_prism.dmp", work_dir);
      iaux = mmr_export_mesh(mesh_id, MMC_MOD_FEM_MESH_DATA, arg);
      if(iaux<0) {
	/* if error in writing data */
      fprintf(interactive_output,"Error in writing mesh data!\n");
      }
      sprintf(arg,"%s/field_std_lin.dmp", work_dir);
      iaux = apr_write_field(field_id, nreq,-1,0.000000001, arg);
      if(iaux<0) {
	/* if error in writing data */
      fprintf(interactive_output,"Error in writing field data!\n");
      }

      if(pdv_problem.inv==1)  //write stress invariants
    	  pdr_write_sigma(field_id);

      sprintf(arg3, "%s/paraview_%d.vtu", work_dir,indeks);
      utr_write_paraview_std_lin(mesh_id, field_id, arg3);

         //constraints remove
         //while(pdr_constr(field_id)!=5);

         sprintf(arg3, "%s/grains3D_%d.mesh", work_dir,indeks);
         writeGrains3Dconstr(mesh_id,field_id,elemgr,licznik,arg3);

    }
    else if(c=='s'){
      indeks++;
      printf("Start\n");
      if(pdv_problem.gr.en==1)
      {
    	  if(indeks==1)
    	  {
    		  printf("Wczytuję!\n");
			  //grains = fopen("data_3D.txt","r");
    		  grains = fopen("data_3D_small.txt","r");
			  if(grains==NULL)
			  {
				 printf("Unable to open grains file - make sure that you have 'data_3D' file!\n");
				 exit(-1);
			  }
			  //utr_skip_rest_of_line(grains);
			  mn=pdv_problem.gr.multip;

			  liczfer=0;
			  //for(i=0;i<1000000;i++)
			  for(i=0;i<125000;i++)
			  {
				  fscanf(grains,"%lf %lf %lf %d\n",&tmpx,&tmpy,&tmpz,&tmpfer[i]);
//				  if((tmpfer[i]==3))
//				  {
//					 x[liczfer]=tmpx;
//					 y[liczfer]=tmpy;
//					 z[liczfer]=tmpz;
//					 liczfer++;
//				  }
				  xa[i]=tmpx;
				  ya[i]=tmpy;
				  za[i]=tmpz;
				  //if(i==0)
					//  printf("Wczytane: xa[i]=%lf,ya[i]=%lf,za[i]=%lf",xa[i],ya[i],za[i]);
			  }
			  //printf("Ferrite grains - %d\n",liczfer);

			  fclose(grains);
    	  }

    	  elemgr=(int *)calloc(mmr_get_max_elem_id(mesh_id)+1,sizeof(int));

    	  printf("Setting material data\n");
    	  printf("\n");
    	  nel=0;
    	  nmaxel=mmr_get_max_elem_id(mesh_id);

//    	  while((nel=mmr_get_next_act_elem(mesh_id, nel))!=0)
//    	  {
//    		  mmr_el_set_mate(mesh_id,nel,-1);
//    		  //printf("%d\r",nel/nmaxel*100);
//    		  spr=0;
//    		  spr2=0;
//    		  mmr_el_node_coor(mesh_id,nel,el_nodes,node_coor);
////    		  for(i=0;i<18;i++)
////    		  {
////    			  printf("Node %d - %lf\n",i/3,node_coor[i]);
////    		  }
////    		  printf("\n");
//
//    		  flag=0;
//    	  	  for(i=0;i<liczfer;i++)
//    	  	  {
//    	  		 p[0]=x[i];
//    	  		 p[1]=y[i];
//    	  		 p[2]=0;
//    	  		 spr=pointintriangle(p,&node_coor[0],&node_coor[3],&node_coor[6]);
//    	  		 if(spr==1)
//    	  		   if(z[i]>node_coor[2] && z[i]<node_coor[11])
//   	  		       {
//   	  			      //spr2=1;
//   	  			      //printf("z[i]=%lf,node_coor[2,11]=%lf,%lf!\n",z[i],node_coor[2],node_coor[11]);
//   	  		          flag=1;
//    	  			  //printf("Punkt %lf,%lf,%lf należy do elementu %d o wspolrzednych trojkat: a=%lf,%lf,b=%lf,%lf,c=%lf,%lf ,czworokat - %lf,%lf\n",x[i],y[i],z[i],nel,node_coor[0],node_coor[1],node_coor[3],node_coor[4],node_coor[6],node_coor[7],node_coor[2],node_coor[11]);
//    	  		   }
//    	  	  }
//    	  	  if(flag==0)
//    	  	  {
//    	  		 spr=0;
//    	  		 spr2=0;
//    	  		 //for(i=0;i<1000000;i++)
//    	  		 for(i=0;i<125000;i++)
//    	  		 {
//    	  			p[0]=xa[i];
//    	  			p[1]=ya[i];
//    	  			p[2]=0;
//    	  			spr+=pointintriangle(p,&node_coor[0],&node_coor[3],&node_coor[6]);
//    	  		 }
//    	  		 if(spr==0)
//    	  		 {
//    	  			flag=3;
//    	  			//printf("flag=3 dla elementu %d o wspolrzednych - trojkat: (%lf %lf %lf),(%lf %lf %lf),(%lf %lf %lf),czworokat - %lf,%lf\n",nel,node_coor[0],node_coor[1],node_coor[2],node_coor[3],node_coor[4],node_coor[5],node_coor[6],node_coor[7],node_coor[8],node_coor[2],node_coor[11]);
//    	  		 }
//    	  	  }
//
//    	  	  if(flag==1)
//    	  	  {
//    	  		 mmr_el_set_mate(mesh_id,nel,2);
//    	  		 elemgr[nel]=2;
//    	  	  }
//    	  	  else if(flag==0)
//    	  	  {
//    	  		 mmr_el_set_mate(mesh_id,nel,1);
//    	  		 elemgr[nel]=1;
//    	  	  }
//    	  	  else
//    	  	  {
//    	  		mmr_el_set_mate(mesh_id,nel,3);
//    	  		//elemgr[nel]=1;
////    	  		 xs=node_coor[0]+node_coor[3]+node_coor[6];
////    	  		 xs=xs/3;
////    	  		 xs=xs*mn;
////    	  		 ys=node_coor[1]+node_coor[4]+node_coor[7];
////    	  		 ys=ys/3;
////    	  		 ys=ys*mn;
////    	  		 zs=node_coor[2]+node_coor[11];
////    	  		 zs=zs/2;
////    	  		 zs=zs*mn;
////    	  		 zxs=round(xs);
////    	  		 zys=round(ys);
////    	  		 zzs=round(zs);
////    	  		 //for(i=0;i<1000000;i++)
////    	  		 //if(nel==69324)
////    	  		 //{
////    	  		//	 printf("xs=%lf,ys=%lf,zs=%lf,zxs=%d,zys=%d,zzs=%d\n",xs,ys,zs,zxs,zys,zzs);
////    	  		 //}
////
////    	  		 for(i=0;i<125000;i++)
////    	  		 {
////    	  			zxa=round(xa[i]*mn);
////    	  			zya=round(ya[i]*mn);
////    	  			zza=round(za[i]*mn);
////    	  			//if(nel==69324&&i==0)
////    	  			//	printf("xa[i]=%lf,ya[i]=%lf,za[i]=%lf,zxa=%d zya=%d zza=%d\n",xa[i],ya[i],za[i],zxa,zya,zza);
////    	  			if((zxa==zxs)&&(zya==zys)&&(zza==zzs))
////    	  			{
////    	  			   //printf("xa[%d]=%lf ya[%d]=%lf za[%d]=%lf\n",zxa,xa[i],zya,ya[i],zza,za[i]);
////    	  			   if(tmpfer[i]==2)
////    	  			   {
////    	  				   mmr_el_set_mate(mesh_id,nel,1);
////    	  				   elemgr[nel]=1;
////    	  			   }
////    	  			   else
////    	  			   {
////    	  				   mmr_el_set_mate(mesh_id,nel,2);
////    	  				   elemgr[nel]=2;
////    	  			   }
////    	  			   //printf("OK!\n");
////    	  			}
////    	  			/*else
////    	  			{
////
////    	  				printf("błąd? %d\n",nel);
////    	  				printf("xa[%d]=%lf ya[%d]=%lf za[%d]=%lf\n",zxa,xa[i],zya,ya[i],zza,za[i]);
////    	  			  for(i=0;i<18;i++)
////    	      		  {
////    	      			  printf("Node %d - %lf\n",i/3,node_coor[i]);
////    	  	   		  }
////    	  	   		  printf("\n");
////    	  				exit(1);
////    	  				mmr_el_set_mate(mesh_id,nel,1);
////    	  			}*/
////    	  		 }
//    	  	  }
//
//    	  						/*
//    	  						if(k==0)
//    	  							min=mmr_el_hsize(mesh_id,nel,NULL,NULL,NULL);
//    	  						hsize=mmr_el_hsize(mesh_id,nel,NULL,NULL,NULL);
//    	  						if(hsize<min)
//    	  							min=hsize;
//    	  						//printf("Element %d nalezy do ziarna %d\n",nel,elemgr[nel]);
//    	  						k++;
//    	  						/**/
////    	  	  if(mmr_el_mate(mesh_id,nel)!=2 && mmr_el_mate(mesh_id,nel)!=1)
////    	  	  {
////    	  	      printf("Element %d - hsize: %lf ma material %d\n",nel,mmr_el_hsize(mesh_id,nel,NULL,NULL,NULL),mmr_el_mate(mesh_id,nel));
////    	  	      for(i=0;i<6;i++)
////    	  	    	  printf("Node %d - %lf,%lf,%lf\n",el_nodes[i+1],node_coor[3*i],node_coor[3*i+1],node_coor[3*i+2]);
////
////    	  	      //exit(-1);
////    	  	  }
//    	  } //loop over elements


    	  double odleglosc,srodek[3];
    	  nel=0;

    	  while((nel=mmr_get_next_act_elem(mesh_id, nel))!=0)
    	  {
    		  mmr_el_set_mate(mesh_id,nel,-1);
    		  //if(mmr_el_mate(mesh_id,nel)==3)
    		  //{
				  mmr_el_node_coor(mesh_id,nel,el_nodes,node_coor);
				  srodek[0]=node_coor[0]+node_coor[3]+node_coor[6];
				  srodek[0]=srodek[0]/3;
				  srodek[1]=node_coor[1]+node_coor[4]+node_coor[7];
				  srodek[1]=srodek[1]/3;
				  srodek[2]=node_coor[2]+node_coor[11];
				  srodek[2]/=2;
//				  printf("Srodek pryzmy o wspolrzednych:\t");
//				  for(i=0;i<18;i++)
//				  {
//					  printf("%lf ",node_coor[i]);
//					  if(i!=0&&(i+1)%3==0)
//						  printf("\n");
//				  }
//				  printf("\n");
//				  printf("%lf,%lf,%lf\n",srodek[0],srodek[1],srodek[2]);
				  double min=0;
				  int wsp=0;
    			  for(i=0;i<125000;i++)
    			  {
    				  //sortowanie babaelkowe??Minimum??
    				  odleglosc=sqrt(pow(xa[i]-srodek[0],2)+pow(ya[i]-srodek[1],2)+pow(za[i]-srodek[2],2));
    				  if(i==0)
    				  {
    					  min=odleglosc;
    					  wsp=i;
    				  }
    				  else
    				  {
    					  if(odleglosc<min)
    					  {
    						  min=odleglosc;
    						  wsp=i;
    					  }
    				  }
    			  }
    			  //printf("Minimalna odleglosc = %lf dla punktu %d o wsp: %lf,%lf,%lf - ferryt=%d\n",min,wsp,xa[wsp],ya[wsp],za[wsp],tmpfer[wsp]);
    			  mmr_el_set_mate(mesh_id,nel,tmpfer[wsp]-1);
    			  elemgr[nel]=tmpfer[wsp]-1;
    		  //}
    		  if(mmr_el_mate(mesh_id,nel)!=2 && mmr_el_mate(mesh_id,nel)!=1)
			  {
				  printf("Element %d - hsize: %lf ma material %d\n",nel,mmr_el_hsize(mesh_id,nel,NULL,NULL,NULL),mmr_el_mate(mesh_id,nel));
				  for(i=0;i<6;i++)
					  printf("Node %d - %lf,%lf,%lf\n",el_nodes[i+1],node_coor[3*i],node_coor[3*i+1],node_coor[3*i+2]);

				  exit(-1);
			  }
    	  }




//    	  int gen=0;
//    	  int anc=0;
//    	  int mat=0;
//    	  int weight1=0;
//    	  int weight2=0;
//    	  int weight3=0;
//    	  int neig[6];
//    	  nel=0;
//    	  while((nel=mmr_get_next_act_elem(mesh_id, nel))!=0)
//    	  {
//    		 if(mmr_el_mate(mesh_id,nel)==3)
//    		 {
//    			 printf("Element %d!! - ",nel);
//    			 gen=mmr_el_gen(mesh_id,nel);
//    			 printf("Generation level: %d - ",gen);
//    			 anc=mmr_el_ancestor(mesh_id,nel,gen-1);
//    			 mat=mmr_el_mate(mesh_id,anc);
//    			 printf("Przodek %d ma material %d \n",anc,mat);
//    			 mmr_el_set_mate(mesh_id,nel,mat);
    			 //mmr_el_set_mate(mesh_id,nel,1);
//    			 mmr_el_eq_neig(mesh_id,nel,neig,NULL);
//    			 for (i=1;i<6;i++)
//    			 {
//    				 printf("Sąsiad %d -%d",i,neig[i]);
//    				 if(neig[i]>0)
//    				 {
//    					 mat = mmr_el_mate(mesh_id,neig[i]);
//    					 printf(" - material %d",mat);
//    					 if(mat==1)
//    						 weight1++;
//    					 else if(mat==2)
//    						 weight2++;
//    					 else
//    						 weight3++;
//
//    				 }
//    				 printf("\n");
//    			 }
//    			 if(weight1>weight2)
//    			 {
//    				 mmr_el_set_mate(mesh_id,nel,1);
//    				 elemgr[nel]=1;
//    			 }
//    			 else if(weight2>=weight1)
//    			 {
//    		    	 mmr_el_set_mate(mesh_id,nel,2);
//    		    	 elemgr[nel]=2;
//    		     }
    			 //else if(weight3>=weight1 && weight3>=weight2)
    			 //{
    			//	 gen=mmr_el_gen(mesh_id,nel);
    			//	 anc=mmr_el_ancestor(mesh_id,nel,gen-1);
    			//	 mat=mmr_el_mate(mesh_id,anc);
    			//	 mmr_el_set_mate(mesh_id,nel,mat);
    			 //  	 elemgr[nel]=mat;
    			 //}

//    	  }


      }//end grains 3d
      //printf("\n");
#ifdef PARALLEL
    if(pcr_my_proc_id()==pcr_print_master()){
#endif
      fprintf(interactive_output,
	"\nBeginning solution of the test problem - Laplace's equation\n\n");
#ifdef PARALLEL
    }
#endif
      /* very simple time measurement */
      t_wall=time_clock();

#ifdef PARALLEL
      {
	int ione = 1;
/* initiate exchange tables for DOFs - for one field = one solver, one level */
	appr_init_exchange_tables(pdv_nr_proc, pcr_my_proc_id(), 1, &ione);
      }
#endif

      /* problem dependent interface with linear solvers */
      sprintf(arg,"%s/solver.dat", work_dir);
#ifndef PARALLEL
      sir_solve_lin_sys(problem_id, SIC_SEQUENTIAL, arg,-2,-2,-2,2);
#endif

#ifdef PARALLEL
      sir_solve_lin_sys(problem_id, SIC_PARALLEL, arg);
/* free exchange tables for DOFs - for one field = one solver */
      appr_free_exchange_tables(1);
#endif

      /* very simple time measurement */
      t_wall=time_clock()-t_wall;

#ifdef PARALLEL
    if(pcr_my_proc_id()==pcr_print_master()){
#endif
      fprintf(interactive_output,
	      "\nTime for solving a system of linear equations %lf\n\n",t_wall);

#ifdef PARALLEL
    }
#endif
    }//end of solve
    else if(c=='a'){
    	//pdr_adapt(field_id);
    	//pdr_create_patch(field_id);
    	//utr_adapt(problem_id,work_dir,interactive_input,interactive_output);
    	//pdr_free_list();
    	pdr_adapt(field_id);
    	//t_wall=time_clock()-t_wall;
    	pdr_free_list();

    }
    else if(c=='e'){

    	fprintf(interactive_output,"\n\nZienkiewicz-Zhu error estimator:\n\n");
    	pdr_get_zzhu_error(field_id);
    	//pdr_get_sigma(field_id);
    	//pdr_compute_eyoung(field_id);
    }
    else if(c=='p'){
//postprocessing
      pdr_post_process(field_id,interactive_output);

    }
    else if(c=='m'){

      utr_manual_refinement( problem_id, work_dir, 
			     interactive_input, interactive_output );

    }
    else if(c=='r'){

      utr_test_refinements(problem_id, work_dir, 
			   interactive_input, interactive_output );

    } /* end test of mesh refinements */

  } while(c != 'q');

  /* free allocated space */
  apr_free_field(field_id);
  mmr_free_mesh(mesh_id);

  fclose(interactive_input);
  fclose(interactive_output);

#ifdef PARALLEL
  pcr_exit_parallel();
#endif

  return(0);

}
Example #2
0
/* Has all kinds of effects in different circumstances.
   Eventually will be more interesting */
void s_ritual(void)
{
    pob symbol;
    int i,roomno;
    int x,y;

    mprint("You begin your ritual....");
    mprint("You enter a deep trance. Time Passes...");
    setgamestatus(SKIP_PLAYER);
    time_clock(FALSE);
    setgamestatus(SKIP_PLAYER);
    time_clock(FALSE);
    setgamestatus(SKIP_PLAYER);
    time_clock(FALSE);
    setgamestatus(SKIP_PLAYER);
    time_clock(FALSE);
    setgamestatus(SKIP_PLAYER);
    time_clock(FALSE);
    if (RitualHour == hour())
        mprint("Your mental fatigue prevents from completing the ritual!");
    else if (random_range(100) > Player.iq+Player.pow+Player.level)
        mprint("Your concentration was broken -- the ritual fails!");
    else {
        mprint("You charge the ritual with magical energy and focus your will.");
        mprint("Time Passes...");
        setgamestatus(SKIP_PLAYER);
        time_clock(FALSE);
        setgamestatus(SKIP_PLAYER);
        time_clock(FALSE);
        setgamestatus(SKIP_PLAYER);
        time_clock(FALSE);
        setgamestatus(SKIP_PLAYER);
        time_clock(FALSE);
        setgamestatus(SKIP_PLAYER);
        time_clock(FALSE);
        RitualHour = hour();
        /* set of random conditions for different ritual effects */
        if (Current_Environment == E_CITY) {
            mprint("Flowing waves of mystical light congeal all around you.");
            mprint("'Like wow, man! Colors!'");
            mprint("Appreciative citizens throw you spare change.");
            Player.cash +=random_range(50);
        }
        else if ( (roomno=Level->site[Player.x][Player.y].roomnumber) >= ROOMBASE )
        {
            if (RitualRoom == roomno)
                mprint("For some reason the ritual doesn't work this time...");
            else {
                RitualRoom = roomno;
                switch (RitualRoom) {
                case RS_TREASURE: /* ransacked treasure chamber */
                    mprint("Your spell sets off frenetic growth all around you!");
                    for(i=0; i<8; i++) {
                        Level->site[Player.x+Dirs[0][i]][Player.y+Dirs[1][i]].locchar =
                            HEDGE;
                        Level->site[Player.x+Dirs[0][i]][Player.y+Dirs[1][i]].p_locf =
                            L_TRIFID;
                        lset(Player.x+Dirs[0][i], Player.y+Dirs[1][i], CHANGED);
                    }
                    break;
                case RS_HAREM: /* harem */
                case RS_BOUDOIR: /* boudoir */
                    mprint("A secret panel opens next to the bed....");
                    if (random_range(2))
                        summon(0,INCUBUS); /* succubus/incubus */
                    else summon(0,SATYR); /* satyr/nymph */
                    break;
                case RS_SHRINE: /*shrine to high magic */
                    mprint("A storm of mana coaelesces around you.");
                    mprint("You are buffeted by bursts of random magic.");
                    p_damage(random_range(Player.pow),UNSTOPPABLE,"high magic");
                    mprint("Continue ritual? Could be dangerous.... [yn] ");
                    if (ynq()=='y') s_wish();
                    else mprint("The mana fades away to nothingness.");
                    x = Player.x;
                    y = Player.y;
                    while (x >= 0 && Level->site[x - 1][y].roomnumber == RS_SHRINE)
                        x--;
                    while (y >= 0 && Level->site[x][y - 1].roomnumber == RS_SHRINE)
                        y--;
                    for (i = 0; Level->site[x][y].roomnumber == RS_SHRINE;) {
                        Level->site[x][y].roomnumber = RS_ZORCH;
                        lset(x, y, CHANGED);
                        x++;
                        i++;
                        if (Level->site[x][y].roomnumber != RS_SHRINE) {
                            x -= i;
                            i = 0;
                            y++;
                        }
                    }
                    break;
                case RS_MAGIC_LAB: /* magician's lab */
                    mprint("Your magical activity sets off a latent spell in the lab!");
                    cast_spell(random_range(NUMSPELLS));
                    break;
                case RS_PENTAGRAM: /* pentagram room */
                    mprint("A smoky form begins to coalesce....");
                    summon(-1,-1);
                    mprint("Fortunately, it seems confined to the pentagram.");
                    m_status_reset(Level->mlist->m,MOBILE);
                    break;
                case RS_OMEGA_DAIS: /* blue omega room */
                    mprint("The Lords of Destiny look upon you....");
                    if (Player.level > 10) {
                        mprint("A curtain of blue flames leaps up from the omega.");
                        morewait();
                        l_adept();
                    }
                    else {
                        if (Player.patron == DESTINY) {
                            mprint("Your patrons take pity on you.");
                            if ((Player.rank[PRIESTHOOD]<SPRIEST) &&
                                    (! find_item(&symbol,OB_SYMBOL_DESTINY,-1))) {
                                symbol = ((pob) checkmalloc(sizeof(objtype)));
                                *symbol = Objects[OB_SYMBOL_DESTINY];
                                symbol->known = 2;
                                symbol->charge = 17;
                                gain_item(symbol);
                                mprint("You feel uplifted.");
                            }
                            else gain_experience(min(1000,Player.xp));
                        }
                        else if (random_range(3)==1) {
                            mprint("You feel Fated.");
                            gain_experience(Player.level*Player.level*10);
                            Player.hp = max(Player.hp, Player.maxhp);
                        }
                        else if (random_range(2)) {
                            mprint("You feel Doomed.");
                            Player.hp = 1;
                            Player.mana = 0;
                            Player.xp = 0;
                        }
                        else mprint("The Lords of Destiny laugh at you!");
                    }
                    break;
                default:
                    mprint("Well, not much effect. Chalk it up to experience.");
                    gain_experience(Player.level*5);
                    break;
                }
            }
        }
        else {
            if (RitualRoom == Level->site[Player.x][Player.y].roomnumber)
                mprint("The ritual fails for some unexplainable reason.");
            else {
                mprint("The ritual seems to be generating some spell effect.");
                RitualRoom = Level->site[Player.x][Player.y].roomnumber;
                switch (RitualRoom) {
                case RS_WALLSPACE:
                    shadowform();
                    break;
                case RS_CORRIDOR:
                    haste(0);
                    break;
                case RS_PONDS:
                    breathe(0);
                    break;
                case RS_ADEPT:
                    hero(1);
                    break;
                default:
                    mprint("The ritual doesn't seem to produce any tangible results...");
                    gain_experience(Player.level*6);
                }
            }
        }
    }
}
Example #3
0
/*---------------------------------------------------------
utr_initialize_mesh - to initialize mesh of a specified type
---------------------------------------------------------*/
int utr_initialize_mesh( /* returns mesh_id */
  FILE *Interactive_output, /* file or stdout to write messages */
  const char* Work_dir, // path to working directory
  char Mesh_type, /* letter symbol denoting mesh_type (j, p, t or h) */
  char* Mesh_file /* mesh file name - conforming to naming convention */
  )
{

  int mesh_id;
  char mesh_desc=0;
  char arg[500]={0};
/*++++++++++++++++ executable statements ++++++++++++++++*/

  switch(Mesh_type) {
  case 'j': mesh_desc = MMC_GRADMESH_DATA; break;
  case 'p': mesh_desc = MMC_MOD_FEM_PRISM_DATA; break;
  case 't': mesh_desc = MMC_MOD_FEM_TETRA_DATA; break;
  case 'h': mesh_desc = MMC_MOD_FEM_HYBRID_DATA; break;
  case 'n': mesh_desc = MMC_NASTRAN_DATA; break;
  case 'b': mesh_desc = MMC_BINARY_DATA; break;
  case 'i': mesh_desc = MMC_IN_ANSYS_DATA; break;
  default:{ 
	fprintf(Interactive_output,
		"Unknown mesh type %c in utr_initialize_mesh.... ! Exiting\n",Mesh_type);
	exit(-1);
  }break;
  } //!switch(mesh_type)


/// Here MODFEM_NEW_MPI define that switches old and new version of I/O handling.
#ifdef MODFEM_NEW_MPI
  // Using MODFEM_NEW_MPI (mmpd_adapter)
  mesh_id = mmr_init_mesh2(Interactive_output,0,0,0,0);
  if(mesh_id > 0) {
   int n_readed = utr_io_read_mesh(mesh_id, Work_dir, Mesh_file, mesh_desc);
   assert(n_readed > 0);
  }
#else
  // Using default mpi (mmpd_prism)
  // Create full mesh file path.
  sprintf(arg, "%s/%s", Work_dir, Mesh_file);
  // Initialize sequential/shared memory  mesh.
  mesh_id = mmr_init_mesh(mesh_desc, arg, Interactive_output);
#endif
/// !MODFEM_NEW_MPI

  // If parallel overlap is on, initialize parallel mesh.
#ifdef PARALLEL
  /* very simple time measurement */
  double t_wall = time_clock();
  /* initial mesh (generation 0) as basis for decomposition */
  mmpr_init_mesh(MMC_INIT_GEN_LEVEL, mesh_id, pcr_nr_proc(), pcr_my_proc_id() );
  /* very simple time measurement */
  t_wall = time_clock() - t_wall;
  fprintf(Interactive_output, "\nTime for domain decomposition (mesh partition) %lf\n\n", t_wall);
#endif

  /* printf("\nInitiated mesh %d\n", mesh_id); */

  /* int nodes[10]={0}; */
  /* int nodecoor[30]={0}; */
  
  /* int loops=100; */
  /* int Nel=0; */
  /* time_init(); */
  /* while(--loops) { */
  /*   Nel=0; */
  /*   while( (Nel=mmr_get_next_act_elem(mesh_id,Nel))!=0 ) { */
  /*     mmr_el_node_coor(mesh_id, Nel, nodes, nodecoor); */
  /*   } */
  /* } */
  /* double time_loop = time_CPU(); */
  /* printf("\nCzas wykonania pętli dla 100 powtórzeń: %lf (śr na el: %.12lf)",time_loop, (time_loop/100.0)/(double)mmr_get_nr_elem(mesh_id)); */
    

  return(mesh_id);
}
Example #4
0
int main(int argc, char *argv[])
{
  int continuing = 0;
  int count;
  int scores_only = 0;
  int i;

#ifndef NOGETOPT
  while(( i= getopt( argc, argv, "dsh")) != -1)
  {
     switch (i)
     {
       case 'd':
#ifdef DEBUG
         DG_debug_flag++;
#endif
         break;
       case 's':
         scores_only = 1;
         break;
       case 'h':
#ifdef DEBUG
         printf("Usage: omega [-shd] [savefile]\n");
#else
         printf("Usage: omega [-sh] [savefile]\n");
#endif
         printf("Options:\n");
         printf("  -s  Display high score list\n");
         printf("  -h  Display this message\n");
#ifdef DEBUG
         printf("  -d  Enable debug mode\n");
#endif
         exit(0);
         break;
       case '?':
         /* error parsing args... ignore? */
         printf("'%c' is an invalid option, ignoring\n", optopt );
         break;
     }
  }

  if (optind >= argc ) {
    /* no save file given */
#if defined( BSD ) || defined( SYSV )
    sprintf( SaveFileName, "Omega%d", getuid() );
#else
    strcpy( SaveFileName,"Omega");
#endif
  } else {
    /* savefile given */
    continuing = 1;
    strcpy(SaveFileName,argv[optind]);
  }

#else 
  /* alternate code for people who don't support getopt() -- no enhancement */
  if (argc ==2) {
    strcpy( SaveFileName, argv[1]);
    continuing = 1;
  } else {
    strcpy( SaveFileName,"Omega");
  }
#endif

  /* always catch ^c and hang-up signals */

#ifdef SIGINT
  signal(SIGINT,signalquit);
#endif
#ifdef SIGHUP
  signal(SIGHUP,signalsave);
#endif

#ifndef MSDOS
  if (CATCH_SIGNALS) {
    signal(SIGQUIT,signalexit);
    signal(SIGILL,signalexit);
#ifdef DEBUG
    if( DG_debug_flag ) {
#endif
    signal(SIGTRAP,signalexit);
    signal(SIGFPE,signalexit);
    signal(SIGSEGV,signalexit);
#ifdef DEBUG
    }
#endif
#ifdef SIGIOT
    signal(SIGIOT,signalexit);
#endif
#ifdef SIGABRT
    signal(SIGABRT,signalexit);
#endif
#ifdef SIGEMT
    signal(SIGEMT,signalexit);
#endif
#ifdef SIGBUS
    signal(SIGBUS,signalexit);
#endif
#ifdef SIGSYS
    signal(SIGSYS,signalexit);
#endif
    }
#endif

#ifndef FIXED_OMEGALIB
  if (!(Omegalib = getenv("OMEGALIB")))
#endif
    Omegalib = OMEGALIB;

  /* if filecheck is 0, some necessary data files are missing */
  if (filecheck() == 0) exit(0);

  /* all kinds of initialization */
  init_perms();
  initgraf();
#ifndef MSDOS_SUPPORTED_ANTIQUE
  initdirs();
#endif
  initrand(E_RANDOM, 0);
  initspells();

#ifdef DEBUG
  /* initialize debug log file */
  DG_debug_log = fopen( "/tmp/omega_dbg_log", "a" );
  assert( DG_debug_log ); /* WDT :) */
  setvbuf( DG_debug_log, NULL, _IOLBF, 0);
  fprintf(DG_debug_log, "##############  new game started ##############\n");
#endif

  for (count = 0; count < STRING_BUFFER_SIZE; count++)
    strcpy(Stringbuffer[count],"<nothing>");

#ifdef SAVE_LEVELS
  msdos_init();
#endif

  omega_title();
  showscores();

  if (scores_only ) {
    endgraf();
    exit(0);
  }

  /* game restore attempts to restore game if there is an argument */
  if (continuing) 
  {
     game_restore(SaveFileName);
     mprint("Your adventure continues....");
  }
  else
  {
    /* monsters initialized in game_restore if game is being restored */  
    /* items initialized in game_restore if game is being restored */
    inititem(TRUE);
    Date = random_range(360);
    Phase = random_range(24);
#ifdef NEW_BANK
    bank_init();
#else
    strcpy(Password,"");
#endif
    continuing = initplayer(); /* RM: 04-19-2000 loading patch */
  }
  if (!continuing)
  {
    init_world();  /* RM: 04-19-2000 loading patch */
    mprint("'?' for help or commandlist, 'Q' to quit.");
  }

  timeprint();
  calc_melee();
  if (Current_Environment != E_COUNTRYSIDE)
    showroom(Level->site[Player.x][Player.y].roomnumber);
  else
    terrain_check(FALSE);
  
  if (optionp(SHOW_COLOUR))
    colour_on();
  else
    colour_off();

  screencheck(Player.x,Player.y);

 /* game cycle */
  if (!continuing)
    time_clock(TRUE);
  while (TRUE) {
    if (Current_Environment == E_COUNTRYSIDE)
      p_country_process();
    else time_clock(FALSE);
  }
}
/*------------------------------------------------------------
  pdr_comp_stiff_mat - to provide a solver with a stiffness matrix
                      and a load vector corresponding to the specified
                      mesh entity, together with information on how to
                      assemble entries into the global stiffness matrix
                      and the global load vector
------------------------------------------------------------*/
int pdr_comp_stiff_mat(	 /* returns: >=0 - success code, <0 - error code */
  int Problem_id,	/* in: approximation field ID  */
  int Int_ent_type,	/* in: unique identifier of the integration entity */
  int Int_ent_id,	/* in: unique identifier of the integration entity */
  int Comp_sm,	/* in: indicator for the scope of computations: */
  /*   PDC_NO_COMP  - do not compute anything */
  /*   PDC_COMP_SM - compute entries to stiff matrix only */
  /*   PDC_COMP_RHS - compute entries to rhs vector only */
  /*   PDC_COMP_BOTH - compute entries for sm and rhsv */
  int *Pdeg_vec,	/* in: enforced degree of polynomial (if > 0 ) */
  int *Nr_dof_ent,	/* in: size of arrays, */
			/* out: number of mesh entities with which dofs and */
			/*      stiffness matrix blocks are associated */
  int *List_dof_ent_type,	/* out: list of types for 'dof' entities */
  int *List_dof_ent_id,	/* out: list of ids for 'dof' entities */
  int *List_dof_ent_nrdofs,	/* out: list of no of dofs for 'dof' entity */
  int *Nrdofs_loc,	/* in(optional): size of Stiff_mat and Rhs_vect */
	      /* out(optional): actual number of dofs per integration entity */
  double *Stiff_mat,	/* out(optional): stiffness matrix stored columnwise */
  double *Rhs_vect,	/* outpds_elast_ls_std_intf.c(optional): rhs vector */
  char *Rewr_dofs	/* out(optional): flag to rewrite or sum up entries */
			/*   'T' - true, rewrite entries when assembling */
			/*   'F' - false, sum up entries when assembling */
 )
{
  int field_id, mesh_id, face_neig[2];
  double timer = time_clock();
  int elem;
  
  int pdeg;
  /* element degree of approximation for linear prisms is a single number */
  if (Pdeg_vec == NULL)
    pdeg = 0;
  else
    pdeg = Pdeg_vec[0];
/*kbw
    printf("in pdr_comp_stiff_mat: problem_id %d, int_ent: type %d, id %d, enforced pdeg %d\n",
    Problem_id, Int_ent_type, Int_ent_id, pdeg);
/*kew */
  
  field_id = pdr_ctrl_i_params(Problem_id, 3);
  
  /* compute UNCONSTRAINED stiffness matrices (no hanging nodes considered) */
  if (Int_ent_type == PDC_ELEMENT) {
    pdr_ns_supg_comp_el_stiff_mat(Problem_id, Int_ent_id, Comp_sm, pdeg, 
				  Nr_dof_ent, List_dof_ent_type, 
				  List_dof_ent_id, List_dof_ent_nrdofs, 
				  Nrdofs_loc, Stiff_mat, Rhs_vect, Rewr_dofs);

    elem = Int_ent_id;
    
    
  } else if (Int_ent_type == PDC_FACE) {
    pdr_ns_supg_comp_fa_stiff_mat(Problem_id, Int_ent_id, Comp_sm, pdeg, 
				  Nr_dof_ent, List_dof_ent_type, 
				  List_dof_ent_id, List_dof_ent_nrdofs, 
				  Nrdofs_loc, Stiff_mat, Rhs_vect, Rewr_dofs);

    mesh_id = apr_get_mesh_id(field_id);
    mmr_fa_neig(mesh_id, Int_ent_id, face_neig, NULL, NULL, NULL, NULL, NULL); 
    elem = abs(face_neig[0]);
    
  } else {
    printf("ERROR: Wrong integration entity type in pdr_comp_stiff_mat!\n");
    exit(-1);
  }
  
  /* change the option compute SM and RHSV to rewrite SM and RHSV */
  if (Comp_sm != PDC_NO_COMP)  Comp_sm += 3;
  
  /* obligatory procedure to fill Lists of dof_ents and rewite SM and RHSV */
  /* the reason is to take into account POSSIBLE CONSTRAINTS (HANGING NODES) */
  apr_get_stiff_mat_data(field_id, elem, Comp_sm, 'N',  
			 pdeg, 0, Nr_dof_ent, List_dof_ent_type, 
			 List_dof_ent_id, List_dof_ent_nrdofs, 
			 Nrdofs_loc, Stiff_mat, Rhs_vect);
  
  /*kbw
  //if(Comp_sm!=PDC_NO_COMP)
	  {
		int i;
    printf("In pdr_com_el_stiff_mat: field_id %d, El_id %d, Comp_sm %d, Nr_dof_ent %d\n",
     field_id, Int_ent_id, Comp_sm, *Nr_dof_ent);
     printf("For each block: \ttype, \tid, \tnrdof\n");
     for(i=0;i<*Nr_dof_ent;i++){
     printf("\t\t\t%d\t%d\t%d\n",
     List_dof_ent_type[i],List_dof_ent_id[i],List_dof_ent_nrdofs[i]);
     }
     printf("\n\n");
     }
     //getchar();getchar();
     /*kew */

  /* matrix displayed by rows, altghough stored by columns !!!!!!!!! */
  /*kbw
     if(Comp_sm!=PDC_NO_COMP)
     {
     printf("\nElement %d: Modified stiffness matrix:\n",El_id);
     for (idofs=0;idofs<*Nrdofs_loc;idofs++) { //for each row!!!!
     for (jdofs=0;jdofs<*Nrdofs_loc;jdofs++) { // for each element in row !!!
     printf("%7.3lf",Stiff_mat[idofs+jdofs*(*Nrdofs_loc)]);
     }
     printf("\n");
     }
     printf("Element %d: Rhs_vect:\n",El_id);
     for (idofs=0;idofs<*Nrdofs_loc;idofs++) {
     printf("%7.3lf",Rhs_vect[idofs]);
     }
     printf("\n\n");
     //getchar();
     }
     /* */

  pdv_ns_supg_ale_timer_pdr_comp_el_stiff_mat += time_clock() - timer;

  return (1);
}
Example #6
0
/**
 * @brief ui_ggs_play
 *
 * Search the best move.
 *
 * @param ui User Interface.
 * @param turn Edax's color.
 */
static void ui_ggs_play(UI *ui, int turn) {
	long long real_time = -time_clock();
	int remaining_time = ui->ggs->board->clock[turn].ini_time;
	int extra_time = ui->ggs->board->clock[turn].ext_time;
	Play *play;
	Result *result;
	char move[4], line[32];
	const char *(search_state_array[6]) = {"running", "interrupted", "stop pondering", "out of time", "stopped on user demand", "completed"};
	char search_state[32];

	if (ui->is_same_play) {
		play = ui->play;
		if (search_count_tasks(ui->play->search) < options.n_task) {
			printf("<use a single %d tasks search while a single game is played>\n", options.n_task);
			play_stop_pondering(ui->play);
			search_set_task_number(ui->play[0].search, options.n_task);
			play_stop_pondering(ui->play + 1);
			search_set_task_number(ui->play[1].search, 0);
		}
	} else {
		play = ui->play + turn;
		if (search_count_tasks(ui->play->search) == options.n_task && options.n_task > 1) {
			printf("<split single %d tasks search into two %d task searches>\n", options.n_task, options.n_task / 2);
			play_stop_pondering(ui->play);
			search_set_task_number(ui->play[0].search, options.n_task / 2);
			play_stop_pondering(ui->play + 1);
			search_set_task_number(ui->play[1].search, options.n_task / 2);
			search_share(ui->play[0].search, ui->play[1].search);
			ui_ggs_ponder(ui, turn ^ 1); // ponder opponent move
		}
	}

	// game over detection...
	if (play_is_game_over(play)) {
		ggs_client_send(ui->ggs, "tell .%s *** GAME OVER ***\n", ui->ggs->me);
		return ;
	}

	result = play->result;
	
	if (remaining_time > 60000) remaining_time -= 10000; // keep 10s. for safety.
	else if (remaining_time > 10000) remaining_time -= 2000; // keep 2s. for safety.
	if (remaining_time < 1000) remaining_time = 1000; // set time to at list 1ms
	play_adjust_time(play, remaining_time, extra_time);

	printf("<ggs: go thinking>\n");
	play_go(play, false);

	real_time += time_clock();

	move_to_string(result->move, play->player, move);

	ggs_client_send(ui->ggs, "tell /os play %s %s/%d/%.2f\n", ui->ggs->board->id, move, result->score, 0.001 * (real_time + 1));

	if (result->book_move) {
		printf("[%s plays %s in game %s ; score = %d from book]\n", ui->ggs->me, move, ui->ggs->board->id, result->score);
		ggs_client_send(ui->ggs, "tell .%s -----------------------------------------"
			"\\%s plays %s in game %s"
			"\\score == %d from book\n",
			ui->ggs->me,
			ui->ggs->me, move, ui->ggs->board->id,
			result->score
		);
	} else if (play->search->n_empties >= 15) { //avoid noisy display
		const char *bound;
		char s_nodes[16], s_speed[16];

		if (result->bound[result->move].lower < result->score && result->score == result->bound[result->move].upper) bound = "<=";
		else if (result->bound[result->move].lower == result->score && result->score < result->bound[result->move].upper) bound = ">=";
		else bound = "==";

		info("<%s plays %s in game %s ; score = %d at %d@%d%% ; %lld nodes in %.1fs (%.0f nodes/s.)>\n",
			ui->ggs->me, move, ui->ggs->board->id,
			result->score, result->depth, selectivity_table[result->selectivity].percent,
			result->n_nodes, 0.001 * real_time, (result->n_nodes / (0.001 * real_time + 0.001))
		);
		if (play->search->stop == STOP_TIMEOUT) {
			sprintf(search_state, "%s at %d@%d%%", search_state_array[play->search->stop], play->search->depth, selectivity_table[play->search->selectivity].percent);
		} else {
			sprintf(search_state, "%s", search_state_array[play->search->stop]);
		}
		ggs_client_send(ui->ggs, "tell .%s -----------------------------------------"
			"\\%s plays %s in game %s using %d thread%s"
			"\\score %s %+02d at %d@%d%% ; PV: %s ;"
			"\\nodes: %s ; time: search = %.1fs, move = %.1fs; speed: %s."
			"\\search %s\n",
			ui->ggs->me,
			ui->ggs->me, move, ui->ggs->board->id, search_count_tasks(play->search), search_count_tasks(play->search) > 1 ? "s ;" : " ;",
			bound, result->score,
			result->depth, selectivity_table[result->selectivity].percent,
			line_to_string(result->pv, 8, " ", line),
			format_scientific(result->n_nodes, "N", s_nodes), 0.001 * result->time, 0.001 * real_time, format_scientific(result->n_nodes / (0.001 * result->time+ 0.001), "N/s", s_speed),
			search_state
		);
	}
}
Example #7
0
void l_arena(void)
{
    char response;
    Object* newitem;
    int i,prize,monsterlevel;
    char *melee = NULL;

    print1("Rampart Coliseum");
    if (Player.rank[ARENA] == 0) {
        print2("Enter the games, or Register as a Gladiator? [e,r,ESCAPE] ");
        do response = (char) mcigetc();
        while ((response != 'e') && (response != 'r') && (response != ESCAPE));
    }
    else {
        print2("Enter the games? [yn] ");
        response = ynq2();
        if (response == 'y') response = 'e';
        else response = ESCAPE;
    }
    if (response == 'r') {
        if (Player.rank[ARENA]>0)
            print2("You're already a gladiator....");
        else if (Player.rank[ORDER]>0)
            print2("We don't let Paladins into our Guild.");
        else if (Player.rank[LEGION]>0)
            print2("We don't train no stinkin' mercs!");
        else if (Player.str < 13)
            print2("Yer too weak to train!");
        else if (Player.agi < 12)
            print2("Too clumsy to be a gladiator!");
        else {
            print1("Ok, yer now an Arena Trainee.");
            print2("Here's a wooden sword, and a shield");
            morewait();
            clearmsg();
            newitem = ((Object*) checkmalloc(sizeof(Object)));
            *newitem = Objects[OB_CLUB]; /* club */
            gain_item(newitem);
            newitem = ((Object*) checkmalloc(sizeof(Object)));
            *newitem = Objects[OB_LRG_RND_SHIELD]; /* shield */
            gain_item(newitem);
            Player.rank[ARENA] = TRAINEE;
            Arena_Opponent = 3;
            morewait();
            clearmsg();
            print1("You've got 5000Au credit at the Gym.");
            Gymcredit+=5000;
        }
    }
    else if (response == 'e') {
        print1("OK, we're arranging a match....");
        morewait();
        Arena_Monster = ((Monster*) checkmalloc(sizeof(Monster)));
        Arena_Victory = false;
        switch(Arena_Opponent) {
        case 0:
            *Arena_Monster = Monsters[GEEK];
            break;
        case 1:
            *Arena_Monster = Monsters[HORNET];
            break;
        case 2:
            *Arena_Monster = Monsters[HYENA];
            break;
        case 3:
            *Arena_Monster = Monsters[GOBLIN];
            break;
        case 4:
            *Arena_Monster = Monsters[GRUNT];
            break;
        case 5:
            *Arena_Monster = Monsters[TOVE];
            break;
        case 6:
            *Arena_Monster = Monsters[APPR_NINJA];
            break;
        case 7:
            *Arena_Monster = Monsters[SALAMANDER];
            break;
        case 8:
            *Arena_Monster = Monsters[ANT];
            break;
        case 9:
            *Arena_Monster = Monsters[MANTICORE];
            break;
        case 10:
            *Arena_Monster = Monsters[SPECTRE];
            break;
        case 11:
            *Arena_Monster = Monsters[BANDERSNATCH];
            break;
        case 12:
            *Arena_Monster = Monsters[LICHE];
            break;
        case 13:
            *Arena_Monster = Monsters[AUTO_MAJOR];
            break;
        case 14:
            *Arena_Monster = Monsters[JABBERWOCK];
            break;
        case 15:
            *Arena_Monster = Monsters[JOTUN];
            break;
        default:
            if ((Player.rank[ARENA] < 5) && (Player.rank[ARENA] > 0)) {
                strcpy(Str1,Champion);
                strcat(Str1,", the arena champion");
                *Arena_Monster = Monsters[HISCORE_NPC];
                Arena_Monster->name = salloc(Str1);
                strcpy(Str2,"The corpse of ");
                strcat(Str2,Str1);
                Arena_Monster->corpseString = salloc(Str2);
                m_status_set( Arena_Monster, ALLOC );
                Arena_Monster->level = 20;
                Arena_Monster->hp = Championlevel*Championlevel*5;
                Arena_Monster->hit = Championlevel*4;
                Arena_Monster->ac = Championlevel*3;
                Arena_Monster->dmg = 100+Championlevel*2;
                Arena_Monster->xpv = Championlevel*Championlevel*5;
                Arena_Monster->speed = 3;
                melee = Arena_Monster->combatManeuvers = (char *) checkmalloc(30*sizeof(char));
                strcpy(Arena_Monster->combatManeuvers,"");
                for(i=0; i<Championlevel/5; i++)
                    strcat(Arena_Monster->combatManeuvers,"L?R?");
                m_status_set(Arena_Monster, MOBILE);
                m_status_set(Arena_Monster, HOSTILE);
            }
            else {
                do
                    i = random_range(ML9 - ML0) + ML0;
                while (i == NPC || i == HISCORE_NPC || i == ZERO_NPC ||
                        (Monsters[i].uniqueness != COMMON) ||
                        (Monsters[i].dmg == 0));
                *Arena_Monster = Monsters[i];
            }
            break;
        }
        monsterlevel = Arena_Monster->level;
        if (Arena_Monster->level != 20) {
            strcpy(Str1,nameprint());
            strcat(Str1," the ");
            strcat(Str1,Arena_Monster->name);
            Arena_Monster->name = salloc(Str1);
            strcpy(Str2,"The corpse of ");
            strcat(Str2,Str1);
            Arena_Monster->corpseString = salloc(Str2);
            m_status_set( Arena_Monster, ALLOC );
        }
        Arena_Monster->uniqueness = UNIQUE_MADE;
        print1("You have a challenger: ");
        print2(Arena_Monster->name);
        Arena_Monster->wasAttackedByPlayer = true;
        m_status_set(Arena_Monster,HOSTILE);
        /* DAG  pump up the stats of the arena monster; from env.c */
        /* DAG should we even do this for the champion? */
        Arena_Monster->hp += Arena_Monster->level*10;
        Arena_Monster->hit += Arena_Monster->hit;
        Arena_Monster->dmg += Arena_Monster->dmg/2;

        morewait();
        clearmsg();
        change_environment(E_ARENA);
        print1("Let the battle begin....");

        time_clock(true);
        while (Current_Environment == E_ARENA)
            time_clock(false);

        /* DAG all this nasty mess cleaned up...  */
        /* one process with m_status_set( Arena_Monster, ALLOC) */

        /* free(name); */
        /* free(corpse); */

        if (melee)
            free(melee);
        if (! Arena_Victory) {
            print1("The crowd boos your craven behavior!!!");
            if (Player.rank[ARENA] > 0) {
                print2("You are thrown out of the Gladiator's Guild!");
                morewait();
                clearmsg();
                if (Gymcredit > 0) print1("Your credit at the gym is cut off!");
                Gymcredit = 0;
                Player.rank[ARENA] = -1;
            }
        }
        else {
            Arena_Opponent++;
            if (monsterlevel == 20) {
                print1("The crowd roars its approval!");
                if (Player.rank[ARENA]) {
                    print2("You are the new Arena Champion!");
                    Championlevel = Player.level;
                    strcpy(Champion,Player.name);
                    Player.rank[ARENA] = 5;
                    morewait();
                    Championbehavior = fixnpc(4);
                    save_hiscore_npc(11);
                    print1("You are awarded the Champion's Spear: Victrix!");
                    morewait();
                    newitem = ((Object*) checkmalloc(sizeof(Object)));
                    *newitem = Objects[OB_VICTRIX];
                    gain_item(newitem);

                }
                else {
                    print1("As you are not an official gladiator,");
                    nprint1("you are not made Champion.");
                    morewait();
                }
            }
            morewait();
            clearmsg();
            print1("Good fight! ");
            nprint1("Your prize is: ");
            prize = max(25,monsterlevel * 50);
            if (Player.rank[ARENA] > 0) prize *= 2;
            mnumprint(prize);
            nprint1("Au.");
            Player.cash+=prize;
            if ((Player.rank[ARENA]<4) &&
                    (Arena_Opponent>5) &&
                    (Arena_Opponent % 3 == 0)) {
                if (Player.rank[ARENA]>0) {
                    Player.rank[ARENA]++;
                    morewait();
                    print1("You've been promoted to a stronger class!");
                    print2("You are also entitled to additional training.");
                    Gymcredit+=Arena_Opponent*1000;
                }
            }
        }
        xredraw();
    }
    else clearmsg();
}
Example #8
0
/*** DEFINITIONS ***/
int main(int argc, char **argv)
{

/* local variables */
  char interactive_input_name[300];
  char interactive_output_name[300], tmp[100];
  char field_module_name[100];
  FILE *interactive_input, *interactive_output;
  char c, d, arg[300]; /* string variable to read menu */
  int i, iaux, jaux, kaux;
  int nreq, nr_sol, iel, nr_mat, base;
  int problem_id, field_id, mesh_id;
  double daux, t_wall;
  int nrno, nmno, nred, nmed, nrfa, nmfa, nrel, nmel;

#ifdef PARALLEL
  int nr_proc;
  int my_proc_id;
  int info;
#endif

/*++++++++++++++++ executable statements ++++++++++++++++*/

  /* very simple - for the beginning instead of GUI */
  if(argv[1]==NULL){
	strcpy(work_dir,".");
  } else {
	sprintf(work_dir,"%s",argv[1]);
  }

  utr_set_interactive(work_dir, argc, argv,
		      &interactive_input, &interactive_output);

#ifdef DEBUG
  fprintf(interactive_output,"Starting program in debug mode.\n");
#endif
#ifdef DEBUG_MMM
  fprintf(interactive_output,"Starting mesh module in debug mode.\n");
#endif
#ifdef DEBUG_APM
  fprintf(interactive_output,"Starting approximation module in debug mode.\n");
#endif
#ifdef DEBUG_SIM
  fprintf(interactive_output,"Starting solver interface in debug mode.\n");
#endif
#ifdef DEBUG_LSM
  fprintf(interactive_output,"Starting linear solver (adapter) module in debug mode.\n");
#endif


  /*++++ initialization of problem, mesh and field data ++++*/
  pdr_init_problem(work_dir, interactive_input, interactive_output);
  problem_id = 1; // there is only one problem by default
  i=2; mesh_id=pdr_ctrl_i_params(problem_id,i);
  i=3; field_id = pdr_ctrl_i_params(problem_id,i);  
  i=4; nr_sol = pdr_ctrl_i_params(problem_id,i);
  i=5; nreq = pdr_ctrl_i_params(problem_id,i);
  // currently supported fields:
  // STANDARD_LINEAR - for continuous, vector, linear approximations
  // DG_SCALAR_PRISM - for discontinuous, scalar, high order approximations
  apr_module_introduce(field_module_name);
  
  /*++++++++++++ main menu loop ++++++++++++++++++++++++++++*/
  do {
    
#ifdef PARALLEL
    my_proc_id = pcr_my_proc_id();
    if(pcr_my_proc_id()==pcr_print_master()){
#endif

    if(interactive_input == stdin){
      
      
      do {
	/* define a menu */
	printf("\nChoose a command from the menu:\n");
	printf("\ts - solve test problem - Laplace's quation \n");
	printf("\tu - solve test problem with direct solver \n");
	printf("\tp - postprocessing\n");
	printf("\tk - launch graphic module\n");
	printf("\te - compute error for test problem\n");
	printf("\tz - compute ZZ error estimator for test problem\n");
	printf("\ta - automatic mesh adaptation based on ZZ error estimate\n");
	printf("\tm - perform manual mesh adaptation \n");
	printf("\td - dump out data \n");
	printf("\tv - dump out ParaView graphics data \n");
	printf("\tg - dump out ModFemViewer graphics data \n");
	printf("\tr - perform random test of h-adaptivity\n");
	printf("\tq - exit the program\n");
	
	scanf(" %c",&c);
      } while ( c != 'm' && c != 'd' && c != 'r' && c != 'v'
		&& c != 's' && c != 'e' && c != 'p' && c != 'a'
		&& c != 'z' && c != 'g' && c != 'u' && c != 'q' && c != 'k');
      
    } else{
      
      // read control data from interactive_input file
      fscanf(interactive_input,"%c\n",&c);
      
    }
    
#ifdef PARALLEL
    }

    pcr_bcast_char(pcr_print_master(),1,&c);
    //printf("After BCAST %c\n",c);

#endif

    // dumping data
    if(c=='d'){
      
/* different mesh files can be taken into account using MESHFIL_TYP parameter */ 
      sprintf(arg,"%s/mesh_prism.dmp", work_dir);
      iaux = mmr_export_mesh(mesh_id, MMC_MOD_FEM_MESH_DATA, arg); 
      if(iaux<0) {
	/* if error in writing data */
	fprintf(interactive_output,"Error in writing mesh data!\n");
      }
      
      nreq = pdr_ctrl_i_params(problem_id, 5);
      nr_sol =  pdr_ctrl_i_params(problem_id, 4);
      
      if(nr_sol==1) iaux=1; // parameter to select vectors written to file
      if(nr_sol==2) iaux=3; // both vectors written to file
      // scheme: 1 - 1, 2 - 2, 3 - 4, 1+2 - 3, 1+3 - 5, 2+3 - 6, 1+2+3 - 7
      
      sprintf(arg,"%s/field.dmp", work_dir);
      
      // write field to file arg with accuracy parameter = 0 - full accuracy 
      iaux = apr_write_field(field_id, nreq, iaux, 0, arg);
      if(iaux<0) {
	/* if error in writing data */
	fprintf(interactive_output,"Error in writing field data!\n");
      }
      
    }

    // storing ParaView graphics data
    else if(c=='v'){
      
      if( strncmp(field_module_name, "STANDARD_LINEAR", 15) == 0){  
	sprintf(arg, "%s/dump_paraview.vtu", work_dir);
	utr_write_paraview_std_lin(mesh_id, field_id, arg);
      }
      else{
	fprintf(interactive_output,"ParaView dump only for std_lin approx!\n");
      }


    }

    else if(c=='k'){
    	c='\0';
    	init_mod_fem_viewer(argc,argv,interactive_output);
    }

    // solving the problem with direct solver
    else if(c=='u'){
      
#ifndef PARALLEL

      /* very simple time measurement */
      t_wall=time_clock();

      /* problem dependent interface with linear solvers */
      sprintf(arg,"%s/pardiso.dat", work_dir);

      sir_direct_solve_lin_sys(problem_id, SIC_SEQUENTIAL, arg);

      /* very simple time measurement */
      t_wall=time_clock()-t_wall;
      
      fprintf(interactive_output,
	      "\nTime for solving a system of linear equations %lf\n\n",t_wall);
#endif

    }
    else if(c=='s'){
      
      
#ifdef PARALLEL
    if(pcr_my_proc_id()==pcr_print_master()){
#endif
      fprintf(interactive_output,
	"\nBeginning solution of the test problem - Laplace's equation\n\n");
#ifdef PARALLEL
    }
#endif
      
      /* very simple time measurement */
      t_wall=time_clock();
      
#ifdef PARALLEL
      {
	int ione = 1;
/* initiate exchange tables for DOFs - for one field = one solver, one level */
	appr_init_exchange_tables(pcr_nr_proc(), pcr_my_proc_id(), 1, &ione);
      }
#endif

      /* problem dependent interface with linear solvers */
      sprintf(arg,"%s/solver.dat", work_dir);

#ifndef PARALLEL
      sir_solve_lin_sys(problem_id, SIC_SEQUENTIAL, arg, // below: defaults
			-1, //pdr_lins_i_params(problem_id, 2), // max_iter
			-1, //pdr_lins_i_params(problem_id, 3), // error_type
			-1.0, //pdr_lins_d_params(problem_id, 4), // error_tol
			-1 //pdr_lins_i_params(problem_id, 5) // monitor level
			);
#endif
      
#ifdef PARALLEL
      sir_solve_lin_sys(problem_id, SIC_PARALLEL, arg, // below: defaults
			-1, //pdr_lins_i_params(problem_id, 2), // max_iter
			-1, //pdr_lins_i_params(problem_id, 3), // error_type
			-1.0, //pdr_lins_d_params(problem_id, 4), // error_tol
			-1 //pdr_lins_i_params(problem_id, 5) // monitor level
			);
/* free exchange tables for DOFs - for one field = one solver */
      appr_free_exchange_tables(1);
#endif

      /* very simple time measurement */
      t_wall=time_clock()-t_wall;
      
#ifdef PARALLEL
    if(pcr_my_proc_id()==pcr_print_master()){
#endif
      fprintf(interactive_output,
	      "\nTime for solving a system of linear equations %lf\n\n",t_wall);
      
#ifdef PARALLEL
    }
#endif
    }

    // computing error
    else if(c=='e'){
      
      double error_h1;
      /* simple L2 and H1 error for the test problem (with known exact solution) */
      error_h1 = pdr_error_test(field_id,interactive_output);
      
    }
    else if(c=='z'){
      
      double error_ZZ;
      /* Zienkiewicz-Zhu error estimator */
      error_ZZ = pdr_zzhu_error(field_id,interactive_output);
      
    }

    // performing simple post-processing
    else if(c=='p'){
      
      pdr_post_process(field_id,interactive_input,interactive_output);
      
    }
    else if(c=='a'){
      
      /* adaptation based on Zienkiewicz-Zhu error estimator */
      pdr_adapt(problem_id, work_dir, 
		interactive_input, interactive_output );
      
    }

    // manual mesh adaptation
    else if(c=='m'){
      
      utr_manual_refinement( problem_id, work_dir, 
			     interactive_input, interactive_output );
      
      
    }

    // testing refinement/derefinement procedures
    else if(c=='r'){
      
      utr_test_refinements(problem_id, work_dir, 
			   interactive_input, interactive_output );
      
    } /* end test of mesh refinements */
    
  } while(c != 'q');
  
  /* free allocated space */
  apr_free_field(field_id);
  mmr_free_mesh(mesh_id);

  fclose(interactive_input);
  fclose(interactive_output);

#ifdef PARALLEL
  pcr_exit_parallel();
#endif

  return(0);

}
Example #9
0
/*---------------------------------------------------------
  tmr_ocl_init - to initialize OpenCL thread management
---------------------------------------------------------*/
int tmr_ocl_init(
  char* Work_dir,
  FILE *Interactive_input,
  FILE *Interactive_output,
  int Control,  // OpenCL device type
  int Monitor
)
{

  // MONITOR SHOULD BE PASSED AS PARAMETER !!!!!!!!!!!!!!!!!!!!!!
  // for all operations indicate explicit info messages
  //int Monitor = TMC_PRINT_INFO + 1;
  
#ifdef TIME_TEST
  double t_begin, t_end;
  t_begin = time_clock();
#endif
  
  // Create OpenCL contexts on all available platforms
  // contexts are stored in table with indices: 0-CPU, 1-GPU, 2-ACCELERATOR
  // table entry is NULL if there is no such context for a given platform
  int number_of_platforms = tmr_ocl_create_contexts(Interactive_output,
						    TMC_OCL_ALL_PLATFORMS, Monitor);
  
#ifdef DEBUG_TMM  
  if(number_of_platforms>1){
    fprintf(Interactive_output,
	    "\nMore than one platform in a system! Check whether it's OK with the code.\n");
  }
#endif

  if(number_of_platforms>1){
    if(Interactive_input == stdin){
      fprintf(Interactive_output,
	      "\nSelect platform ID (index): ");
      fscanf(Interactive_input, "%d", &tmv_ocl_struct.current_platform_index);
      //tmv_ocl_struct.current_platform_index = 0;

    }
    else{ // if input from file - first platform selected

      tmv_ocl_struct.current_platform_index = 0;

    }

  }
  else{ // if only one platform - first platform selected
    
    tmv_ocl_struct.current_platform_index = 0;
    
  }
  
  fprintf(Interactive_output,
	  "\nSelected platform ID (index): %d", 
	  tmv_ocl_struct.current_platform_index);


#ifdef TIME_TEST
  t_end = time_clock();
  fprintf(Interactive_output,"EXECUTION TIME: creating contexts: %lf\n", t_end-t_begin);
#endif
  
#ifdef TIME_TEST
  t_begin = time_clock();
#endif
  

  int platform_index = tmv_ocl_struct.current_platform_index;
  // or better
  // int platform_index = tmr_ocl_get_current_platform_index();

  // create command queues on all devices 
  tmr_ocl_create_command_queues(Interactive_output, platform_index, 
				TMC_OCL_ALL_DEVICES, Monitor);
  
#ifdef TIME_TEST
  t_end = time_clock();
  fprintf(Interactive_output,"EXECUTION TIME: creating command queues: %lf\n", 
	  t_end-t_begin);
#endif
  
  //cl_platform_id platform = tmv_ocl_struct.list_of_platforms[platform_index].id;
  tmt_ocl_platform_struct platform_struct = 
    tmv_ocl_struct.list_of_platforms[platform_index];
  
/*-------------- KERNEL CREATION PHASE--------------------*/

  int device_tmc_type=Control;
  tmv_ocl_struct.current_device_type=Control;
  int device_index;
  int kernel_index = TMC_OCL_KERNEL_NUM_INT_GENERIC;

#ifdef TIME_TEST
  t_begin = time_clock();
#endif


  if(Monitor>TMC_PRINT_INFO){
    if(device_tmc_type==0){
      fprintf(Interactive_output, 
	      "\nSelecting OpenCL device type %d (CPU) for platform %d\n", 
	      device_tmc_type, platform_index);
    }
    else if(device_tmc_type==1){
      fprintf(Interactive_output, 
	      "\nSelecting OpenCL device type %d (GPU) for platform %d\n", 
	      device_tmc_type, platform_index);
    }
    else if(device_tmc_type==2){
      fprintf(Interactive_output, 
	      "\nSelecting OpenCL device type %d (ACCELERATOR) for platform %d\n", 
	      device_tmc_type, platform_index);
    }
    else {
      fprintf(Interactive_output, 
	      "\nUnknown OpenCL device type %d for platform %d. Exiting!\n", 
	      device_tmc_type, platform_index);
      exit(-1);
    }
  }

  // choose device_index
  device_index = tmr_ocl_select_device(platform_index, device_tmc_type);

  // if required context exists
  if(device_index >= 0){

    // create the kernel for numerical integration
    kernel_index = TMC_OCL_KERNEL_NUM_INT_INDEX;

    if(Monitor>TMC_PRINT_INFO){
      fprintf(Interactive_output, 
	      "\nCreating OpenCL kernel %d for device type %d and device index %d\n", 
	      kernel_index, device_tmc_type, device_index);
    }

    // !!!!!!!!!!!!!!!!!!!!!!????????????????!!!!!!!!!!!!!!!!!!!!!!!
    // APART FROM DIFFERENT KERNELS FOR DIFFERENT HARDWARE, THERE ARE
    // DIFFERENT KERNEL VERSIONS FOR DIFFERENT ALGORITHMS;
    // FROM tmd_ocl/tmh_ocl.h:
// numerical integration kernel versions depending on hardware
//#define TMC_OCL_KERNEL_NUM_INT_GENERIC   0
//#define TMC_OCL_KERNEL_NUM_INT_CPU_OPT   1
//#define TMC_OCL_KERNEL_NUM_INT_GPU_OPT   2
//#define TMC_OCL_KERNEL_NUM_INT_CELL_OPT  3

// numerical integration kernel versions depending on algorithm
//#define TMC_OCL_KERNEL_NUM_INT_ONE_EL_ONE_THREAD    1
//#define TMC_OCL_KERNEL_NUM_INT_ONE_EL_ONE_WORKGROUP 2

    // HARDCODED DEFAULT
    platform_struct.list_of_devices[device_index].num_int_kernel_version = 0;
    int kernel_version_hw = 0;
    int kernel_version_alg = 0; 

  // BELOW IT IS READ FROM INPUT:
  // IT SHOULD BE BASED ON INPUT PARAMETERS FOR OPENCL !!!!!!!!!!!!!!!
    /* if(Interactive_input == stdin){ */

    /*   printf("Select kernel version (kernel_version_hw + 10*kernel_version_alg): \n"); */
    /*   printf("see tmd_ocl/tmh_ocl.h for details\n"); */
    /*   // HARDCODED DEFAULT */
    /*   int i = 0; */
    /*   fscanf(Interactive_input, "%d", &i); */
    /*   platform_struct.list_of_devices[device_index].num_int_kernel_version = i; */
    /*   int kernel_version_hw = i%10; */
    /*   int kernel_version_alg = i/10;  */

    /* } */


  // BASED ON INPUT PARAMETERS SELECT OPENCL KERNEL FOR NUMERICAL INTEGRATION !!!!!!!
    if(kernel_index == TMC_OCL_KERNEL_NUM_INT_GENERIC){
      tmr_ocl_create_kernel(Interactive_output,platform_index,device_index,kernel_index,
	// kernel name:         , file:
        "tmr_ocl_num_int_el", "tmr_ocl_num_int_el.cl", Monitor);
    }
    /* else if(kernel_index == TMC_OCL_KERNEL_NUM_INT_CPU_OPT){ */

    /*   tmr_ocl_create_kernel(Interactive_output,platform_index,device_index,kernel_index, */
    /* 	   // kernel name:         , file: */
    /*     "tmr_ocl_num_int_el", "tmr_ocl_num_int_el_cpu.cl", Monitor); */
    /* } */
    /* else if(kernel_index == TMC_OCL_KERNEL_NUM_INT_GPU_OPT){ */

    /*   tmr_ocl_create_kernel(Interactive_output,platform_index,device_index,kernel_index, */
    /* 	   // kernel name:         , file: */
    /*     "tmr_ocl_num_int_el", "tmr_ocl_num_int_el_gpu.cl", Monitor); */
    /* } */
    /* else if(kernel_index == TMC_OCL_KERNEL_NUM_INT_CELL_OPT){ */

    /*   tmr_ocl_create_kernel(Interactive_output,platform_index,device_index,kernel_index, */
    /* 	   // kernel name:         , file: */
    /*     "tmr_ocl_num_int_el", "tmr_ocl_num_int_el_cell.cl", Monitor); */
    /* } */

#ifdef TIME_TEST
    t_end = time_clock();
    fprintf(Interactive_output,"EXECUTION TIME: creating OpenCL kernel for integration: %lf\n", t_end-t_begin);
#endif
  
  }
  else{
      fprintf(Interactive_output,"Requested device not supported for this platform.\n");
      exit(-1);
  }

  return(1);
}