Пример #1
0
/*------------------------------------------------------------------------*/
int set_format_n_property(void* _pvCtx, char* pobjUID, void* _pvData, int valueType, int nbRow, int nbCol)
{
    BOOL status = FALSE;
    char* format = NULL;
    char * oldFormat = NULL;
    StringMatrix * labels = NULL;

    if (valueType != sci_strings)
    {
        Scierror(999, _("Wrong type for '%s' property: String expected.\n"), "format_n");
        return SET_PROPERTY_ERROR;
    }

    format = (char*)_pvData;

    getGraphicObjectProperty(pobjUID, __GO_FORMATN__, jni_string, (void **)&oldFormat);

    if (strcmp(format, oldFormat) == 0)
    {
        return SET_PROPERTY_SUCCEED;
    }

    status = setGraphicObjectProperty(pobjUID, __GO_FORMATN__, format, jni_string, 1);
    if (status == TRUE)
    {
        labels = computeDefaultTicsLabels(pobjUID);
        if (labels != NULL)
        {
            char ** data = getStrMatData(labels);
            setGraphicObjectProperty(pobjUID, __GO_TICKS_LABELS__, data, jni_string_vector, labels->nbCol * labels->nbRow);
            deleteMatrix(labels);
        }

        return SET_PROPERTY_SUCCEED;
    }
    else
    {
        Scierror(999, _("'%s' property does not exist for this handle.\n"), "format_n");
        return SET_PROPERTY_ERROR;
    }
}
Пример #2
0
int main (int argc, char* argv[])
{
	srand48(time(NULL));
	
	int fd, dupSTDIN, i;
	struct stat buffer;
		
	if (argc > 1)
	{
		stat(argv[1], &buffer);
		if ((buffer.st_mode & S_IFMT)==S_IFREG)
		{
			fd = open(argv[1], O_RDONLY);
			dupSTDIN = dup(0);
			dup2(fd, 0);
			
			LaunchInterpreter();
	
			close(fd);
			close(0);
			dup(dupSTDIN);
			close(dupSTDIN);
		}
		else
		{
			printf("\t%s : non regular file\n", argv[1]);
			return 1;
		}
	}
	else LaunchInterpreter();
	
	for (i=0; i<cur_var; i++) free(vars[i]);
	for (i=0; i<cur_mat; i++)
	{
		deleteMatrix(mats[i]->mat);
		free(mats[i]);
	}
	
	return 0;
}
Пример #3
0
void gcm::PQsubspace(double** C, double** PQ_subspace)
{
	//SVD to obtain the subspace
	double* w;
	w = new double[nDimension];
	double **v;
	v = newMatrix(nDimension,nDimension);

	gcmSVD.svdcmp(C, nDimension, nDimension, w, v);

	//The C[all][reDim =10] is the subspace
	for (int i=0; i<nDimension; i++)
	{
		for (int j=0; j<subspaceDim; j++)
		{
			PQ_subspace[i][j] = C[i][j];
		}
	}

	//Release
	//deleteMatrix(C,nDimension);
	delete w;
	deleteMatrix(v, nDimension);
}
Пример #4
0
/*
int ClusterHop(SNarray snA, Charge one, int * totalX);

char *outname = "t-I.txt";
char buffer[30], buffer2[30], buffer3[30];

int main(){

	mem_init();      
	atexit(mem_term);

	//real number of charges in the real materials, area = 0.11 (cm*cm)
 	double rN;
  double electricField;
	double electricEnergy;
	int r, l, j, n;
  int AV_Xrundist_counter[N_av+1][2*SLength+1];
	int Xrundist_counter[N_av+1][2*SLength+1];
  double Vindex[2*SLength+1];
	double currentR[TCount+1];
	int currentR_av[TCount+1];
	int rv;
	double ncR[TCount+1];
	double ncR_av[TCount+1];
	double nelec_drainR[TCount+1];
	double nelec_drainR_av[TCount+1];

  electricField = voltage / (SLength * SiteDistance);
	//if SiteDistance = 1E-7 and electricField = 6E5; then electricEnergy = 0.06 
	electricEnergy = SiteDistance * electricField; 

  rN = 1.272E10 + 2.0789E10 * pow(voltage, 0.77388);
  printf("rN is %g\n", rN);

  for (j = 0 ; j < 2 * SLength + 1 ; j++) {
		//initialize velocity array
    Vindex[j]= 0;   
		//assign velocity values
		Vindex[j]= ((j-SLength) * SiteDistance) / (Nstep_av*TStep); 
    
		for (l = 1; l < N_av+1; l++) {
      AV_Xrundist_counter[l][j]=0;
    }
  }
  
  for(n=0;n<TCount;n++){
    currentR[n]=0;
    ncR[n]=0;
    nelec_drainR[n]=0;
  }

  for (r=1;r<Rcount+1;r++){

    printf("Seed iteration # = %d\n", r);
		//set seed of random function
    srand(rdtsc());
		//set seed of random function
    srandom(rdtsc()); 

		SNarray snA = newSNarray(SLength,SWidth,SHeight);
    initSite(electricEnergy, snA);
		//Determine Clusters
		ArbArray ClArLL;
		ArbArray NeighClArLL;
		
		//ArbArrayCheck(ClArLL);
		FindCluster( snA, electricEnergy, &ClArLL, &NeighClArLL);

		rv=ArbArrayCheck(ClArLL);
		assert(rv!=-1);
		rv=ArbArrayCheck(NeighClArLL);
		assert(rv!=-1);

    printf("Past initSite\n");
    randomWalk( snA, rN, Xrundist_counter, currentR, ncR, nelec_drainR);
    printf("Past randomWalk\n");
		rv=ArbArrayCheck(ClArLL);
		assert(rv!=-1);
		rv=ArbArrayCheck(NeighClArLL);
		assert(rv!=-1);


    for (l = 1; l < N_av+1; l++) {
      for ( j = 0 ; j < 2 * SLength + 1 ; j++){
        AV_Xrundist_counter[l][j] += Xrundist_counter[l][j];
      }
    }

    for(n=0;n<TCount;n++){
      currentR_av[n]+=currentR[n];
      ncR_av[n]+=ncR[n];
      nelec_drainR_av[n]+=nelec_drainR[n];
    }

    if(r==Rcount){
      
			printf("Rcount is reached, computing average\n");
      for(n=0;n<TCount;n++){
        currentR_av[n]=currentR_av[n]/Rcount;
        ncR_av[n]=ncR_av[n]/Rcount;
        nelec_drainR_av[n]=nelec_drainR_av[n]/Rcount;
      }
      FILE *AV_tI;
      int coincoin = sprintf(buffer3, "AV_tI.txt");
      char *outname4 = buffer3;

      if((AV_tI = fopen(outname4, "w")) == NULL)
        printf("Could not open output file outname4.\n");   

      fprintf(AV_tI, "Length of sample in cm: %g \n",SLength*SiteDistance);
			fprintf(AV_tI, "Time interval in s: %g \n",TStep);
			fprintf(AV_tI, "Number of charges: %d \n",NCh);
			fprintf(AV_tI, "Applied voltage in V : %g \n", voltage);

      for(n=0;n<TCount;n++){
        fprintf(AV_tI, "%g \t %d \t %g \t %g \n", \
						n*TStep, currentR_av[n], ncR_av[n], nelec_drainR_av[n]);
      }
      fclose(AV_tI);


      for (l = 1; l < N_av+1; l++) {
        FILE *AV_velocity_file;
        int coincoin = sprintf(buffer2, "velocity_dist_AV_%d.txt", l);
        char *outname3 = buffer2;
        if((AV_velocity_file = fopen(outname3, "w")) == NULL)
          printf("Could not open output file outname3.\n");   

        fprintf(AV_velocity_file, "Length of sample in cm: %g \n",SLength*SiteDistance);
				fprintf(AV_velocity_file,"Time interval in s: %g \n",TStep);
				fprintf(AV_velocity_file,"Number of charges: %d \n",NCh);
				fprintf(AV_velocity_file,"Applied voltage in V : %g \n",voltage);
				fprintf(AV_velocity_file,"Time over which velocity is averaged in s: %g \n",Nstep_av*TStep);
				fprintf(AV_velocity_file,"Total number of averaging steps: %d \n",N_av);
				fprintf(AV_velocity_file,"Averaging step #: %d/%d \n",l, N_av);
        fprintf(AV_velocity_file, "l%d\tDistribution counter_av_%d \t",l,l);
				fprintf(AV_velocity_file,"Velocity in cm/s_av%d \t",l);
				fprintf(AV_velocity_file,"Number of counts_av%d \n", l); 

        for ( j = 0 ; j < 2 * SLength + 1 ; j++){
          fprintf(AV_velocity_file, "%d \t %d \t %g \t %d \n", l, j, Vindex[j], AV_Xrundist_counter[l][j]);
        }
        fclose(AV_velocity_file);
      }
    }
		printf("Here2\n");
		assert(ClArLL!=NULL);
	//Delete ClArLL and Neigh ClArLL
		printf("Here2.5\n");
		rv=deleteArbArray(ClArLL);
		assert(rv!=-1);
		printf("Here2.6\n");
		rv=deleteArbArray(NeighClArLL);
		assert(rv!=-1);
		printf("Here3\n");
		deleteSNarray(snA);
		printf("Here3.5\n");

  }

  int t;
  for ( t=0;t< SLength;t++) {
    printf("t is %d\t",t);
  }

			printf("Here4\n");

  return 0;
}
*/
int SiteHop(SNarray snA, Charge one, SiteNode site, int * totalX, int * totalY, int * totalZ, const int EndX, const int EndY, const int EndZ, const int XElecOn, const int YElecOn, const int ZElecOn, const int PeriodicX, const int PeriodicY, const int PeriodicZ){

	//totalX is used to measure the total current in the X direction as the charges move around
	//totalY is used to measure the total current in the Y direction as the charges move around
	//totalZ is used to measure the total current in the Z direction as the charges move around
	if((PeriodicX==1 && EndX==-1)	|| (PeriodicX==0 && EndX>0) ||\
     (PeriodicY==1 && EndY==-1)	|| (PeriodicY==0 && EndY>0) ||\
		 (PeriodicZ==1 && EndZ==-1)	|| (PeriodicZ==0 && EndZ>0)){
		return -1;
	}

	if((EndX==0 && XElecOn==1) ||\
		 (EndY==0 && YElecOn==1) ||\
		 (EndZ==0 && ZElecOn==1)){
		return -1;
	}

	if(snA==NULL || one == NULL || site ==NULL){
		return -1;
	}

	//Initially, the flag is set to 0 
	//means the charge is able to hop
	int flag = 0; 
  double position;
  int middle;
	int rv;
	int l;
	//Below values define location of the charge in the
	//sample when the periodicity is removed
	int x;
	int y;
	int z;
	int SLength;
	int SWidth;
	int SHeight;

	SLength = getAlen(snA);
	SWidth = getAwid(snA);
	SHeight = getAhei(snA);
	//First Check is to see if all the neighboring sites are occupied. 
	//If the site is not located at a boundary
	//If they are all occupied set the flag to 1
	x = getCx(one)%SLength;
	y = getCy(one)%SWidth;
	z = getCz(one)%SHeight;
	
	//This is the random number used to determine which direction a charge hops
	position = (double)rand() / RAND_MAX;
	
	if(x!=0 && x!=(SLength-1) && y!=0 && y!=(SWidth-1) && z!=0 && z!=(SHeight-1)){
		rv = OccAllNei(snA, x, y, z);
		if (rv==1){
			//All neighboring sites are occupied
			flag=1;
		}

		if(flag==0){

			l=0;
			//Cycle through the pvals until the pval
			//is equal or above the random number
			while( getSN_p(site,l)<position){
				l++;
			}
			middle = l;
		


		}

	}else{
		//If the charge is at a boundary requires special attention
		int codeX;
		int codeY;
		int codeZ;

		if (PeriodicX==1){
		//Periodic in x
			if(EndX==0){
			//In this case the charge will never hit a boundary
				codeX=0;

			}else{
			//Charge might hit boundary depending on how many samples
			//charge has traveled through

				if (XElecOn==1){
				//If there are electrodes at the boundaries will always include the pvals
					codeX==0;
				}else{
					if(x==0){
					//Need to determine if charge is at the edge of the boundaries.
						if(getCx(one)/SLength==0){
						//Means it is at the boundary
							codeX=1;
						}else{
						//Means not at the boundary
							codeX=0;
						}
					}else if(x==(SLength-1)){
						
						if(getCx(one)/SLength==EndX-1){
							//Hop forward is not allowed 
							codeX=2;
						}else{
							codeX=0;
						}
					}else{
						codeX=0;
					}
				
				}
			
			}

		}else{
		//Non periodic in x
			if(XElecOn==0){
			//This means there are no electrodes on the yz electrodes
			//on the x axis
				if(x==0){
					codeX=1;
				}else if(x==SLength-1){
					codeX=2;
				}else{
					codeX=0;
				}
			}else{
			//There are electrodes
				codeX=0;
			}
		}

		if (PeriodicY==1){
		//Periodic in y
			if(EndY==0){
			//In this case the charge will never hit a boundary
				codeY=0;

			}else{
			//Charge might hit boundary depending on how many samples
			//charge has traveled through
	
				if(YElecOn==1){
					codeY==0;
				}else{
					if(y==0){
						if(getCy(one)/SWidth==0){
							codeY=1;
						}else{
							codeY=0;
						}
					}else if(y==(SWidth-1)){
						if(getCy(one)/SWidth==EndY-1){
							codeY=2;
						}else{
							codeY=0;
						}
					}else{
						codeY=0;
					}
				}

			}

		}else{
		//Non periodic in y
			if(YElecOn==0){
			//This means there are no electrodes on the yz electrodes
			//on the x axis
				if(y==0){
					codeY=1;
				}else if(y==SWidth-1){
					codeY=2;
				}else{
					codeY=0;
				}
			}else{
				codeY=0;
			}

		}

		if (PeriodicZ==1){
		//Periodic in z
			if(EndZ==0){
			//In this case the charge will never hit a boundary
				codeZ==0;

			}else{
			//Charge might hit boundary depending on how many samples
			//charge has traveled through
				if(ZElecOn==1){
					codeZ==0;
				}else{
					if(z==0){
						if(getCz(one)/SHeight==0){
							codeZ=1;
						}else{
							codeZ=0;
						}
					}else if(z==(SHeight-1)){
						if(getCz(one)/SWidth==EndZ-1){
							codeZ=2;
						}else{
							codeZ=0;
						}
					}else{
						codeZ=0;
					}
				}
			}
		}else{
		//Non periodic in z

			if(ZElecOn==0){
			//This means there are no electrodes on the yz electrodes
			//on the x axis
				if(z==0){
					codeZ=1;
				}else if(z==SHeight-1){
					codeZ=2;
				}else{
					codeZ=0;
				}
			}else{
				codeZ=0;
			}
		}

		//codeX values:
		//0 - can hop to +x and -X
		//1 - cannot hop to -x
		//2 - cannot hop to +x
		//codeY values:
		//0 - can hop to +y and -y
		//1 - cannot hop to -y
		//2 - cannot hop to +y
		//codeZ values:
		//0 - can hop to +z and -z
		//1 - cannot hop to -z
		//2 - cannot hop to +z
		double value;

		if(codeX==0 && codeY==0 && codeZ==0){
			position = (double)rand() / RAND_MAX;
			l=0;
			//Cycle through the pvals until the pval
			//is equal or above the random number
			while( getSN_p(site,l)<position){
				l++;
			}
			middle = l;
		}else if(codeX>0 && codeY==0 && codeZ==0){
			//Need to redefine the pvals
			matrix mtxPval = newMatrix(5,1);
			if(codeX==1){
			//Ignore the hop forward
				value = getSN_p(site,0);
				setE(mtxPval,1,1,value);
				value += getSN_p(site,2)-getSN_p(site,1);
				setE(mtxPval,2,1,value);
				value += getSN_p(site,3)-getSN_p(site,2);
				setE(mtxPval,3,1,value);
				value += getSN_p(site,4)-getSN_p(site,3);
				setE(mtxPval,4,1,value);
				value += getSN_p(site,5)-getSN_p(site,4);
				setE(mtxPval,5,1,value);

				DivideEachElement(&mtxPval,value);

				l=1;
				//Cycle through the pvals until the pval
				//is equal or above the random number
				while( getE(mtxPval,l,1)<position){
					l++;
				}
				
				if(l==1){
					l=0;
				}
				middle = l;
				deleteMatrix(mtxPval);

			}else{
			//Ignore the hop backward
				value = getSN_p(site,1)-getSN_p(site,0);
				setE(mtxPval,1,1,value);
				value += getSN_p(site,2)-getSN_p(site,1);
				setE(mtxPval,2,1,value);
				value += getSN_p(site,3)-getSN_p(site,2);
				setE(mtxPval,3,1,value);
				value += getSN_p(site,4)-getSN_p(site,3);
				setE(mtxPval,4,1,value);
				value += getSN_p(site,5)-getSN_p(site,4);
				setE(mtxPval,5,1,value);

				DivideEachElement(&mtxPval,value);

				l=1;
				//Cycle through the pvals until the pval
				//is equal or above the random number
				while( getE(mtxPval,l,1)<position){
					l++;
				}
				
				middle = l;
				deleteMatrix(mtxPval);

			}
		}else if(codeX==0 && codeY>0 && codeZ==0){
			matrix mtxPval = newMatrix(5,1);
			if(codeY==1){
			//Not allowed to hop to the left or -y
				value = getSN_p(site,0);
				setE(mtxPval,1,1,value);
				value += getSN_p(site,1)-getSN_p(site,0);
				setE(mtxPval,2,1,value);
				value += getSN_p(site,3)-getSN_p(site,2);
				setE(mtxPval,3,1,value);
				value += getSN_p(site,4)-getSN_p(site,3);
				setE(mtxPval,4,1,value);
				value += getSN_p(site,5)-getSN_p(site,4);
				setE(mtxPval,5,1,value);

				DivideEachElement(&mtxPval,value);

				l=1;
				//Cycle through the pvals until the pval
				//is equal or above the random number
				while( getE(mtxPval,l,1)<position){
					l++;
				}
			
				if(l<=2){
					l--;
				}

				middle = l;
				deleteMatrix(mtxPval);

			}else{
			//Not allowed to hop to the right or +y
				value = getSN_p(site,0);
				setE(mtxPval,1,1,value);
				value += getSN_p(site,1)-getSN_p(site,0);
				setE(mtxPval,2,1,value);
				value += getSN_p(site,2)-getSN_p(site,1);
				setE(mtxPval,3,1,value);
				value += getSN_p(site,4)-getSN_p(site,3);
				setE(mtxPval,4,1,value);
				value += getSN_p(site,5)-getSN_p(site,4);
				setE(mtxPval,5,1,value);

				DivideEachElement(&mtxPval,value);

				l=1;
				//Cycle through the pvals until the pval
				//is equal or above the random number
				while( getE(mtxPval,l,1)<position){
					l++;
				}
			
				if(l<=3){
					l--;
				}

				middle = l;
				deleteMatrix(mtxPval);

			}
		}else if(codeX==0 && codeY==0 && codeZ>0){
			matrix mtxPval = newMatrix(5,1);
			if(codeZ==1){
			//Cannot hop Below
				value = getSN_p(site,0);
				setE(mtxPval,1,1,value);
				value += getSN_p(site,1)-getSN_p(site,0);
				setE(mtxPval,2,1,value);
				value += getSN_p(site,2)-getSN_p(site,1);
				setE(mtxPval,3,1,value);
				value += getSN_p(site,3)-getSN_p(site,2);
				setE(mtxPval,4,1,value);
				value += getSN_p(site,5)-getSN_p(site,4);
				setE(mtxPval,5,1,value);

				DivideEachElement(&mtxPval,value);

				l=1;
				//Cycle through the pvals until the pval
				//is equal or above the random number
				while( getE(mtxPval,l,1)<position){
					l++;
				}
			
				if(l<=4){
					l--;
				}

				middle = l;
				deleteMatrix(mtxPval);

			}else{
			//Cannot hop Above
				value = getSN_p(site,0);
				setE(mtxPval,1,1,value);
				value += getSN_p(site,1)-getSN_p(site,0);
				setE(mtxPval,2,1,value);
				value += getSN_p(site,2)-getSN_p(site,1);
				setE(mtxPval,3,1,value);
				value += getSN_p(site,3)-getSN_p(site,2);
				setE(mtxPval,4,1,value);
				value += getSN_p(site,4)-getSN_p(site,3);
				setE(mtxPval,5,1,value);

				DivideEachElement(&mtxPval,value);

				l=1;
				//Cycle through the pvals until the pval
				//is equal or above the random number
				while( getE(mtxPval,l,1)<position){
					l++;
				}
			
				if(l<=5){
					l--;
				}

				middle = l;
				deleteMatrix(mtxPval);

			}
		}else if(codeX>0 && codeY>0 && codeZ==0){
			matrix mtxPval = newMatrix(4,1);
			if(codeX==1){
				//Not allowed to hop forward
				value = getSN_p(site,0);
				setE(mtxPval,1,1,value);
			}else{
				//Not allowed to hop backward
				value = getSN_p(site,1)-getSN_p(site,0);
				setE(mtxPval,1,1,value);
			}

			if(codeY==1){
				//Not allowed to hop to the left
				value += getSN_p(site,3)-getSN_p(site,2);
				setE(mtxPval,2,1,value);
			}else{
				//Not allowed to hop to the right
				value += getSN_p(site,2)-getSN_p(site,1);
				setE(mtxPval,2,1,value);
			}
			value += getSN_p(site,4)-getSN_p(site,3);
			setE(mtxPval,3,1,value);
			value += getSN_p(site,5)-getSN_p(site,4);
			setE(mtxPval,4,1,value);

			DivideEachElement(&mtxPval,value);

			l=1;
			//Cycle through the pvals until the pval
			//is equal or above the random number
			while( getE(mtxPval,l,1)<position){
				l++;
			}
		
			if(l>=3){
				l++;
			}else	if(l==2){
				if(codeY==1){
					l=3;	
				}else{
					l=2;
				}
			}else	if(l==1){
				if(codeX==1){
					l=0;
				}else{
					l=1;
				}
			}

			middle = l;
			deleteMatrix(mtxPval);


		}else if(codeX==0 && codeY>0 && codeZ>0){
			matrix mtxPval = newMatrix(4,1);
			
			value = getSN_p(site,0);
			setE(mtxPval,1,1,value);
			value += getSN_p(site,1)-getSN_p(site,0);
			setE(mtxPval,2,1,value);
		
			if(codeY==1){
				//Not allowed to hop to the left
				value += getSN_p(site,3)-getSN_p(site,2);
				setE(mtxPval,3,1,value);
			}else{
				//Not allowed to hop to the right
				value += getSN_p(site,2)-getSN_p(site,1);
				setE(mtxPval,3,1,value);
			}
			if(codeZ==1){
				//Not allowed to hop below
				value += getSN_p(site,5)-getSN_p(site,4);
				setE(mtxPval,4,1,value);
			}else{
				//Not allowed to hop backward
				value += getSN_p(site,4)-getSN_p(site,3);
				setE(mtxPval,4,1,value);
			}
			
			DivideEachElement(&mtxPval,value);

			l=1;
			//Cycle through the pvals until the pval
			//is equal or above the random number
			while( getE(mtxPval,l,1)<position){
				l++;
			}
		
			if(l<3){
				l--;
			}else if(l==3){
				if(codeY==1){
					l=3;
				}else{
					l=2;
				}
			}else{
				if(codeZ==1){
					l=5;
				}else {
					l=4;
				}
			}
			
			middle = l;
			deleteMatrix(mtxPval);
			
		}else if(codeX>0 && codeY==0 && codeZ>0){
			matrix mtxPval = newMatrix(4,1);
			
			if(codeX==1){
				//Not allowed to hop forward
				value = getSN_p(site,0);
				setE(mtxPval,1,1,value);
			}else{
				//Not allowed to hop backward
				value = getSN_p(site,1)-getSN_p(site,0);
				setE(mtxPval,1,1,value);
			}

			value += getSN_p(site,2)-getSN_p(site,1);
			setE(mtxPval,2,1,value);
			value += getSN_p(site,3)-getSN_p(site,2);
			setE(mtxPval,3,1,value);

			if(codeZ==1){
				//Not allowed to hop below
				value += getSN_p(site,5)-getSN_p(site,4);
				setE(mtxPval,4,1,value);
			}else{
				//Not allowed to hop backward
				value += getSN_p(site,4)-getSN_p(site,3);
				setE(mtxPval,4,1,value);
			}
			
			DivideEachElement(&mtxPval,value);

			l=1;
			//Cycle through the pvals until the pval
			//is equal or above the random number
			while( getE(mtxPval,l,1)<position){
				l++;
			}
	
			if(l==1){
				if(codeX==1){
					l=0;
				}else{
					l=1;
				}
			}else if(l==4){
				if(codeZ==1){
					l=5;
				}else{
					l=4;
				}
			}else{
				l=l;
			}
				
			middle = l;
			deleteMatrix(mtxPval);
		
		}else{
			matrix mtxPval = newMatrix(3,1);
			
			if(codeX==1){
				//Not allowed to hop forward
				value = getSN_p(site,0);
				setE(mtxPval,1,1,value);
			}else{
				//Not allowed to hop backward
				value = getSN_p(site,1)-getSN_p(site,0);
				setE(mtxPval,1,1,value);
			}
			if(codeY==1){
				//Not allowed to hop to the left
				value += getSN_p(site,3)-getSN_p(site,2);
				setE(mtxPval,2,1,value);
			}else{
				//Not allowed to hop to the right
				value += getSN_p(site,2)-getSN_p(site,1);
				setE(mtxPval,2,1,value);
			}
			if(codeZ==1){
				//Not allowed to hop below
				value += getSN_p(site,5)-getSN_p(site,4);
				setE(mtxPval,3,1,value);
			}else{
				//Not allowed to hop backward
				value += getSN_p(site,4)-getSN_p(site,3);
				setE(mtxPval,3,1,value);
			}
	
			DivideEachElement(&mtxPval,value);

			l=1;
			//Cycle through the pvals until the pval
			//is equal or above the random number
			while( getE(mtxPval,l,1)<position){
				l++;
			}
	
			if(l==1){
				if(codeX==1){
					l=0;
				}else{
					l=1;
				}
			}else if(l==2){
				if(codeY==1){
					l=3;
				}else{
					l=2;
				}
			}else{
				if(codeZ==1){
					l=5;
				}else{
					l=4;
				}
			}

			middle = l;
			deleteMatrix(mtxPval);
		}

	}

	//l value
	//0 - backward 	x-
	//1 - forward 	x+
	//2 - left 			y-
	//3 - right 		y+
	//4 - below 		z-
	//5 - above	 		z+

	if(flag!=1){		
		switch(middle){
		//if the charge is on the illuminated electrode (x=0), it recombines there,
		//ie negative current
		case 0: if( OccXneg(snA, x, y, z)==1) {
							//there is no possibility to hopp
							flag = 1;   
							break;
						}
						//Move the charge backward
						CxMinus(one);
						//current decreases in x
						*totalX=*totalX-1;  
						break;

						//if the charge is adjacent to the opposite electrode (x=Length), 
						//it recombines there, ie positive current
		case 1: if( OccXpos(snA, x,y ,z)== 1){  
							//there is no possibility to hop
							flag = 1;   
							break;
						}
						//move the charge forward
						CxPlus(one);   
						//current increases in x
						*totalX=*totalX+1;   
						break;

		//if the site on the left of the charge position is occupied,
		case 2: if( OccYnegPeriodic(snA, x,y,z)==1){ 
							//there is no possibility to hopp
							flag = 1;
							break;
						}
						//move the charge to the left
						CyMinus(one);
						//current decreases in y
						*totalY=*totalY-1;
						break;

		//if the site on the right of the charge position is occupied,
		case 3: if( OccYposPeriodic(snA, x,y,z)==1){   
							//there is no possibility to hopp
							flag = 1;   
							break;
						}
						//move the charge to the right
						CyPlus(one);
						//current increases in y
						*totalY=*totalY+1;
						break;

		//if the charge is at the lower interface or the site in the decided direction 
		//(below the charge position) is occupied,
		case 4: if( OccZneg(snA, x,y,z)==1){  
							//then there is no possibility to hop
							flag = 1;   
							break;
						}
						//move the charge down
						CzMinus(one);
						//current decreases in z
						*totalZ=*totalZ-1;
						break;
		
		//if the charge is at the upper interface or the site in the decided direction 
		//(above the charge position) is occupied,
		case 5: if( OccZpos(snA, x,y,z)==1){
							//there is no possibility to hopp
							flag = 1;
							break;
						}
						//move the charge up
						CzPlus(one);
						//current increases in z
						*totalZ=*totalZ+1;
						break;
		}
	}
	return flag;

}
Пример #5
0
/* Assumes C is a linear cone (i.e. with apex zero).
 * All equalities are removed first to speed up the computation
 * in zsolve.
 */
Matrix *Cone_Hilbert_Basis(Polyhedron *C, unsigned MaxRays)
{
    unsigned dim;
    int i;
    Matrix *M2, *M3, *T;
    Matrix *CV = NULL;
    LinearSystem initialsystem;
    ZSolveMatrix matrix;
    ZSolveVector rhs;
    ZSolveContext ctx;

    remove_all_equalities(&C, NULL, NULL, &CV, 0, MaxRays);
    dim = C->Dimension;

    for (i = 0; i < C->NbConstraints; ++i)
	assert(value_zero_p(C->Constraint[i][1+dim]) ||
	       First_Non_Zero(C->Constraint[i]+1, dim) == -1);

    M2 = Polyhedron2standard_form(C, &T);
    matrix = Matrix2zsolve(M2);
    Matrix_Free(M2);

    rhs = createVector(matrix->Height);
    for (i = 0; i < matrix->Height; i++)
	rhs[i] = 0;

    initialsystem = createLinearSystem();
    setLinearSystemMatrix(initialsystem, matrix);
    deleteMatrix(matrix);

    setLinearSystemRHS(initialsystem, rhs);
    deleteVector(rhs);

    setLinearSystemLimit(initialsystem, -1, 0, MAXINT, 0);
    setLinearSystemEquationType(initialsystem, -1, EQUATION_EQUAL, 0);

    ctx = createZSolveContextFromSystem(initialsystem, NULL, 0, 0, NULL, NULL);
    zsolveSystem(ctx, 0);

    M2 = VectorArray2Matrix(ctx->Homs, C->Dimension);
    deleteZSolveContext(ctx, 1);
    Matrix_Transposition(T);
    M3 = Matrix_Alloc(M2->NbRows, M2->NbColumns);
    Matrix_Product(M2, T, M3);
    Matrix_Free(M2);
    Matrix_Free(T);

    if (CV) {
	Matrix *T, *M;
	T = Transpose(CV);
	M = Matrix_Alloc(M3->NbRows, T->NbColumns);
	Matrix_Product(M3, T, M);
	Matrix_Free(M3);
	Matrix_Free(CV);
	Matrix_Free(T);
	Polyhedron_Free(C);
	M3 = M;
    }

    return M3;
}
Пример #6
0
void gcm::gcmSubspace(void)
{
	int n = nFrames;
	//white
	for (int d=0; d<nDimension; d++)
	{
		double dimAve = 0.0;
		for (int f=0; f<nFrames; f++)
		{
			dimAve += feature_ori[f][d];
		}
		dimAve /= nFrames;
		for (int f=0; f<nFrames; f++)
		{
			feature_ori[f][d] -= dimAve;
		}
	}

	//Obtain the Covariance
	double** C;
	C = new double*[nDimension];
	for (int i=0; i<nDimension; i++)
	{
		C[i] = new double[nDimension];
	}


	for (int d=0; d<nDimension; d++)
	{
		for (int d2=0; d2<nDimension; d2++)
		{
			C[d][d2] = 0.0;
			for (int f=0; f<nFrames; f++)
			{
				C[d][d2] += feature_ori[f][d]*feature_ori[f][d2];
			}
		}
	}

	for (int d=0; d<nDimension; d++)
	{
		for (int d2=0; d2<nDimension; d2++)
		{
			C[d][d2] /= nFrames;
			if (d == d2)
			{
				C[d][d2] += 0.001;
			}
		}
	}


	//SVD to obtain the subspace
	double* w;
	w = new double[nDimension];
	double **v;
	v = new double*[nDimension];
	for (int i=0; i<nDimension; i++)
	{
		v[i] = new double[nDimension];
	}

	gcmSVD.svdcmp(C, nDimension, nDimension, w, v);

	//The C[all][reDim =10] is the subspace
	for (int i=0; i<nDimension; i++)
	{
		for (int j=0; j<subspaceDim; j++)
		{
			gcm_subspace[i][j] = C[i][j];
		}
	}

	//Release
	deleteMatrix(C,nDimension);
	delete w;
	deleteMatrix(v, nDimension);
}
Пример #7
0
int menuResolution()
{
	Matrix m,result;
	int action,i,j;
	int dim=0;
	action=-1;
	while(action!=0)
	{
		for(i=0;i<40;i++)
			printf("-");
		printf("\n\nRESOLUTION : \n");
		for(i=0;i<2;i++)
		{
			printf("\t%d./ ",i);
			switch(i)
			{
				case 0:
					printf("Retourner au menu ;\n");
					break;
				case 1:
					printf("Resolution par le pivot de gauss ;\n");
					break;
				default:
					break;
			}
		}
		printf("\n\n");
		for(i=0;i<40;i++)
			printf("-");
		printf("\n\n");

		printf("Que voulez-vous faire?\n");
		scanf("%d",&action);
		printf("\n\n");

		if(action==1)
		{
			printf("Donnez la dimension de la matrice.\n");
			scanf("%d",&dim);
			printf("\n");

			printf("Souhaitez-vous remplir la matrice ou la créer	aléatoirement?\n");
			printf("\t1./ Je remplis la matrice moi-même\n");
			printf("\t2./ Je fais confiance au hasard\n");
			scanf("%d",&action);
			printf("\n\n");

			if((dim>=0)&&(action>0)&&(action<3))
			{
				result=newMatrix(dim,1);
				m=newMatrix(dim,dim);

				if(action==1)
				{
					for(i=0;i<dim;i++)
					{
						for(j=0;j<dim;j++)
						{
							printf("Donnez le %dème coefficient pour l'équation %d:	",j,i);
							scanf("%f",&m->mat[i*dim+j]);
						}
						printf("Donnez le résultat pour l'équation %d: ",i);
						scanf("%f",&result->mat[i]);
					}
				}
				if(action==2)	
				{
					fillMatrix(m);
					fillMatrix(result);
				}

				printf("\nVoici les matrices:\n");
				afficheMatrice(m);
				afficheMatrice(result);
				printf("\n");

				result=resol(m,result);
				printf("On obtient: \n");
				for(i=0;i<dim;i++)
					printf("x%d = %f; \n",i,result->mat[i]);
				printf("\n\n\n");

				deleteMatrix(m);
				deleteMatrix(result);
			}
		}
		else
		{
			break;
		}
	}
	return action;
}
int main(void){

	//mem_init();
	//Parameter List
	//
	ParameterFrame PF = newParamFrame();
	int SLength = 20;
	PFset_Len(PF,SLength);
	int SWidth = 20;
	PFset_Wid(PF,SWidth);
	int SHeight = 20;
	PFset_Hei(PF,SHeight);
	
	double RelativePerm = 3.9;
	PFset_RelativePerm(PF,RelativePerm);
	double electricEnergyX = 0;
	double electricEnergyY = 0;
	double electricEnergyZ = 0;
	double KT = 1;
	double reOrgEnergy = 1;
	PFset_reOrg(PF,reOrgEnergy);
	double SiteDistance = 1E-9;
	PFset_SiteDist(PF,SiteDistance);
	int CutOff = 5;
	PFset_CutOff(PF,CutOff);
	double lambda = 1E-9;
	PFset_lambda(PF,lambda);
	int SeedProt = 1;
	PFset_SeedProt(PF,SeedProt);
	int PeriodicX = 0;
	PFset_Px(PF,PeriodicX);
	int PeriodicY = 0;
	PFset_Py(PF,PeriodicY);
	int PeriodicZ = 0;
	PFset_Pz(PF,PeriodicZ);
	
	int XElecOn = 1;
	PFset_XElecOn(PF,XElecOn);
	int YElecOn = 0;
	PFset_YElecOn(PF,YElecOn);
	int ZElecOn = 0;
	PFset_ZElecOn(PF,ZElecOn);
	
	int EndX = 1;
	PFset_EndX(PF,EndX);
	int EndY = 1;
	PFset_EndY(PF,EndY);
	int EndZ = 1;
	PFset_EndZ(PF,EndZ);
	
	double E0 = -5.2;
	PFset_E0(PF,E0);
	double Etrap = -4.9;
	PFset_Etrap(PF,Etrap);
	//double q = 1.602E-19;
	double fracSeed = 0.01;
	PFset_FracSeed(PF,fracSeed);
	double fraction = 0.005;
	PFset_FracTrap(PF,fraction);
	double Tsigma = 0.07;
	PFset_Tsigma(PF,Tsigma);
	double sigma = 0.07;
	PFset_sigma(PF,sigma);
	double gamma = 2;
	PFset_gamma(PF,gamma);
	double AttemptToHop = 10E13;
	PFset_AttemptToHop(PF,AttemptToHop);
	
	double vX = 10E13;
	PFset_vX(PF,vX);
	double vY = 10E13;
	PFset_vY(PF,vY);
	double vZ = 10E13;
	PFset_vZ(PF,vZ);
	double MarcusCoeff = 10E13;
	
	double FermiExb = -2;
	PFset_XFermiB(PF,FermiExb);
	double FermiEyl = -2;
	PFset_YFermiL(PF,FermiEyl);
	double FermiEzb = -2;
	PFset_ZFermiB(PF,FermiEzb);
	double FermiExf = -2;
	PFset_XFermiF(PF,FermiExf);
	double FermiEyr = -2;
	PFset_YFermiR(PF,FermiEyr);
	double FermiEza = -2;
	PFset_ZFermiA(PF,FermiEza);

	double alphaxb = 2;
	PFset_alphaxb(PF,alphaxb);
	double alphayl = 2;
	PFset_alphayl(PF,alphayl);
	double alphazb = 2;
	PFset_alphazb(PF,alphazb);
	double alphaxf = 2;
	PFset_alphaxf(PF,alphaxf);
	double alphayr = 2;
	PFset_alphayr(PF,alphayr);
	double alphaza = 2;
	PFset_alphaza(PF,alphaza);

	Electrode elXb = NULL;
	Electrode elXf = NULL;
	Electrode elYl = NULL;
	Electrode elYr = NULL;
	Electrode elZb = NULL;
	Electrode elZa = NULL;

	const double D = 20E14; 
	PFset_D(PF,D);

	SNarray snA = newSNarray(SLength,SWidth,SHeight);

/*	initJumPossibility(electricEnergy, KT, reOrgEnergy, snA,\
				PeriodicX, PeriodicY, PeriodicZ,\
				XElecOn, YElecOn, ZElecOn);
*/

	//Non - periodic 
	int rv = initSite(electricEnergyX,electricEnergyY,\
			  electricEnergyZ, KT, snA, PF);
	

	printSNarray_Detailed( snA);
	
	char File1[] = "Test1\0";

	printVisitFreq(snA, &File1[0]);

	int Ntot = 100;
	PFset_Ntot(PF,Ntot);	
	int NCh = 20;
	PFset_NCh(PF,NCh);
	int i;
	//Create an array the size of all the charges
	//label the charges starting from 0 to Ntot-1
	matrix sequence = newMatrix(Ntot,1);
	for(i = 0; i<Ntot; i++){
		setE(sequence,i+1,1,i);
	}
	ChargeArray chA = initCharget0( sequence, snA, Ntot, NCh,\
																	D, XElecOn, YElecOn, ZElecOn,\
																	EndX, EndY, EndZ);
	printChargeA(chA);

	rv = initCharge( 20, 2, &chA, sequence, snA,\
					Ntot, NCh, D, XElecOn, YElecOn, ZElecOn,\
					EndX, EndY, EndZ);

	printChargeA(chA);


	printf("Testing initElec\n");

	rv = initElec(electricEnergyX, electricEnergyY, electricEnergyZ,\
		      MarcusCoeff, KT, snA,\
		      &elXb, &elXf, &elYl, &elYr,&elZb,&elZa,\
		      PF);
	
	
	deleteSNarray(snA);
	deleteChargeA(chA);
	deleteMatrix(sequence);
	
	SNarray snAmini;
	matrix mtxmini;

	if (elXb!=NULL){
		snAmini = (SNarray) getElectrode_AdjacentSites(elXb);
		deleteSNarray(snAmini);
		mtxmini = (matrix) getElectrode_HopRates(elXb);
		deleteMatrix(mtxmini);
		deleteElectrode(&elXb);	
	
	}
	if (elXf!=NULL){
		snAmini = (SNarray) getElectrode_AdjacentSites(elXf);
		deleteSNarray(snAmini);
		mtxmini = (matrix) getElectrode_HopRates(elXf);
		deleteMatrix(mtxmini);
		deleteElectrode(&elXf);	
	}

	if (elYl!=NULL){
		snAmini = (SNarray) getElectrode_AdjacentSites(elYl);
		deleteSNarray(snAmini);
		mtxmini = (matrix) getElectrode_HopRates(elYl);
		deleteMatrix(mtxmini);
		deleteElectrode(&elYl);	
	}
	if (elYr!=NULL){
		snAmini = (SNarray) getElectrode_AdjacentSites(elYr);
		deleteSNarray(snAmini);
		mtxmini = (matrix) getElectrode_HopRates(elYr);
		deleteMatrix(mtxmini);
		deleteElectrode(&elYr);	
	}
	if (elZb!=NULL){
		snAmini = (SNarray) getElectrode_AdjacentSites(elZb);
		deleteSNarray(snAmini);
		mtxmini = (matrix) getElectrode_HopRates(elZb);
		deleteMatrix(mtxmini);
		deleteElectrode(&elZb);	
	}

	if (elZa!=NULL){
		snAmini = (SNarray) getElectrode_AdjacentSites(elZa);
		deleteSNarray(snAmini);
		mtxmini = (matrix) getElectrode_HopRates(elZa);
		deleteMatrix(mtxmini);
		deleteElectrode(&elZa);	
	}
	//atexit(mem_term);
	
	
	/*
	//Fully Periodic
	SNarray snA2 = newSNarray(SLength,SWidth,SHeight);
	
	rv = initSite(electricEnergy, KT, reOrgEnergy,\
							lambda, CutOff,\
							fracSeed, fraction, SiteDistance,\
							Etrap, Tsigma, E0, sigma,\
							SeedProt, 1, 1, 1,\
							XElecOn, YElecOn, ZElecOn, snA2);
	
	char File2[] = "Test2\0";

	printVisitFreq(snA2, &File2[0]);

	//Periodic Only in the x
	SNarray snA3 = newSNarray(SLength, SWidth, SHeight);

	rv = initSite(electricEnergy, KT, reOrgEnergy,\
							lambda, CutOff,\
							fracSeed, fraction, SiteDistance,\
							Etrap, Tsigma, E0, sigma,\
							SeedProt, 1, 0, 0,\
							XElecOn, YElecOn, ZElecOn, snA3);
	
	
	char File3[] = "Test3\0";

	printVisitFreq(snA3, &File3[0]);
*/
	
	deleteParamFrame(&PF);

	return 0;
}
Пример #9
0
int menuOperation()
{
	Matrix m,m1,result;
	int action,act,i,j,row,column,row1,column1;
	int dim=0;
	action=-1;
	while(act!=0)
	{
		for(i=0;i<40;i++)
			printf("-");
		printf("\n\nOPERATIONS: \n");
		for(i=0;i<4;i++)
		{
			printf("\t%d./ ",i);
			switch(i)
			{
				case 0:
					printf("Retourner au menu ;\n");
					break;
				case 1:
					printf("Echelonner une matrice par le pivot de gauss ;\n");
					break;
				case 2:
					printf("Additionner deux matrices ;\n");
					break;
				case 3:
					printf("Multiplication de deux matrices.\n");
					break;
				default:
					break;
			}
		}
		printf("\n\n");
		for(i=0;i<40;i++)
			printf("-");
		printf("\n\n");

		printf("Que voulez-vous faire?\n");
		scanf("%d",&act);
		printf("\n\n");

		switch(act)
		{
			case 1:
				printf("Donnez la dimension de la matrice.\n");
				scanf("%d",&dim);
				printf("\n");

				printf("Souhaitez-vous remplir la matrice ou la créer	aléatoirement?\n");
				printf("\t1./ Je remplis la matrice moi-même\n");
				printf("\t2./ Je fais confiance au hasard\n");
				scanf("%d",&action);
				printf("\n\n");

				if((dim>0)&&(action>0)&&(action<3))
				{
					m=newMatrix(dim,dim);

					if(action==1)
					{
						for(i=0;i<dim;i++)
						{
							for(j=0;j<dim;j++)
							{
								printf("Donnez le %dème coefficient pour la ligne %d:	",j,i);
								scanf("%f",&m->mat[i*dim+j]);
							}
						}
					}
					if(action==2)	
					{
						fillMatrix(m);
					}

					printf("\nVoici la matrice: \n");
					afficheMatrice(m);
					printf("\n");

					result=gauss(m);

					printf("On obtient: \n");
					afficheMatrice(result);

					deleteMatrix(result);
				}	
				break;
			case 2: 
				printf("Donnez les dimensions de la matrice.\n");
				printf("\tNombre de lignes: ");
				scanf("%d",&row);
				printf("\tNombre de colonnes: ");
				scanf("%d",&column);
				printf("\n");

				printf("Souhaitez-vous remplir les matrices ou les créer aléatoirement?\n");
				printf("\t1./ Je remplis les matrices moi-même\n");
				printf("\t2./ Je fais confiance au hasard\n");
				scanf("%d",&action);
				printf("\n\n");

				if((row>0)&&(column>0))
				{
					m=newMatrix(row,column);
					m1=newMatrix(row,column);

					if(action==1)
					{
						printf("Matrice 1: \n");
						for(i=0;i<row;i++)
						{
							for(j=0;j<column;j++)
							{
								printf("%dème ligne, %d colonne:	",i,j);
								scanf("%f",&m->mat[i*column+j]);
							}
						}
						printf("\n\nMatrice 2: \n");
						for(i=0;i<row;i++)
						{
							for(j=0;j<column;j++)
							{
								printf("%dème ligne, %d colonne:	",i,j);
								scanf("%f",&m1->mat[i*column+j]);
							}
						}
					}
					if(action==2)	
					{
						fillMatrix(m);
						fillMatrix(m1);
					}

					printf("\nVoici les matrices: \n");
					afficheMatrice(m);
					afficheMatrice(m1);
					printf("\n");

					result=addition(m,m1);

					printf("On obtient: \n");
					afficheMatrice(result);

					deleteMatrix(result);
					deleteMatrix(m);
					deleteMatrix(m1);
				}			
				break;
			case 3:
				printf("Donnez les dimensions des matrices.\n");
				printf("Matrice 1:\n");
				printf("\tNombre de lignes: ");
				scanf("%d",&row);
				printf("\tNombre de colonnes: ");
				scanf("%d",&column);
				printf("Matrice 2:\n");
				printf("\tNombre de lignes: ");
				scanf("%d",&row1);
				printf("\tNombre de colonnes: ");
				scanf("%d",&column1);
				printf("\n");

				if((column==row1)&&(row>0)&&(column>0)&&(column1>0))
				{
					printf("Souhaitez-vous remplir les matrices ou les créer aléatoirement?\n");
					printf("\t1./ Je remplis les matrices moi-même\n");
					printf("\t2./ Je fais confiance au hasard\n");
					scanf("%d",&action);
					printf("\n\n");

					m=newMatrix(row,column);
					m1=newMatrix(row1,column1);

					if(action==1)
					{
						printf("Matrice 1: \n");
						for(i=0;i<row;i++)
						{
							for(j=0;j<column;j++)
							{
								printf("%dème ligne, %dème colonne:	",i,j);
								scanf("%f",&m->mat[i*column+j]);
							}
						}
						printf("Matrice 2: \n");
						for(i=0;i<row1;i++)
						{
							for(j=0;j<column1;j++)
							{
								printf("%dème ligne, %dème colonne:	",i,j);
								scanf("%f",&m1->mat[i*column1+j]);
							}
						}
					}
					if(action==2)	
					{
						fillMatrix(m);
						fillMatrix(m1);
					}

					printf("\nVoici les matrices: \n");
					afficheMatrice(m);
					afficheMatrice(m1);
					printf("\n");

					result=multiplication(m,m1);

					printf("On obtient: \n");
					afficheMatrice(result);

					deleteMatrix(result);
					deleteMatrix(m);
					deleteMatrix(m1);
				}
				break;
			default:
				break;
		}
	}
	return action;
}
Пример #10
0
int menuDecomposition()
{
	Matrix m,p,l,u;
	int action,i,j;
	int dim=0;
	action=-1;
	while(action!=0)
	{
		for(i=0;i<40;i++)
			printf("-");
		printf("\n\nDECOMPOSITION : \n");
		for(i=0;i<2;i++)
		{
			printf("\t%d./ ",i);
			switch(i)
			{
				case 0:
					printf("Retourner au menu ;\n");
					break;
				case 1:
					printf("Décompostion PLU.\n");
					break;
				default:
					break;
			}
		}
		printf("\n\n");
		for(i=0;i<40;i++)
			printf("-");
		printf("\n\n");

		printf("Que voulez-vous faire?\n");
		scanf("%d",&action);
		printf("\n\n");

		if(action==1)
		{
			printf("Donnez la dimension de la matrice.\n");
			scanf("%d",&dim);
			printf("\n");

			printf("Souhaitez-vous remplir la matrice ou la créer	aléatoirement?\n");
			printf("\t1./ Je remplis la matrice moi-même\n");
			printf("\t2./ Je fais confiance au hasard\n");
			scanf("%d",&action);
			printf("\n\n");

			if((dim>0))
			{
				p=identite(dim,dim);
				l=identite(dim,dim);
				u=newMatrix(dim,dim);
				m=newMatrix(dim,dim);

				if(action==1)
				{
					for(i=0;i<dim;i++)
					{
						for(j=0;j<dim;j++)
						{
							printf("Donnez le %dème coefficient pour l'équation %d:	",j,i);
							scanf("%f",&m->mat[i*dim+j]);
						}
					}
				}
				if(action==2)	
				{
					fillMatrix(m);
				}

				printf("\nVoici les matrices:\n");
				afficheMatrice(m);
				printf("\n");

				plu(m,p,l,u);

				printf("On obtient: \n");
				afficheMatrice(p);
				afficheMatrice(l);
				afficheMatrice(u);
				printf("\n\n\n");

				deleteMatrix(m);
				deleteMatrix(p);
				deleteMatrix(l);
				deleteMatrix(u);
			}
		}
		else
		{
			break;
		}
	}
	return action;
}
Пример #11
0
int menuInversion()
{
	Matrix m,result;
	int action,act,i,j;
	int dim=0;
	action=-1;
	while(action!=0)
	{
		for(i=0;i<40;i++)
			printf("-");
		printf("\n\nINVERSION : \n");
		for(i=0;i<3;i++)
		{
			printf("\t%d./ ",i);
			switch(i)
			{
				case 0:
					printf("Retourner au menu ;\n");
					break;
				case 1:
					printf("Inversion par la comatrice ;\n");
					break;
				case 2:
					printf("Inversion par le pivot de gauss.\n");
					break;
				default:
					break;
			}
		}
		printf("\n\n");
		for(i=0;i<40;i++)
			printf("-");
		printf("\n\n");

		printf("Que voulez-vous faire?\n");
		scanf("%d",&act);
		printf("\n\n");

		if(act!=0)
		{
			printf("Donnez la dimension de la matrice.\n");
			scanf("%d",&dim);
			printf("\n");

			printf("Souhaitez-vous remplir la matrice ou la créer	aléatoirement?\n");
			printf("\t1./ Je remplis la matrice moi-même\n");
			printf("\t2./ Je fais confiance au hasard\n");
			scanf("%d",&action);
			printf("\n\n");

			if((dim>0)&&(action>0)&&(action<3))
			{
				m=newMatrix(dim,dim);

				if(action==1)
				{
					for(i=0;i<dim;i++)
					{
						for(j=0;j<dim;j++)
						{
							printf("Donnez le %dème coefficient pour la ligne %d:	",j,i);
							scanf("%f",&m->mat[i*dim+j]);
						}
					}
				}
				if(action==2)	
				{
					fillMatrix(m);
				}

				printf("\nVoici la matrice: \n");
				afficheMatrice(m);
				printf("\n");

				if(act==1) 
				{
					printf("attention cette inversion n'est pas toujours foncionnelle\n");
					result=inverseComat(m);
				}
				else result=inverseGauss(m);

				printf("On obtient: \n");
				afficheMatrice(result);

				deleteMatrix(m);
				deleteMatrix(result);
			}
		}
		else
		{
			break;
		}
	}
	return action;
}
Пример #12
0
void Objdrawaxis (char     dir    ,
                  char     tics   ,
                  double* x      ,
                  int    * nx     ,
                  double* y      ,
                  int    * ny     ,
                  char   * val[]  ,
                  int      subint ,
                  char   * format ,
                  int      font   ,
                  int      textcol,
                  int      ticscol,
                  char     flag   ,
                  int      seg    ,
                  int      nb_tics_labels)
{
    int iObjUID = 0;
    int iSubwinUID = 0;
    int ticksDirection = 0;
    int ticksStyle = 0;

    iSubwinUID = getCurrentSubWin();

    checkRedrawing();

    switch (dir)
    {
        default :
        case 'u' :
            ticksDirection = 0;
            break;
        case 'd' :
            ticksDirection = 1;
            break;
        case 'l' :
            ticksDirection = 2;
            break;
        case 'r' :
            ticksDirection = 3;
            break;
    }

    switch (tics)
    {
        default:
        case 'v':
            ticksStyle = 0;
            break;
        case 'r':
            ticksStyle = 1;
            break;
        case 'i':
            ticksStyle = 2;
            break;
    }

    iObjUID = createAxis(iSubwinUID, ticksDirection, ticksStyle, x, *nx, y, *ny, subint, format, font, textcol, ticscol, seg);

    if (iObjUID == NULL)
    {
        Scierror(999, _("%s: No more memory.\n"), "Objdrawaxis");
        return;
    }

    if (val == NULL)
    {
        char **matData;
        StringMatrix *tics_labels;

        tics_labels = computeDefaultTicsLabels(iObjUID);

        if (tics_labels == NULL)
        {
            deleteGraphicObject(iObjUID);
            return;
        }

        matData = getStrMatData(tics_labels);

        /*
        * The labels vector size must be computed using the matrix's dimensions.
        * To be modified when the labels computation is moved to the Model.
        */
        setGraphicObjectProperty(iObjUID, __GO_TICKS_LABELS__, matData, jni_string_vector, tics_labels->nbCol * tics_labels->nbRow);

        deleteMatrix(tics_labels);
    }
    else
    {
        int i = 0;
        /*
        * Labels are set using the str argument; the previous code tested whether each element of the
        * str array was null and set the corresponding Axis' element to NULL, though there was no
        * apparent reason to do so. This is still checked, but now aborts building the Axis.
        */

        if (nb_tics_labels == -1)
        {
            Scierror(999, _("Impossible case when building axis\n"));
            deleteGraphicObject(iObjUID);
            return;
        }

        for (i = 0; i < nb_tics_labels; i++)
        {
            if (val[i] == NULL)
            {
                deleteGraphicObject(iObjUID);
                return;
            }
        }

        setGraphicObjectProperty(iObjUID, __GO_TICKS_LABELS__, val, jni_string_vector, nb_tics_labels);
    }

    setCurrentObject(iObjUID);
}
Пример #13
0
int resizeRow(matrix * mtx, int Row){

	if(!(*mtx)) return -1;
	if(Row<=0 ) return -1;
	//Find if we are adding or removing from the matrix
	//printf("ResizeRow\n");	
	//If flag equals 1 means decreasing the size of the
	//matrix if it is 0 it means we are increasing the size
	int i;
	int j;
	int cols = (*mtx)->cols;
	int flag = 0;
	int currentRow = 0;
	int rowResize = Row;
	matrix * mtxtemp;
	matrix * mtxprev;
	mtxtemp = mtx;

	if(Row>((*mtx)->rows+currentRow)){
		while((*mtxtemp)->Extra!=NULL && flag==0){
			currentRow+=(*mtxtemp)->rows;
			rowResize=Row-currentRow;
			(*mtxprev) = (*mtxtemp);
			(*mtxtemp)=(*mtxtemp)->Extra;
			if(Row<=((*mtxtemp)->rows+currentRow)){
				flag=1;
			}
		}
	}else{
		flag=1;
	}

	if(flag==0){
		//Increasing
		//If we are increasing mtxtemp->Extra should be NULL
		if((*mtxtemp)->Extra!=NULL){
			printf("ERROR should not be increasing size of matrix\n");
			return -1;
		}

		//Determine if it is the first matrix in the list
		if((*mtx)->Extra==NULL){
			//First matrix in the list
			matrix temp = duplicateMatrix((*mtx));
			matrix mtxnew = newMatrix(rowResize,12);
			
			for(i=1;i<=rowResize;i++){
				for(j=1;j<=cols;j++){
					if(i<=temp->rows){
						setE(mtxnew,i,j,getE(temp,i,j));
					}else{
						setE(mtxnew,i,j,0);
					}
				}
			}

			deleteMatrix(mtx);
			deleteMatrix(&temp);
			(*mtx) = mtxnew;

		}else{
			//Not the first matrix in the list
			matrix temp = duplicateMatrix((*mtxtemp));
			matrix mtxnew = newMatrix(rowResize,12);

			for(i=1;i<=rowResize;i++){
				for(j=1;j<=cols;j++){
					if(i<=temp->rows){
						setE(mtxnew,i,j,getE(temp,i,j));
					}else{
						setE(mtxnew,i,j,0);
					}
				}
			}

			deleteMatrix(mtxtemp);
			deleteMatrix(&temp);
			(*mtxprev)->Extra = mtxnew;

		}

	}else{
		//Decreasing
		//mtxtemp is the matrix that is being reduced in size
		//All matrices linked after mtxtemp are to be deleted
		if((*mtxtemp)->Extra!=NULL){
			matrix mtxRemove = (*mtxtemp)->Extra;
			deleteMatrix(&mtxRemove);
			(*mtxtemp)->Extra=NULL;
		}

		//Now we just need to resize mtxtemp
		matrix temp = duplicateMatrix((*mtxtemp)); 
		matrix mtxnew = (matrix) realloc((*mtxtemp), sizeof(struct _matrix)+sizeof(double)*rowResize*cols);
		if(!mtxnew) {
			printf("ERROR unable to realloc matrix returned NULL\n");
			return -1;
		}
		mtxnew->rows=rowResize;
		mtxnew->cols=cols;
		mtxnew->Extra=NULL;

		for (i=1;i<=rowResize;i++){
			for (j=1;j<=cols;j++){
				if(i<=temp->rows){
					setE(mtxnew,i,j,getE(temp,i,j));
				}else{
					printf("ERROR should not have a value in the new matrix that is greater than the old one\n");
					return -1;
				}
			}
		}

		deleteMatrix(&temp);
		(*mtxtemp) = mtxnew;


	}

	return 0;
}
Пример #14
0
int main(int argc, char* argv[])
{
	// check the number of arguments
	if (argc != 5) {
		printf("Program needs 4 integer arguments divided by space: M1.rows M1.columns M2.rows M2.columns\n");
		return 1;
	}
	// check if OpenMP is available
	if (!omp_support()) {
		printf("Unfortunately, OpenMP is not available.\n");
		return 1;
	}

	//Define matrices
	int rows1 = atoi(argv[1]);
	int cols1 = atoi(argv[2]);
	int rows2 = atoi(argv[3]);
	int cols2 = atoi(argv[4]);
	int **matrix1, **matrix2;

	if (cols1 != rows2) {
		printf("Program needs 4 integer arguments divided by space: M1.rows M1.columns M2.rows M2.columns\nUnfortunately, you've entered wrong matrix size:\n\tM1.columns must be equal to M2.rows!\n");
		return 1;
	}

	int rows3 = rows1;
	int cols3 = cols2;
	int** matrix3;

	srand(time(NULL));

	//omp_set_nested(1);

#pragma omp parallel
	{
#pragma omp sections
	{
#pragma omp section
	{
		//create the first matrix
		matrix1 = createMatrix(rows1, cols1);
	}
#pragma omp section
	{
		//create the second matrix
		matrix2 = createMatrix(rows2, cols2);
	}
#pragma omp section
	{
		//create the third/multiplication matrix
		matrix3 = createMatrix(rows3, cols3);
	}
	}

#pragma omp sections
	{
#pragma omp section
	{
		//fill the first matrix
		randFillMatrix(matrix1, rows1, cols1);
	}
#pragma omp section
	{
		//fill the second matrix
		randFillMatrix(matrix2, rows2, cols2);
	}
#pragma omp section
	{
		//fill the second matrix
		zeroInitMatrix(matrix3, rows3, cols3);
	}
	}
	}

/*
RCI
*/
//#pragma omp parallel for
//	for (int r = 0; r < rows1; r++) {
//		for (int c = 0; c < cols2; c++) {
//			for (int i = 0; i < cols1; i++) {
//				matrix3[r][c] = matrix3[r][c] + matrix1[r][i] * matrix2[i][c];
//			}
//		}
//	}


/*
CRI
*/
//#pragma omp parallel for
//	for (int c = 0; c < cols2; c++) {
//		for (int r = 0; r < rows1; r++) {
//		// for (int c = 0; c < cols2; c++) {
//			for (int i = 0; i < cols1; i++) {
//				matrix3[r][c] = matrix3[r][c] + matrix1[r][i] * matrix2[i][c];
//			}
//		}
//	}
//
//	auto start_time = omp_get_wtime();
///*
//CIR
//*/
//#pragma omp parallel for
//	for (int c = 0; c < cols2; c++) {
//		for (int i = 0; i < cols1; i++) {
//			for (int r = 0; r < rows1; r++) {
//				matrix3[r][c] = matrix3[r][c] + matrix1[r][i] * matrix2[i][c];
//			}
//		}
//	}
//
//	auto run_time = omp_get_wtime() - start_time;
//	printf("parallel - cir,%s,%s,%s,%s,%f\n", argv[1], argv[2], argv[3], argv[4], run_time);
//

/*
IRC
*/
	auto start_time = omp_get_wtime();
#pragma omp parallel for
	for (int i = 0; i < cols1; i++) {
		for (int r = 0; r < rows1; r++) {
			for (int c = 0; c < cols2; c++) {
				matrix3[r][c] = matrix3[r][c] + matrix1[r][i] * matrix2[i][c];
			}
		}
	}


	auto run_time = omp_get_wtime() - start_time;
	printf("parallel - irc,%s,%s,%s,%s,%f\n", argv[1], argv[2], argv[3], argv[4], run_time);

	//#pragma omp barrier
#pragma omp parallel
	{

#pragma omp sections
	{
#pragma omp section
	{
		//delete the first matrix
		deleteMatrix(matrix1, rows1);
	}
#pragma omp section
	{
		//delete the second matrix
		deleteMatrix(matrix2, rows2);
	}
#pragma omp section
	{
		//delete the third (multiplication) matrix
		deleteMatrix(matrix3, rows3);
	}
	}
	}

	return 0;
}
Пример #15
0
void SpeedTest(FunctionCall fc)
{
	int i, min, max, step, sec=0;
	int sizeTimeArray, fct;
	
	char fnc[MAXSIZE_FCT];
	char foutput[256];
	
	struct sigaction action;
	action.sa_handler = handler;
	sigemptyset(&action.sa_mask);
	
	struct timeval start, end, result;
	double maxtime = 0;
	double time;
	double usec;
	double* timeArray;
	
	Matrix a=NULL, b=NULL, tmp=NULL;
	E s;
	int n; 
	
	TokenizeSpeedTest(fc, fnc, &min, &max, &step, &sec);
	
	if (min>0 && max>0 && step>0)
	{
		sizeTimeArray = ((max-min)/step)+1;
		timeArray = (double*)malloc(sizeTimeArray*sizeof(double));
		for (i=0; i<sizeTimeArray; i++) timeArray[i] = 0;
	}
	
	usec = (double)sec * 1000000;
	
	sprintf(foutput, "speedtest_%s_%d_%d_%d_%d", fnc, min, max, step, sec);
	
	fct = GetFunction(fnc);
	
	switch (fct)
	{
		case NMX :
		{
			printf("\t You must specify another function\n");
			return;
		}
		
		case ADD :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				b = randomMatrix(i, i, MIN_E, MAX_E);
				
				gettimeofday(&start, NULL);
				tmp = addMatricis(a, b);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				deleteMatrix(b);
				deleteMatrix(tmp);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case SUB :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				b = randomMatrix(i, i, MIN_E, MAX_E);
				
				gettimeofday(&start, NULL);
				tmp = substractMatricis(a, b);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				deleteMatrix(b);
				deleteMatrix(tmp);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case MUL :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				b = randomMatrix(i, i, MIN_E, MAX_E);
				
				gettimeofday(&start, NULL);
				tmp = mulMatricis(a, b);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				deleteMatrix(b);
				deleteMatrix(tmp);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case MSC :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				s = mRand(MIN_SCA, MAX_SCA);
				
				gettimeofday(&start, NULL);
				tmp = mult_scal(a, s);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				deleteMatrix(tmp);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case EXP :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				n = (int)mRand(MIN_EXP, MAX_EXP);
				
				gettimeofday(&start, NULL);
				tmp = expo(a, n);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				deleteMatrix(tmp);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case TRA :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				
				gettimeofday(&start, NULL);
				tmp = transposeMatrix(a);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				deleteMatrix(tmp);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case DET :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				
				gettimeofday(&start, NULL);
				s = determinant(a);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case DLU :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				b = newMatrix(i, i);
				tmp = identityMatrix(i);
				
				gettimeofday(&start, NULL);
				decomposition(a, b, tmp);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				deleteMatrix(b);
				deleteMatrix(tmp);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case SOL :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				b = randomMatrix(i, 1, MIN_E, MAX_E);
				
				gettimeofday(&start, NULL);
				tmp = gauss(a, b);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				deleteMatrix(b);
				deleteMatrix(tmp);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case INV :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				
				gettimeofday(&start, NULL);
				tmp = invert(a);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				deleteMatrix(tmp);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case RNK :
		{
			sigaction(SIGINT, &action, NULL);
			
			for (i=min; i<=max; i+=step)
			{
				a = randomMatrix(i, i, MIN_E, MAX_E);
				
				gettimeofday(&start, NULL);
				n = rank(a);
				gettimeofday(&end, NULL);
				
				timersub(&end, &start, &result);
				time = (result.tv_sec*1000000)+result.tv_usec;
				if (maxtime < time) maxtime = time;
				
				timeArray[(i-min)/step] = time;
				printf("\t* %s Size:%5d ;\tTime:%8.0f µs ;\n", fnc, i, time);
				
				deleteMatrix(a);
				
				if (usec >= 1000000) {
					if (time >= usec) {
						i++;
						break;
					}
				}
				if (CTRLC) {
					i++;
					break;
				}
			}
			
			CreateGNUPLOTFile(min, i-step, step, timeArray, maxtime, foutput);
			break;
		}
		
		case VAR : // default
		case NOF : // default
		default :
		{
			printf("\t%s : Function Not Implemented\n", fnc);
			fni++;
			break;
		}
	}
	
	if (fct!=NOF && fct !=VAR) fni = 0;
	
	free(timeArray);
	CTRLC = 0;
	sigemptyset(&action.sa_mask);
}
int main(void){


	//mem_init();
	
	int rv;
	long int n;
	int nc;
	int nca;

	int Num_elXb;
	int Num_elXf;
	int Num_elYl;
	int Num_elYr;
	int Num_elZb;
	int Num_elZa;

	SiteNode sn;
	int future;

	int SLength;
	int SWidth;
	int SHeight;

	double electricEnergyX;
	double electricEnergyY;
	double electricEnergyZ;

	double ElectricFieldX;
	double ElectricFieldY;
	double ElectricFieldZ;

	int XElecOn;
	int YElecOn;
	int ZElecOn;

	Electrode elXb = NULL;
	Electrode elXf = NULL;
	Electrode elYl = NULL;
	Electrode elYr = NULL;
	Electrode elZb = NULL;
	Electrode elZa = NULL;

	int EndX;
	int EndY;
	int EndZ;

	int PeriodicX;
	int PeriodicY;
	int PeriodicZ;

	int OrderL;

	//Number of time increments charges are injected
	int Tcount;
	//Size of time increments
	double TStep;
	//How many steps pass before we record the data
	int Nstep_av;
	//How many charges are injected at a time
	int NCh;
	//The distance between sites
	double D;
	//rN some normalization value
	int rN;
	//Attempt to Hop
	double AttemptToHop = 1E13;
	//gamma tunneling constant
	double gamma = 2;
	//SiteDistance is the distance between sites [m]
	double SiteDistance = 1E-9;
	double SiteDistanceNM;
	SiteDistanceNM = SiteDistance*1E9;
	//Testing ChargeClosure

	//Relative Permittivity
	double RelativePerm = 3.9;

	//Hopping Rates from Electrodes
	double vX = 1E13;
	double vY = 1E13;
	double vZ = 1E13;

	//Fermi level of Electrode
	double FermiExb = 0;
	double FermiEyl = 0;
	double FermiEzb = 0;
	double FermiExf = 0;
	double FermiEyr = 0;
	double FermiEza = 0;
	double alphaxb = 2;
	double alphayl = 2;
	double alphazb = 2;
	double alphaxf = 2;
	double alphayr = 2;
	double alphaza = 2;

	//ReOrgEnergy [eV]
	double reOrgEnergy = 1;
	//Ntot is the total number of charges
	int Ntot = 20;
	//nc is the number of charges in the system
	int nc1 = Ntot;
	int nca1 = nc1;
	//Total Charges collected at an electrode
	int TotalCollected = 0;

	double MarcusCoeff;
	double MarcusJ0;
	//Boltzmann constant Units of [eV/K]
	static const double kB = 8.6173324E-5;
	//Planck constant Units of [eV s]
	static const double hbar = 6.58211928E-16;

	double KT;

	KT = 1;

	//Calculating Marcus J0 coefficient assuming the Attempt to hop Rate
	//is equivalent to the marcus coefficient at 300 K
	MarcusJ0 = pow( AttemptToHop*hbar*pow(4*reOrgEnergy*kB*300/M_PI,1/2),1/2);
	//Calculating full Marcus Coefficient;
	MarcusCoeff = pow(MarcusJ0,2)/hbar * pow(M_PI/(4*reOrgEnergy*KT),1/2)*exp(-2*gamma*SiteDistanceNM);

	long double t;
	int Total;
	SNarray snA;
	matrix Sequence;
	matrix FutureSite;
	ChargeArray chA;
	ParameterFrame PF;
	char FileName[50] = "DataT300Vx0.5Vy0Vz0R11.ckpt";

	printf("Testing: Load_CheckPt\n");
	rv = Load_CheckPt(&t, &snA, &chA, &Sequence, \
	&FutureSite, FileName, &PF,&n, &nc, &nca,\
							 &Num_elXb, &Num_elXf, &Num_elYl, &Num_elYr, &Num_elZb, &Num_elZa);

	assert(rv==0);
	//printSNarray_Detailed(snA);
	//printMatrix(Sequence);
	//printMatrix(FutureSite);
	//printChargeA(chA);

	deleteMatrix(&Sequence);
	deleteMatrix(&FutureSite);
	deleteChargeA(chA);
	deleteParamFrame(&PF);
	deleteSNarray(&snA);

	printf("Testing: CheckPt_exist\n");
	char FileName2[256];
	FileName2[0]='\0';
	rv = CheckPt_exist(FileName2,sizeof(FileName2));
	printf("This is the file the function found %s\n",FileName2);
	assert(rv==0);

	char FileName3[256];
	FileName3[0]='\0';
	rv = CheckPt_Latest_TOF(FileName3,sizeof(FileName3), 0.5,0,0,300);
	printf("Value of rv %d\n",rv);
	assert(rv>0);
	printf("Lastest version found %s\n",FileName3);
	
	rv = CheckPt_Latest_TOF(FileName3,sizeof(FileName3), 1, 0,0,300);
	assert(rv==0);
	printf(".ckpt file exist but it is not the one you want \n");
	
	/*printf("rv %d\n",rv);
	printf("FileName %s\n",FileName2);
	
	
	Load_CheckPt(&t, &Total, &snA, &chA, &Sequence, &FutureSite, FileName, &PF, &nc, &nca,\
							 &Num_elXb, &Num_elXf, &Num_elYl, &Num_elYr, &Num_elZb, &Num_elZa);
	printf("Sucess!\n");
	printChargeA(chA);

	deleteMatrix(Sequence);
	deleteMatrix(FutureSite);
	deleteChargeA(chA);
	deleteParamFrame(PF);
	deleteSNarray(&snA);
	*/
	//atexit(mem_term);

	return 0;

}
Пример #17
0
void Exponentiation(FunctionCall fc)
{
	int i, j, s, sign = 1, index, exist = 0;
	Matrix a, c;
	char name[MAXSIZE_NAME] = {0};

	index = IndexMatrix(fc->name);
	if (index==-1)
	{
		index = cur_mat;
		mats[index] = (StrMatObject*)malloc(sizeof(StrMatObject));
		
		if (mats[index] == NULL)
		{
			printf("NewMatrix(): Could not allocate the new matrix\n");
			return;
		}

		for (i = 0; i < MAXSIZE_NAME; i++)
		{
			mats[index]->name[i] = fc->name[i];
			if (fc->name[i]=='\0') break;
		}
	}
	else exist = 1;
	
	j = 0;
	// searching for matrix name
	for (i = 0; i < MAXSIZE_NAME; i++)
	{
		name[j] = fc->args[i];
		if (name[j] == ',') {
			name[j] = '\0';
			break;
		}
		j++;
	}
	
	a = GetMatrix(name);
	if (a==NULL)
	{
		printf("\tMatrix %s Not Found\n", name);
		if (!exist) free(mats[index]);
		return;
	}
	
	if (fc->args[i+1] == '-')
	{
		sign = -1;
		i++;
	}
	
	if (isalpha(fc->args[i+1]))
	{
		j = 0;
		// searching for scalar name
		for (i = i+1; i < MAXSIZE_NAME; i++)
		{
			name[j] = fc->args[i];
			if (name[j] == '\0') break;
			j++;
		}
		
		s = (int)GetVariable(name) * sign;
		if (s==NOVAR)
		{
			printf("\tVariable %s Not Found\n", name);
			if (!exist) free(mats[index]);
			return;
		}
	}
	else
	{
		s = atoi(&(fc->args[i+1])) * sign;
	}
	
	if (a->rows == a->cols)
	{
		c = expo(a, s);
	}
	else
	{
		printf("\tMatrix must be square matrix\n");
		if (!exist) free(mats[index]);
		return ;
	}
	
	if (exist) deleteMatrix(mats[index]->mat);
	mats[index]->mat = c;
	
	// test: display the result
	displayMatrix(mats[index]->mat);
	
	if (!exist) cur_mat++;
}
Пример #18
0
int jacobiMethod( float** a, float* approx, float* b, int size, int iter, float error ){
    float** Dinv; 
    float**R;
    float* matrixRes; 
    float* temp;
    float* approx0;
    int ctr = 0, octr;
    int lastIteration = 0; 
    bool approachAchieved = 0;

    Dinv = createMatrixFloat( size );
    R = createMatrixFloat( size );
    matrixRes = createVectorFloat( size );
    temp = createVectorFloat( size );
    approx0 = createVectorFloat( size );
    
    //We calculate the diagonal inverse matrix make all other entries
    //as zero except Diagonal entries whose resciprocal we store
    for(int row = 0; row < size; row++){
        for( int column = 0; column < size; column++ ){
            if( row == column )
                Dinv[row][column] = 1/a[row][column];
            else
                Dinv[row][column] = 0;
        }
    }

    for(int row = 0; row < size; row++){
        //calculating the R matrix L+U
        for( int column = 0; column < size; column++ ){
            if( row == column ){
                R[row][column] = 0;
            }
            else if( row != column ){
                R[row][column] = a[row][column];
            }
        }
    }

    while( ctr <= iter && approachAchieved == FALSE){
        //copy values of approx to approx0 
        for(int i = 0; i < size; i++)
            approx0[i] = approx[i];
        
        //multiply L+U and the approximation
        multiply( matrixRes, R, approx, size );
        
        for( int row = 0; row < size; row++ ){
            //the matrix( b-Rx )
            temp[row] = b[row] - matrixRes[row]; //the matrix( b-Rx ) i
        }
        
        //multiply D inverse and ( b-Rx )
        multiply( matrixRes, Dinv, temp, size );

        for( octr = 0; octr < size; octr++ ){
            //store matrixRes value int the nex approximation
            approx[octr] = matrixRes[octr];
        }
        
        if( ctr > 0 )
            approachAchieved = checkStoppingCriterion( approx, approx0, size, error );
        
        lastIteration = ctr;
        ctr++;
    }

    deleteMatrix(Dinv, size);
    deleteMatrix(R, size);
    deleteVector(matrixRes );
    deleteVector(temp );
    deleteVector(approx0 );

    return lastIteration;
}
Пример #19
0
void Decomposition(FunctionCall fc)
{
	int i, j, indexL, indexU, existL = 0, existU = 0;
	Matrix a, l, u;
	char nameA[MAXSIZE_NAME] = {0};
	char nameL[MAXSIZE_NAME] = {0};
	char nameU[MAXSIZE_NAME] = {0};

	for (i = 0; i < MAXSIZE_NAME; i++)
	{
		nameL[i] = fc->name[i];
		nameU[i] = fc->name[i];
		if (fc->name[i] == '\0')
		{
			if (i<MAXSIZE_NAME-2)
			{
				nameL[i] = '_';
				nameU[i] = '_';
				nameL[i+1] = 'L';
				nameU[i+1] = 'U';
				nameL[i+2] = '\0';
				nameU[i+2] = '\0';
			}
			break;
		}
	}
	
	indexL = IndexMatrix(nameL);
	if (indexL==-1)
	{
		indexL = cur_mat;
		mats[indexL] = (StrMatObject*)malloc(sizeof(StrMatObject));
		if (mats[indexL] == NULL)
		{
			printf("NewMatrix(): Could not allocate the new matrix\n");
			return;
		}
		
		for (i = 0; i < MAXSIZE_NAME; i++)
		{
			mats[indexL]->name[i] = nameL[i];
			if (nameL[i]=='\0') break;
		}
	}
	else existL = 1;
	
	indexU = IndexMatrix(nameU);
	if (indexU==-1)
	{
		indexU = cur_mat+1;
		mats[indexU] = (StrMatObject*)malloc(sizeof(StrMatObject));
		if (mats[indexU] == NULL)
		{
			printf("NewMatrix(): Could not allocate the new matrix\n");
			return;
		}
		
		for (i = 0; i < MAXSIZE_NAME; i++)
		{
			mats[indexU]->name[i] = nameU[i];
			if (nameU[i]=='\0') break;
		}
	}
	else existU = 1;	
	
	j = 0;
	// searching for matrix name
	for (i = 0; i < MAXSIZE_NAME; i++)
	{
		nameA[j] = fc->args[i];
		if (nameA[j] == ',') {
			nameA[j] = '\0';
			break;
		}
		j++;
	}
	
	a = GetMatrix(nameA);
	if (a==NULL)
	{
		printf("\tMatrix %s Not Found\n", nameA);
		if (!existL) free(mats[indexL]);
		if (!existU) free(mats[indexU]);
		return;
	}
	
	l = identityMatrix(a->rows);
	u = newMatrix(a->rows, a->cols);
	
	if (l!=NULL && u!=NULL)
	{
		decomposition(a, l, u);
	}
	
	if (existL) deleteMatrix(mats[indexL]->mat);
	mats[indexL]->mat = l;
	if (existU) deleteMatrix(mats[indexU]->mat);
	mats[indexU]->mat = u;
	
	// test: display the result
	displayMatrix(mats[indexL]->mat);
	displayMatrix(mats[indexU]->mat);

	if (!existL) cur_mat++;
	if (!existU) cur_mat++;
}
Пример #20
0
 void MatrixMultiplication(int sqrtElements)
{
	printf("Starting matrix multiplication\n");
	omp_set_num_threads(numThreads);

	int dimA = 512, dimB = 216; //Size should be a multiple of 8 to avoid segmentation fault error on Xeon Phi
	if(sqrtElements>0){
		dimA = dimB = sqrtElements;
	}

	printf("\tMatrixMult, Creating matrices with dimmension %dx%d\n", dimA, dimB);
	matrix2d *A, *B, *C;
	A = createMatrix(dimA, dimB);
	B = createMatrix(dimB, dimA);
	
	printf("\tMatrixMult, Randomizing source matrices\n");
	randomizeMatrix(A);
	randomizeMatrix(B);

	printf("Matrix A:\n");
	printMatrix(A, 'd');
	printf("Matrix B:\n");
	printMatrix(B, 'd');
	//__Offload_report(2);

	printf("\tMatrixMult, Initializing MIC\n");
	int nt;
	nt = omp_get_num_threads();
double totalTime=0, minTime = DBL_MAX, maxTime = 0.;
	
//#pragma offload target(mic:MIC_DEV) \
	 in(A:length(sizeof(matrix2d*))) \
	 in(B:length(sizeof(matrix2d*))) \
	out(C:length(sizeof(matrix2d*)))
#pragma omp parallel
	{
		/* warm up to overcome setup overhead */
		printf("\tMatrixMult, Test run\n");
		C = multiplyMatrices(A, B);
		
//		double totalTime=0, minTime = DBL_MAX, maxTime = 0.;
		struct timeval tvBegin, tvEnd, tvDiff;
		/*Run matrix multiplication numIterations times and calculate the average running time. */
		
		int i;
		for (i = 0; i < numIterations; i++) {
			printf("\tMatrixMult, Starting iter: %d\n", i);
			gettimeofday(&tvBegin, NULL);
			C = multiplyMatrices(A, B);
			gettimeofday(&tvEnd, NULL);
			
			double start =  tvBegin.tv_sec + ((double)tvBegin.tv_usec/1e6);
			double end = tvEnd.tv_sec + ((double)tvEnd.tv_usec/1e6);
			double diff = end - start;
			
			maxTime = (maxTime > diff) ? maxTime : diff;
			minTime = (minTime < diff) ? minTime : diff;
			totalTime += diff;
		}
	}
	printf("\tMatrixMult, Completed\n");
	printf("Product (C):\n");
	printMatrix(C, 'd');
		
	double aveTime = totalTime / numIterations;
	long ops = C->rows * C->cols * C->rows;
	double gflops = (double)ops * (double)numIterations / ((double)(1e9) * aveTime);
	
	printf( "MatrixMult, Summary, ");
	printf( "%d threads,", numThreads);
	printf( "%d iterations,", numIterations);
	printf( "%dx%d matrix,", C->rows, C->cols);
	printf( "%g maxRT,", maxTime);
	printf( "%g minRT,",minTime);
	printf( "%g aveRT,", aveTime);
	printf( "%g totalRT,", totalTime);
	printf( "%d operations per iteration,", ops);
	printf( "%g GFlop/s\n",gflops);

	
	deleteMatrix(A);
	deleteMatrix(B);
	deleteMatrix(C);

	//free(A);
	//free(B);
	//free(C);

	//__Offload_report(2);
	return;
}
Пример #21
0
void NewMatrix(FunctionCall fc)
{
	int i, index, exist = 0, ref;
	int n = 1, m = 0;
	int k = -1, l = -1;
	int sign = 1;
	
	index = IndexMatrix(fc->name);
	if (index==-1)
	{
		index = cur_mat;
		mats[index] = (StrMatObject*)malloc(sizeof(StrMatObject));
		
		if (mats[index] == NULL)
		{
			printf("NewMatrix(): Could not allocate the new matrix\n");
			return;
		}

		for (i = 0; i < MAXSIZE_NAME; i++)
		{
			mats[index]->name[i] = fc->name[i];
			if (fc->name[i]=='\0') break;
		}
	}
	else exist = 1;
	
	if ((ref=IndexMatrix(fc->function))!=-1)
	{
		if (ref==index)
		{
			printf("\tSame Matrix\n");
			return;
		}
		else
		{
			if (exist) deleteMatrix(mats[index]->mat);
			mats[index]->mat = clone(mats[ref]->mat);
			displayMatrix(mats[index]->mat);
			cur_mat++;
			return ;
		}
	}
	else
	{
		if (fc->args[0] == '\0')
		{
			printf("\tMatrix %s Not Found\n", fc->function);
			if (!exist) free(mats[index]);
			return ;
		}
	}
	
	// trying to find out the size of the matrix
	for (i = 0; i < MAXSIZE_ARGS; i++)
	{
		if (fc->args[i] == '[')
		{
			n = 1;
		}

		else if (fc->args[i] == ',')
			n++;

		else if (fc->args[i] == ']')
		{
			m++;
		}
		else if (fc->args[i] == '\0') break;
	}

	if (exist) deleteMatrix(mats[index]->mat);
	mats[index]->mat = newMatrix(m,n);

	for (i = 0; i < MAXSIZE_ARGS; i++)
	{
		if (fc->args[i] == '[')
		{
			k++;
			l = 0;
		}

		else if (fc->args[i] == ',')
			l++;

		else if (fc->args[i] == ']')
			continue;
			
		else if (fc->args[i] == '-')
			sign = -1;

		// it is digit so we add the element to the matrix
		else if (isdigit(fc->args[i]))
		{
			E var = (E)strtod(&(fc->args[i]), NULL);
			setElt(mats[index]->mat, sign*var, k, l);
			while (fc->args[i+1]!=',' && fc->args[i+1]!=']') i++;
			sign = 1;
		}

		// we get the variable referenced
		else if (isalpha(fc->args[i]))
		{
			char name[256] = {0};
			int t = 0;
			E var = 0;

			while (fc->args[i] != ',' && fc->args[i] != ']')
			{
				name[t] = fc->args[i];

				t++;
				i++;
			}

			var = GetVariable(name);
			setElt(mats[index]->mat, sign*var, k, l);
			sign = 1;

			l++; // we increment the rows-counting variable
		}
		
		else if (fc->args[i] == '\0') break;
	}

	// test: display the added matrix
	displayMatrix(mats[index]->mat);

	if (!exist) cur_mat++;
}
Пример #22
0
//This function is used to recognize continuous SLR in a off-line way. 
//Since the data should be read in all at once, the class gcmCont is not necessary used. 
int gcm::patchRun_continuous_PQ(vector<SLR_ST_Skeleton> vSkeletonData, vector<Mat> vDepthData, vector<IplImage*> vColorData, 
								int *rankIndex, double *rankScore)
{
	int window = 40;
	int kernelFeatureDim = NClass*NTrainSample;
	//Computing features
	cout<<"Computing features..."<<endl;
	oriData2Feature(vSkeletonData, vDepthData, vColorData);

	//////////////////////////////////////////////////////////////////////////
	//Compute P and Q all at once.
	vector<double*> P;
	vector<double**> Q;
	cout<<"Computing P and Q..."<<endl;

	//computePQ(P, Q, vColorData.size());
	//white
	for (int d=0; d<nDimension; d++)
	{
		double dimAve = 0.0;
		for (int f=0; f<nFrames; f++)
		{
			dimAve += feature_ori[f][d];
		}
		dimAve /= nFrames;
		for (int f=0; f<nFrames; f++)
		{
			feature_ori[f][d] -= dimAve;
		}
	}

	//Compute P and Q.
	int nFrames_PQ = vColorData.size();
	for (int i=0; i<nFrames_PQ; i++)
	{
		cout<<"Current "<<i<<"/"<<nFrames_PQ<<endl;
		//Compute P
		double* tempP = new double[featureDim];
		for (int j=0; j<featureDim; j++)
		{
			tempP[j] = 0;
			for (int k=0; k<i; k++)
			{
				tempP[j] += feature_ori[k][j];
			}
		}
		P.push_back(tempP);    //To release it when reaching the end of a sentence 

		//Compute Q
		double** tempQ;
		tempQ = newMatrix(featureDim, featureDim);
		for (int f1=0; f1<featureDim; f1++)
		{
			for (int f2=0; f2<featureDim; f2++) 
			{
				tempQ[f1][f2] = 0;
				for (int l=0; l<i; l++)
				{
					tempQ[f1][f2] += feature_ori[f1][l]*feature_ori[f2][l];
				}
			}
		}
		Q.push_back(tempQ);      //To release it when reaching the end of a sentence 
	}
	//////////////////////////////////////////////////////////////////////////	
	
	double** C = newMatrix(featureDim, featureDim);
	double* p_temp = new double[featureDim];  //The deltaP
	double** Pm = newMatrix(featureDim, featureDim);
	for (int i=window; i<vColorData.size()-window; i++)
	{
		int begin = i-window/2;
		int end = i+window/2;

		//The matrix from p
		for (int pf=0; pf<featureDim; pf++)
		{
			p_temp[pf] = P[end][pf]-P[begin][pf];
		}
		vector2matrix(p_temp, p_temp, Pm,featureDim);

		//Compute the covariance matrix
		for (int l=0; l<featureDim; l++)
		{
			for (int m=0; m<featureDim; m++)
			{
				C[l][m] = ((Q[end][l][m]-Q[begin][l][m])-Pm[l][m]/(end-begin+1))/(end-begin);
			}
		}

		//Regularization term added
		for (int d=0; d<nDimension; d++)
		{
			for (int d2=0; d2<nDimension; d2++)
			{
				//C[d][d2] /= nFrames;
				if (d == d2)
				{
					C[d][d2] += 0.001;
				}
			}
		}

		//The subspace matrix
		PQsubspace(C, gcm_subspace);

		//For debug
		ofstream foutDebug;
		foutDebug.open("..\\output\\debug.txt");
		for (int i=0; i<featureDim; i++)
		{
			for (int j=0; j<subSpaceDim; j++)
			{
				foutDebug<<gcm_subspace[i][j]<<"\t";
			}
			foutDebug<<"\n";
		}
		foutDebug << flush;
		foutDebug.close();

		//The SVM classification
		x[0].index = 0;
		for (int j=0; j<kernelFeatureDim; j++)
		{
			subMatrix(subFeaAll_model, subFea1, 0, featureDim, j*subSpaceDim, subSpaceDim);
			x[j+1].value = myGcmKernel.Frobenius(subFea1, gcm_subspace, featureDim, subSpaceDim);
			x[j+1].index=j+1;
		}
		x[kernelFeatureDim+1].index=-1;

		int testID = svm_predict_probability(myModel, x, prob_estimates);
		cout<<"Frame: "<<i<<"/"<<vColorData.size()-window<<" Result: "<<testID<<endl;
	}
	delete[] p_temp;
	deleteMatrix(Pm,featureDim);
	deleteMatrix(C, featureDim);

	//To delete P and Q


	return 1;

// 	gcmSubspace();
// 
// 	x[0].index = 0;
// 	for (int j=0; j<kernelFeatureDim; j++)
// 	{
// 		subMatrix(subFeaAll_model, subFea1, 0, featureDim, j*subSpaceDim, subSpaceDim);
// 		x[j+1].value = myGcmKernel.Frobenius(subFea1, gcm_subspace, featureDim, subSpaceDim);
// 		x[j+1].index=j+1;
// 	}
// 	x[kernelFeatureDim+1].index=-1;
// 
// 	int testID = svm_predict_probability(myModel, x, prob_estimates);
// 
// 	//Sort and get the former 5 ranks. 
// 	vector<scoreAndIndex> rank;
// 	for (int i=0; i<myModel->nr_class; i++)
// 	{
// 		scoreAndIndex temp;
// 		temp.index = myModel->label[i];
// 		temp.score = prob_estimates[i];
// 		rank.push_back(temp);
// 	}
// 	sort(rank.begin(),rank.end(),comp);
// 
// 	for (int i=0; i<5; i++)
// 	{
// 		rankIndex[i] = rank[i].index;
// 		rankScore[i] = rank[i].score;
// 	}
// 
// 
// 	//Release
// 	nFrames = 0;
// 
// 	return testID;
}
Пример #23
0
void Solve(FunctionCall fc)
{
	int i, j, index, exist = 0;
	Matrix a, b, x;
	char name[MAXSIZE_NAME] = {0};

	index = IndexMatrix(fc->name);
	if (index==-1)
	{
		index = cur_mat;
		mats[index] = (StrMatObject*)malloc(sizeof(StrMatObject));
		
		if (mats[index] == NULL)
		{
			printf("NewMatrix(): Could not allocate the new matrix\n");
			return;
		}

		for (i = 0; i < MAXSIZE_NAME; i++)
		{
			mats[index]->name[i] = fc->name[i];
			if (fc->name[i]=='\0') break;
		}
	}
	else exist = 1;
	
	j = 0;
	// searching for first matrix name
	for (i = 0; i < MAXSIZE_NAME; i++)
	{
		name[j] = fc->args[i];
		if (name[j] == ',') {
			name[j] = '\0';
			break;
		}
		j++;
	}
	
	a = GetMatrix(name);
	if (a==NULL)
	{
		printf("\tMatrix %s Not Found\n", name);
		if (!exist) free(mats[index]);
		return;
	}
	
	j = 0;
	// searching for second matrix name
	for (i = i+1; i < MAXSIZE_NAME; i++)
	{
		name[j] = fc->args[i];
		if (name[j] == '\0') break;
		j++;
	}
	
	b = GetMatrix(name);
	if (b==NULL)
	{
		printf("\tMatrix %s Not Found\n", name);
		if (!exist) free(mats[index]);
		return;
	}
	
	// testing numbers of rows and columns of both matrix
	if (a->rows==a->cols && a->rows==b->rows && b->cols==1)
	{
		x = gauss(a,b);
	}
	else
	{
		printf("\tMatrix 1 must be square matrix\n");
		printf("\tRows of Matrix 2 must be equal to Rows of Matrix 1\n");
		printf("\tMatrix 2 must only have one Column\n");
		if (!exist) free(mats[index]);
		return;
	}
	
	if (exist) deleteMatrix(mats[index]->mat);
	mats[index]->mat = x;
	
	// test: display the result
	displayMatrix(mats[index]->mat);
	
	if (!exist) cur_mat++;
}
Пример #24
0
int main(int argc, char *argv[])
{
	FILE *stream = NULL;
	int i, j, r, count;
	bool flag;

	Matrix matrix = NULL;
	Vector rhs = NULL;
	VectorArray Lattice = NULL;
	Vector vector = NULL;

	LinearSystem initialsystem;
	ZSolveContext ctx;

	char *token;
	int memory;

	getopts(argc, argv);

	puts(FORTY_TWO_BANNER);

	if (OResume)
	{
		// START OF RESUME SECTION - READ FILES AND CREATE CONTEXT 

		strcat(BaseName, ".backup");
		stream = fopen(BaseName, "r");
		BaseName[BaseLength] = '\0';

		if (stream==NULL)
		{
			printf("Unable to open backup file %s.backup\n", BaseName);
			free(BaseName);
			exit(1);
		}

		// options
		if (fscanf(stream, "%d %d %d", &OVerbose, &OLogging, &OBackup)!=3 || OVerbose<0 || OVerbose>3 || OLogging<0 || OLogging>3 || OBackup<0)
		{
			fclose(stream);
			printf("Backup file %s.backup does not contain valid data.\n", BaseName);
			free(BaseName);
			exit(2);
		}

		// get context
		ctx = createZSolveContextFromBackup(stream, zsolveLogCallbackDefault, backupEvent);
		fclose(stream);

		// logfile
		if (OLogging>0)
		{
			strcat(BaseName, ".log");
			stream = fopen(BaseName, "a");
			BaseName[BaseLength] = '\0';
			if (stream==NULL)
			{
				printf("Unable to open log file %s.log\n", BaseName);
				free(BaseName);
				exit(1);
			}
			ctx->LogFile = LogFile = stream;
		}

		// END OF RESUME SECTION
	}
	else
	{
		// logfile
		if (OLogging>0)
		{
			strcat(BaseName, ".log");
			stream = fopen(BaseName, "w");
			BaseName[BaseLength] = '\0';
			if (stream==NULL)
			{
				printf("Unable to open log file %s.log\n", BaseName);
				free(BaseName);
				exit(1);
			}
			LogFile = stream;
		}
		// check for existance of solution files
		if (!OForce)
		{
			strcat(BaseName, ".zhom");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				fclose(stream);
				if (OVerbose>0)
					printf("%s.hom already exists! Use -f to force calculation.\n", BaseName);
				if (OLogging>0)
				{
					fprintf(LogFile, "%s.hom already exists! Use -f to force calculation.\n", BaseName);
					fclose(LogFile);
				}
				free(BaseName);
				exit(1);
			}
			strcat(BaseName, ".zinhom");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				fclose(stream);
				if (OVerbose>0)
					printf("%s.inhom already exists! Use -f to force calculation.\n", BaseName);
				if (LogFile)
				{
					fprintf(LogFile, "%s.inhom already exists! Use -f to force calculation.\n", BaseName);
					fclose(LogFile);
				}
				free(BaseName);
				exit(1);
			}
		}
	
		// matrix
		strcat(BaseName, ".mat");
		stream = fopen(BaseName, "r");
		BaseName[BaseLength] = '\0';

		if (stream == NULL)
		{
			stream = fopen(BaseName, "r");
			if (stream) {
				if (OVerbose>0)
					printf("Matrix file %s.mat not found, falling back to project file %s.\n\n", BaseName, BaseName);
				if (OLogging>0)
				{
					fprintf(LogFile, "Matrix file %s.mat not found, falling back to project file %s.\n\n", BaseName, BaseName);
					fclose(LogFile);
				}
			}
		}

		if (stream==NULL)
		{
			strcat(BaseName, ".lat");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream==NULL)
			{
				// lattice
				if (OVerbose>0)
					printf("Neither matrix file %s.mat nor lattice file %s.lat exists!\n", BaseName, BaseName);
				if (OLogging>0)
				{
					fprintf(LogFile, "Neither matrix file %s.mat nor lattice file %s.lat exists!\n", BaseName, BaseName);
					fclose(LogFile);
				}
				free(BaseName);
				exit(1);
			}
			else
			{
				// START OF LATTICE SECTION - READ FILES AND CREATE CONTEXT

				Lattice = readVectorArray(stream, false);
				fclose(stream);
				if (Lattice == NULL)
				{
					if (OVerbose>0)
						printf("Lattice file %s.lat does not contain valid data.\n", BaseName);
					if (OLogging>0)
					{
						fprintf(LogFile, "Lattice file %s.lat does not contain valid data.\n", BaseName);
						fclose(LogFile);
					}
					free(BaseName);
					exit(1);
				}
			
				// rhs
				if (ORightHandSide)
				{
					strcat(BaseName, ".rhs");
					stream = fopen(BaseName, "r");
					BaseName[BaseLength] = '\0';
					if (stream!=NULL)
					{
						fscanf(stream, "%d", &i);
						if (i!=1)
						{
							fclose(stream);
							printf("Height of RHS must be 1!\n");
							if (LogFile)
							{
								fprintf(LogFile, "Height of RHS must be 1!\n");
								fclose(LogFile);
							}
							deleteMatrix(matrix);
							free(BaseName);
							exit(1);
						}
						fscanf(stream, "%d", &i);
						while (i--)
						{
							if (fscanf(stream, "%d", &j) || j!=0)
							{
								printf("When reading from %s.lat, RHS file %s.rhs must contain a zero vector.\n", BaseName, BaseName);
								if (LogFile)
								{
									fprintf(LogFile, "When reading from %s.lat, RHS file %s.rhs must contain a zero vector.\n", BaseName, BaseName);
									fclose(LogFile);
								}
								deleteMatrix(matrix);
								free(BaseName);
								exit(1);
							}
						}
					}
				}

				// variable properties

				for (i=0; i<Lattice->Variables; i++)
				{
					Lattice->Properties[i].Column = i;
					Lattice->Properties[i].Lower = OHilbert ? 0 : -MAXINT;
					Lattice->Properties[i].Upper = MAXINT;
					Lattice->Properties[i].Free = (!OGraver && !OHilbert);
				}
			
				// read .rel
				strcat(BaseName, ".rel");
				stream = fopen(BaseName, "r");
				BaseName[BaseLength] = '\0';
				if (stream!=NULL)
				{
					token = NULL;
					memory = 0;
					flag = false;

					if (fscanf(stream, "%d %d", &r, &j)<2 || r != 1)
					{
						printf("RELATION file %s.rel must start with the dimensions.\n", BaseName);
						flag = true;
					}

					for (i=0; i<j; i++)
					{
						if (readTokenFromFile(stream, "0123456789=<>", &token, &memory) == 0)
						{
							printf("RELATION file %s.rel ends unexpectedly.\n", BaseName);
							flag = true;
						}
						else if (!strcmp(token, "<") || !strcmp(token, ">"))
						{
							printf("When reading from %s.lat, inequalities are not allowed.\n", BaseName);
							flag = true;
						}
						else if (strcmp(token, "="))
						{
							printf("Unknown token '%s' in RELATION file %s.rel.\n", token, BaseName);
							flag = true;
						}
					}
					free(token);
					fclose(stream);
	
					if (flag)
					{
						free(BaseName);
						exit(1);
					}
				}
			
				// read .sign
				strcat(BaseName, ".sign");
				stream = fopen(BaseName, "r");
				BaseName[BaseLength] = '\0';
				if (stream!=NULL)
				{
					token = NULL;
					memory = 0;
					flag = false;
	
					if (fscanf(stream, "%d %d", &r, &i)<2 || i != Lattice->Variables || r != 1)
					{
						printf("SIGN file %s.sign must start with '1 %d'.\n", BaseName, Lattice->Variables);
						flag = true;
					}
	
					for (i=0; i<Lattice->Variables; i++)
					{
						if (readTokenFromFile(stream, "0123456789-abcdefghijklmnopqrstuvwxyz", &token, &memory) == 0)
						{
							printf("SIGN file %s.sign ends unexpectedly.\n", BaseName);
							flag = true;
						}
						if (!strcmp(token, "0") || !strcmp(token, "free") || !strcmp(token, "f"))
						{
							Lattice->Properties[i].Upper = MAXINT;
							Lattice->Properties[i].Lower = -MAXINT;
							Lattice->Properties[i].Free = true;
						}
						else if (!strcmp(token, "1") || !strcmp(token, "hil") || !strcmp(token, "h"))
						{
							Lattice->Properties[i].Upper = MAXINT;
							Lattice->Properties[i].Lower = 0;
							Lattice->Properties[i].Free = false;
						}
						else if (!strcmp(token, "-1") || !strcmp(token, "-hil") || !strcmp(token, "-h"))
						{
							Lattice->Properties[i].Upper = 0;
							Lattice->Properties[i].Lower = -MAXINT;
							Lattice->Properties[i].Free = false;
						}
						else if (!strcmp(token, "2") || !strcmp(token, "graver") || !strcmp(token, "g"))
						{
							if (OHilbert)
							{
								printf("Input Error: Graver components for `hilbert' executable.\nInput Error: Use the `graver' executable instead.\n");
								flag = true;
							}
							else
							{
								Lattice->Properties[i].Upper = MAXINT;
								Lattice->Properties[i].Lower = -MAXINT;
								Lattice->Properties[i].Free = false;
							}
						}
						else
						{
							printf("Unknown token '%s' in SIGN file %s.sign.\n", token, BaseName);
							flag = true;
						}
					}
					free(token);
					fclose(stream);

					if (flag)
					{
						deleteVectorArray(Lattice);
						free(BaseName);
						exit(1);
					}
				}
			
				// read .ub
				strcat(BaseName, ".ub");
				stream = fopen(BaseName, "r");
				BaseName[BaseLength] = '\0';
				if (stream!=NULL)
				{
					token = NULL;
					memory = 0;
					flag = false;
		
					if (fscanf(stream, "%d %d", &r, &i)<2 || i != Lattice->Variables || r != 1)
					{
						printf("UPPER BOUNDS file %s.ub must start with '1 %d'.\n", BaseName, Lattice->Variables);
						flag = true;
					}
	
					for (i=0; i<Lattice->Variables; i++)
					{
						if (readTokenFromFile(stream, "0123456789*-", &token, &memory) == 0)
						{
							printf("UPPER BOUNDS file %s.ub ends unexpectedly.\n", BaseName);
							flag = true;
						}
						if (!strcmp(token, "*"))
							Lattice->Properties[i].Upper = MAXINT;
						else if (sscanf(token, "%d", &j) == 1)
						{
							if (Lattice->Properties[i].Free)
							{
								printf("Upper bound '%s' cannot be set for free variables.\n", token);
								flag = true;
							}
							else if (j>=0)
								Lattice->Properties[i].Upper = j;
							else
							{
								printf("Negative upper bound '%s' in UPPER BOUNDS file %s.ub.\n", token, BaseName);
								flag = true;
							}
						}
						else
						{
							printf("Unknown token '%s' in UPPER BOUNDS file %s.ub.\n", token, BaseName);
							flag = true;
						}
					}
					free(token);
					fclose(stream);
		
					if (flag)
					{
						deleteVectorArray(Lattice);
						free(BaseName);
						exit(1);
					}
				}

				// read .lb
				strcat(BaseName, ".lb");
				stream = fopen(BaseName, "r");
				BaseName[BaseLength] = '\0';
				if (stream!=NULL)
				{
					token = NULL;
					memory = 0;
					flag = false;
		
					if (fscanf(stream, "%d %d", &r, &i)<2 || i != Lattice->Variables || r != 1)
					{
						printf("LOWER BOUNDS file %s.lb must start with '1 %d'.\n", BaseName, Lattice->Variables);
						flag = true;
					}
	
					for (i=0; i<Lattice->Variables; i++)
					{
						if (readTokenFromFile(stream, "0123456789*-", &token, &memory) == 0)
						{
							printf("LOWER BOUNDS file %s.lb ends unexpectedly.\n", BaseName);
							flag = true;
						}
						if (!strcmp(token, "*"))
							Lattice->Properties[i].Lower = -MAXINT;
						else if (sscanf(token, "%d", &j) == 1)
						{
							if (Lattice->Properties[i].Free)
							{
								printf("Lower bound '%s' cannot be set for free variables.\n", token);
								flag = true;
							}
							else if (j<=0)
								Lattice->Properties[i].Lower = j;
							else
							{
								printf("Positive lower bound '%s' in LOWER BOUNDS file %s.lb.\n", token, BaseName);
								flag = true;
							}
						}
						else
						{
							printf("Unknown token '%s' in LOWER BOUNDS file %s.lb.\n", token, BaseName);
							flag = true;
						}
					}
					free(token);
					fclose(stream);
		
					if (flag)
					{
						deleteVectorArray(Lattice);
						free(BaseName);
						exit(1);
					}
				}
	
				ctx = createZSolveContextFromLattice(Lattice, LogFile, OLogging, OVerbose, zsolveLogCallbackDefault, backupEvent);
			
				// print lattice
				if (ctx->Verbosity>0)
				{
					printf("\nLattice to use:\n\n");
					printVectorArray(ctx->Lattice, false);
					printf("\n\n");
				}
				if (ctx->LogLevel>0)
				{
					fprintf(ctx->LogFile, "\nLattice to use:\n\n");
					fprintVectorArray(ctx->LogFile, ctx->Lattice, false);
					fprintf(ctx->LogFile, "\n\n");
				}

				// END OF LATTICE SECTION
			}
		}
		else
		{
			// START OF SYSTEM SECTION - READ FILES AND CREATE CONTEXT

			matrix = readMatrix(stream);
			fclose(stream);
			if (matrix==NULL)
			{
				printf("Matrix file %s does not contain valid data.\n", BaseName);
				if (LogFile)
				{
					fprintf(LogFile, "Matrix file %s does not contain valid data.\n", BaseName);
					fclose(LogFile);
				}
				free(BaseName);
				exit(1);
			}
	
			// rhs
			if (ORightHandSide)
			{
				strcat(BaseName, ".rhs");
				stream = fopen(BaseName, "r");
				BaseName[BaseLength] = '\0';
				if (stream!=NULL)
				{
					if (OGraver || OHilbert)
					{
						fclose(stream);
						printf("Input Error: No rhs file is allowed with --graver and --hilbert!\n");
						printf("Input Error: Please delete %s.rhs and rerun zsolve\n", BaseName);
						if (LogFile)
						{
							fprintf(LogFile, "Input Error: No rhs file is allowed with --graver and --hilbert!\n");
							fprintf(LogFile, "Input Error: Please delete %s.rhs and rerun zsolve\n", BaseName);
							fclose(LogFile);
						}
						deleteMatrix(matrix);
						free(BaseName);
						exit(1);
					}
					
					fscanf(stream, "%d", &i);
					if (i!=1)
					{
						fclose(stream);
						printf("Height of RHS must be 1!\n");
						if (LogFile)
						{
							fprintf(LogFile, "Height of RHS must be 1!\n");
							fclose(LogFile);
						}
						deleteMatrix(matrix);
						free(BaseName);
						exit(1);
					}
					fscanf(stream, "%d", &i);
					if (i!=matrix->Height)
					{
						fclose(stream);
						printf("Matrix height conflicts with width of rhs!\n");
						if (LogFile)
						{
							fprintf(LogFile, "Matrix height conflicts with width of rhs!\n");
							fclose(LogFile);
						}
						deleteMatrix(matrix);
						free(BaseName);
						exit(1);
					}
					rhs = readVector(stream, matrix->Height);
					fclose(stream);
					if (rhs==NULL)
					{
						printf("RHS file %s.rhs does not contain valid data.\n", BaseName);
						if (LogFile)
						{
							fprintf(LogFile, "RHS file %s.rhs does not contain valid data.\n", BaseName);
							fclose(LogFile);
						}
						deleteMatrix(matrix);
						free(BaseName);
						exit(1);
					}
				}
			}

			// fill with zeros
			if (rhs==NULL)
			{
				rhs = createVector(matrix->Height);
				for (i=0; i<matrix->Height; i++)
					rhs[i] = 0;
			}

			// create system
			initialsystem = createLinearSystem();
	
			setLinearSystemMatrix(initialsystem, matrix);
			deleteMatrix(matrix);

			setLinearSystemRHS(initialsystem, rhs);
			deleteVector(rhs);

			// default limits

			if (OGraver)
				setLinearSystemLimit(initialsystem, -1, -MAXINT, MAXINT, false);
			else if (OHilbert)
				setLinearSystemLimit(initialsystem, -1, 0, MAXINT, false);
			else
				setLinearSystemLimit(initialsystem, -1, -MAXINT, MAXINT, true);
	
			// default equation type

			setLinearSystemEquationType(initialsystem, -1, EQUATION_EQUAL, 0);

			// read .rel
			strcat(BaseName, ".rel");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				token = NULL;
				memory = 0;
				flag = false;

				if (fscanf(stream, "%d %d", &r, &i)<2 || i != initialsystem->Equations || r != 1)
				{
					printf("RELATION file %s.rel must start with '1 %d'.\n", BaseName, initialsystem->Equations);
					flag = true;
				}

				for (i=0; i<initialsystem->Equations; i++)
				{
					if (readTokenFromFile(stream, "0123456789=<>", &token, &memory) == 0)
					{
						printf("RELATION file %s.rel ends unexpectedly.\n", BaseName);
						flag = true;
					}
					if (!strcmp(token, "="))
						setLinearSystemEquationType(initialsystem, i, EQUATION_EQUAL, 0);
					// BUG: Not a real bug, but maybe misdefinition?? <= is not so hard to type :-)
					else if (!strcmp(token, "<"))
						setLinearSystemEquationType(initialsystem, i, EQUATION_LESSEREQUAL, 0);
					else if (!strcmp(token, ">"))
						setLinearSystemEquationType(initialsystem, i, EQUATION_GREATEREQUAL, 0);
					else
					{
						printf("Unknown token '%s' in RELATION file %s.rel.\n", token, BaseName);
						flag = true;
					}
				}
				free(token);
				fclose(stream);

				if (flag)
				{
					deleteLinearSystem(initialsystem);
					free(BaseName);
					exit(1);
				}
			}

			// read .sign
			strcat(BaseName, ".sign");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				token = NULL;
				memory = 0;
				flag = false;

				if (fscanf(stream, "%d %d", &r, &i)<2 || i != initialsystem->Variables || r != 1)
				{
					printf("SIGN file %s.sign must start with '1 %d'.\n", BaseName, initialsystem->Variables);
					flag = true;
				}

				for (i=0; i<initialsystem->Variables; i++)
				{
					if (readTokenFromFile(stream, "0123456789-abcdefghijklmnopqrstuvwxyz", &token, &memory) == 0)
					{
						printf("SIGN file %s.sign ends unexpectedly.\n", BaseName);
						flag = true;
					}
					if (!strcmp(token, "0") || !strcmp(token, "free") || !strcmp(token, "f"))
						setLinearSystemLimit(initialsystem, i, -MAXINT, MAXINT, true);
					else if (!strcmp(token, "1") || !strcmp(token, "hil") || !strcmp(token, "h"))
						setLinearSystemLimit(initialsystem, i, 0, MAXINT, false);
					else if (!strcmp(token, "-1") || !strcmp(token, "-hil") || !strcmp(token, "-h"))
						setLinearSystemLimit(initialsystem, i, -MAXINT, 0, false);
					else if (!strcmp(token, "2") || !strcmp(token, "graver") || !strcmp(token, "g"))
					{
						if (OHilbert)
						{
							if (!flag)
								printf("Input Error: Graver components for `hilbert' executable.\nInput Error: Use the `graver' executable instead.\n");
							flag = true;
						}
						else
							setLinearSystemLimit(initialsystem, i, -MAXINT, MAXINT, false);
					}
					else
					{
						printf("Unknown token '%s' in SIGN file %s.sign.\n", token, BaseName);
						flag = true;
					}
				}
				free(token);
				fclose(stream);

				if (flag)
				{
					deleteLinearSystem(initialsystem);
					free(BaseName);
					exit(1);
				}
			}

			// read .ub
			strcat(BaseName, ".ub");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				token = NULL;
				memory = 0;
				flag = false;
	
				if (fscanf(stream, "%d %d", &r, &i)<2 || i != initialsystem->Variables || r != 1)
				{
					printf("UPPER BOUNDS file %s.ub must start with '1 %d'.\n", BaseName, initialsystem->Variables);
					flag = true;
				}

				for (i=0; i<initialsystem->Variables; i++)
				{
					if (readTokenFromFile(stream, "0123456789*-", &token, &memory) == 0)
					{
						printf("UPPER BOUNDS file %s.ub ends unexpectedly.\n", BaseName);
						flag = true;
					}
					if (!strcmp(token, "*"))
						setLinearSystemBound(initialsystem, i, 'u', MAXINT);
					else if (sscanf(token, "%d", &j) == 1)
					{
						if (initialsystem->VarProperties[i].Free)
						{
							printf("Upper bound '%s' cannot be set for free variables.\n", token);
							flag = true;
						}
						else if (j>=0)
							setLinearSystemBound(initialsystem, i, 'u', j);
						else
						{
							printf("Negative upper bound '%s' in UPPER BOUNDS file %s.ub.\n", token, BaseName);
							flag = true;
						}
					}
					else
					{
						printf("Unknown token '%s' in UPPER BOUNDS file %s.ub.\n", token, BaseName);
						flag = true;
					}
				}
				free(token);
				fclose(stream);
	
				if (flag)
				{
					deleteLinearSystem(initialsystem);
					free(BaseName);
					exit(1);
				}
			}

			// read .lb
			strcat(BaseName, ".lb");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				token = NULL;
				memory = 0;
				flag = false;
	
				if (fscanf(stream, "%d %d", &r, &i)<2 || i != initialsystem->Variables || r != 1)
				{
					printf("LOWER BOUNDS file %s.lb must start with '1 %d'.\n", BaseName, initialsystem->Variables);
					flag = true;
				}

				for (i=0; i<initialsystem->Variables; i++)
				{
					if (readTokenFromFile(stream, "0123456789*-", &token, &memory) == 0)
					{
						printf("LOWER BOUNDS file %s.lb ends unexpectedly.\n", BaseName);
						flag = true;
					}
					if (!strcmp(token, "*"))
						setLinearSystemBound(initialsystem, i, 'l', -MAXINT);
					else if (sscanf(token, "%d", &j) == 1)
					{
						if (initialsystem->VarProperties[i].Free)
						{
							printf("Lower bound '%s' cannot be set for free variables.\n", token);
							flag = true;
						}
						else if (j<=0)
							setLinearSystemBound(initialsystem, i, 'l', j);
						else
						{
							printf("Positive lower bound '%s' in LOWER BOUNDS file %s.lb.\n", token, BaseName);
							flag = true;
						}
					}
					else
					{
						printf("Unknown token '%s' in LOWER BOUNDS file %s.lb.\n", token, BaseName);
						flag = true;
					}
				}
				free(token);
				fclose(stream);
	
				if (flag)
				{
					deleteLinearSystem(initialsystem);
					free(BaseName);
					exit(1);
				}
			}

			ctx = createZSolveContextFromSystem(initialsystem, LogFile, OLogging, OVerbose, zsolveLogCallbackDefault, backupEvent);
	
			// END OF SYSTEM SECTION
		}
	}

	// DEBUG
//	printVectorArray(ctx->Lattice, true);

	zsolveSystem(ctx, !OResume);

	if (OGraver)
	{
		printf("Writing %d vectors to graver file, with respect to symmetry.\n", ctx->Graver->Size);
		if (LogFile)
			fprintf(LogFile, "Writing %d vectors to graver file, with respect to symmetry.\n", ctx->Graver->Size);
		
		strcat(BaseName, ".gra");
		stream = fopen(BaseName, "w");
		BaseName[BaseLength] = '\0';
		if (stream)
		{
			fprintf(stream, "%d %d\n\n", ctx->Graver->Size, ctx->Graver->Variables);
			fprintVectorArray(stream, ctx->Graver, false);
			fclose(stream);
		}
	}
	else if (OHilbert)
	{
		strcat(BaseName, ".hil");
		stream = fopen(BaseName, "w");
		BaseName[BaseLength] = '\0';
		if (stream)
		{
			fprintf(stream, "%d %d\n\n", ctx->Homs->Size + ctx->Frees->Size, ctx->Homs->Variables);
			fprintVectorArray(stream, ctx->Homs, false);
			fprintf(stream, "\n");
			fprintVectorArray(stream, ctx->Frees, false);
			fclose(stream);
		}
	}
	else
	{
		strcat(BaseName, ".zinhom");
		stream = fopen(BaseName, "w");
		BaseName[BaseLength] = '\0';
		if (stream)
		{
			fprintf(stream, "%d %d\n\n", ctx->Inhoms->Size, ctx->Inhoms->Variables);
			fprintVectorArray(stream, ctx->Inhoms, false);
			fclose(stream);
		}

		strcat(BaseName, ".zhom");
		stream = fopen(BaseName, "w");
		BaseName[BaseLength] = '\0';
		if (stream)
		{
			fprintf(stream, "%d %d\n\n", ctx->Homs->Size, ctx->Homs->Variables);
			fprintVectorArray(stream, ctx->Homs, false);
			fclose(stream);
		}

		if (ctx->Frees->Size>0)
		{
			strcat(BaseName, ".zfree");
			stream = fopen(BaseName, "w");
			BaseName[BaseLength] = '\0';
			if (stream)
			{
				fprintf(stream, "%d %d\n\n", ctx->Frees->Size, ctx->Frees->Variables);
				fprintVectorArray(stream, ctx->Frees, false);
				fclose(stream);
			}
		}
	}


	printf("\n4ti2 Total Time: ");
	printCPUTime(maxd(getCPUTime() - ctx->AllTime, 0.0));
	printf("\n");
	if (LogFile) {
		fprintf(LogFile, "\n4ti2 Total Time: ");
		fprintCPUTime(LogFile, maxd(getCPUTime() - ctx->AllTime, 0.0));
		fprintf(LogFile, "\n");
	}

	deleteZSolveContext(ctx, true);

	if (BaseName!=NULL)
		free(BaseName);

	if (LogFile)
		fclose(LogFile);

	return EXIT_SUCCESS;
}
Пример #25
0
void main(void) {

    unsigned char i,j;

    /* Output configurations */

    ADCON1 |= 0x0F;    // All possible analog input pins config as digital I/O
    CMCON = 0x07;    // Comparators disabled

    /* Natural interaction expansion port configuration    */
    TRISAbits.TRISA4 = 1;    // A4 Botton 3
    TRISAbits.TRISA3 = 1;    // A3 Botton 2
    TRISAbits.TRISA2 = 1;    // A2 Botton 1
    TRISAbits.TRISA1 = 1;    // A1 Potentiometer 2
    TRISAbits.TRISA0 = 1;    // A0 Potentiometer 1

    TRISB = 0;    // B0..B6    Serial input for the Shift Registers
    TRISD = 0;    // D0..D3    Shift Registers control inputs: SCK, RCK, _SCL, _G
    TRISEbits.TRISE0 = 1; //Input button PORTEbits.RE0

    LATA = 0;    // Disable expansion port
    _SCL = 1;    // Disable Shift Register _SCL (Global Clear)
    _G = 0;        // Enables Shift Regusters outputs _G

    // Resetting variables
    for (i = 0; i <= MAX_INDEX_G_BUFFER_GREYSCALE; i++) {
        gBufferGreyscale[i] = 0;
        gPreBufferGreyscale[i] = 0;
    }
    for (i = 0; i <= MAX_INDEX_M_BUFFER_MATRIX; i++) {
        mBufferMatrix[i] = RESET_M_BUFFER_MATRIX;
    }
    iGreyscale = 0;
    iTimer1 = 0;
    iMenu = 0;
    FIRST = 0;
    SECOND = 0;
    THIRD = 0;
    FOURTH = 0;
    FIFTH = 0;
    SIXTH = 0;
    pwm = 0;

    /* Timer 0 Configuration */
    // Used to trigger the refresh matrix printed data routine
    OpenTimer0(TIMER_INT_ON & T0_8BIT & T0_SOURCE_INT & T0_PS_1_1);
    WriteTimer0(0);

    /* Timer 1 Configuration */
    // Used to periodically check the input data (external buttons)
    OpenTimer1(TIMER_INT_ON & T1_SOURCE_INT &  T1_PS_1_8 & T1_OSC1EN_OFF & T1_SYNC_EXT_OFF);
    WriteTimer1( 0x00 & 0x00 );

    /* Timer 3 Configuration */
    // Used to create delays within the different menus without blocking with delays
    OpenTimer3( TIMER_INT_ON & T3_16BIT_RW & T3_SOURCE_INT & T3_PS_1_8 & T3_SYNC_EXT_OFF);
    WriteTimer3( 0x00 & 0x00 );

    /* A/D configuration */
    //ADCON1
    ADCON1bits.VCFG1 = 0;    // Voltage Reference Configuration bit (Vref-) = Vss
    ADCON1bits.VCFG0 = 0;    // Voltage Reference Configuration bit (Vref+) = Vdd
    ADCON1bits.PCFG3 = 1;    // PCFG = "1110" enables AN0 and AN1
    ADCON1bits.PCFG2 = 1;
    ADCON1bits.PCFG1 = 1;
    ADCON1bits.PCFG0 = 0;

    //ADCON0
    ADCON0bits.ADON = 1;    // A/D converter module is enabled
    ADCON0bits.CHS0 = 0;    // CHS = "0000" AN0 selected
    ADCON0bits.CHS1 = 0;
    ADCON0bits.CHS2 = 0;
    ADCON0bits.CHS3 = 0;

    //ADCON2
    ADCON2bits.ADCS0 = 0;    // A/D Adquisition Clock Select bits
    ADCON2bits.ADCS1 = 1;    // Tad = conversion time per bit. The A/D conversion requires 11 Tad
    ADCON2bits.ADCS2 = 0;    // "010" = 32 * Tosc

    ADCON2bits.ACQT0 = 0;    // A/D Adquisition time bits    "000" = Manual adquisition
    ADCON2bits.ACQT1 = 0;
    ADCON2bits.ACQT2 = 0;
    ADCON2bits.ADFM = 0;    // Left justified     . . .ADRESH . . : . . ADRESL. . .
    //                    7 6 5 4 3 2 1 0 : 7 6 5 4 3 2 1 0
    //                    X X X X X X X X . X X . . . . . . <-Left Justified


    /* Enabling interrups */
    INTCONbits.TMR0IE = 1;    // Enables interrupts for TIMER0
    PIE1bits.TMR1IE = 1;    // Enables interrupts for TIMER1
    PIE2bits.TMR3IE = 1;    // Enables interrupts for TIMER3
    INTCONbits.PEIE = 1;    // Peripherial interrupt enabled
    INTCONbits.GIE = 1;    // Global interrupt enabled


    /* Main Loop */
    while(1)
    {

        /*    Main MENU includes the different modes that the table can show
            Switching between menus is done using external button(RE0):

                0 - Fixed light dimmed with external control
                1 - Slow square
                2 - Slow chess board
                3 - Message
                4 - Invaders
                5 - Party (Dirty)

        */
        switch(iMenu) {

        /******************************************************************/
        /* 0 - Fixed light dimmed with external control                   */
        /******************************************************************/
        case 0:
            if (FIRST == 0) {
                deleteMatrix();
                (FIRST = 1);
            }
            drawLine(1,1,1,5,pwm);    //dirty way to draw the all pixels at the same time
            drawLine(2,1,2,5,pwm);
            drawLine(3,1,3,5,pwm);
            drawLine(4,1,4,5,pwm);
            drawLine(5,1,5,5,pwm);
            break;

        /******************/
        /* 1- Slow square */
        /******************/
        case 1:
            if (SECOND == 0) {
                deleteMatrix();
                (SECOND = 1);
            }
            for(j = 130, i = 254; j<=254; j++, i--) {
                drawSquare(1,1,5,5,j);
                drawSquare(2,2,4,4,i);
                drawPoint(3,3,j);
                Delay10KTCYx(100);
                if(iMenu != 1) {
                    break;
                }
            }
            if(iMenu != 1) {
                break;
            }
            for(j = 130, i = 254; j<=254; j++, i--) {
                drawSquare(1,1,5,5,i);
                drawSquare(2,2,4,4,j);
                drawPoint(3,3,i);
                Delay10KTCYx(100);
                if(iMenu != 1) {
                    break;
                }
            }
            if(iMenu != 1) {
                break;   // It allows to break the case during the executation
            }

        /***********************/
        /* 2- Slow Chess board */
        /***********************/
        case 2:
            if (THIRD == 0) {
                deleteMatrix();
                (THIRD = 1);
            }
            for(j = 130, i = 254; j<=254; j++, i--) {
                drawPoint(1,5,j);
                drawLine(1,3,3,5,j);
                drawLine(1,1,5,5,j);
                drawLine(3,1,5,3,j);
                drawPoint(5,1,j);

                drawLine(1,4,2,5,i);
                drawLine(1,2,4,5,i);
                drawLine(2,1,5,4,i);
                drawLine(4,1,5,2,i);
                Delay10KTCYx(100);
                if(iMenu != 2) {
                    break;
                }
            }
            if(iMenu != 2) {
                break;
            }
            for(j = 130, i = 254; j<=254; j++, i--) {
                drawPoint(1,5,i);
                drawLine(1,3,3,5,i);
                drawLine(1,1,5,5,i);
                drawLine(3,1,5,3,i);
                drawPoint(5,1,i);

                drawLine(1,4,2,5,j);
                drawLine(1,2,4,5,j);
                drawLine(2,1,5,4,j);
                drawLine(4,1,5,2,j);
                Delay10KTCYx(100);
                if(iMenu != 2) {
                    break;
                }
            }
            if(iMenu != 2) {
                break;   // It allows to break the case during the executation
            }


        /**************/
        /* 3- Message */
        /**************/
        case 3:
            if (FOURTH == 0) {
                deleteMatrix();
                (FOURTH = 1);
            }
            //knightRider(4);
            scrollText((rom unsigned char *)&Nino[0], TRANS_RIGHT_2_LEFT);

            break;



        /***************/
        /* 4- Invaders */
        /***************/
        case 4:
            if (FIFTH == 0) {
                deleteMatrix();
                (FIFTH = 1);
            }
            for(i = 1; i <= INVADERS_PAIR_REPETITIONS; i++) {
                drawFrame((rom unsigned char *)&invaders[0]);
                Delay10KTCYx(DELAY_INVADERS);
                if(iMenu != 4) {
                    break;
                }
                drawFrame((rom unsigned char *)&invaders[1]);
                Delay10KTCYx(DELAY_INVADERS);
                if(iMenu != 4) {
                    break;
                }
            }// end for
            for(i = 1; i <= INVADERS_PAIR_REPETITIONS; i++) {
                drawFrame((rom unsigned char *)&invaders[2]);
                Delay10KTCYx(DELAY_INVADERS);
                if(iMenu != 4) {
                    break;
                }
                drawFrame((rom unsigned char *)&invaders[3]);
                Delay10KTCYx(DELAY_INVADERS);
                if(iMenu != 4) {
                    break;
                }
            }// end for
            for(i = 1; i <= INVADERS_PAIR_REPETITIONS; i++) {
                drawFrame((rom unsigned char *)&invaders[4]);
                Delay10KTCYx(DELAY_INVADERS);
                if(iMenu != 4) {
                    break;
                }
                drawFrame((rom unsigned char *)&invaders[5]);
                Delay10KTCYx(DELAY_INVADERS);
                if(iMenu != 4) {
                    break;
                }
            }// end for

            break;


        /********************/
        /* 5- Party (Dirty) */
        /********************/
        case 5:
            if (SIXTH == 0) {
                deleteMatrix();
                drawLine(1,5,5,5,254);
            }
            for(j = 100, i = 254; j<=254; j++, i--) {
                drawSquare(1,1,5,5,j);
                drawSquare(2,2,4,4,i);
                drawPoint(3,3,j);
                if(iMenu != 5) {
                    break;
                }
            }
            if(iMenu != 5) {
                break;
            }
            for(j = 100, i = 254; j<=254; j++, i--) {
                drawSquare(1,1,5,5,i);
                drawSquare(2,2,4,4,j);
                drawPoint(3,3,i);
                if(iMenu != 5) {
                    break;
                }
            }

            if(iMenu != 5) {
                break;    // It allows to break the case during the executation
            }

            //SOLVES A BUG: because when TMR1F is called from this case, FIFTH is
            //reset but when we come back is set one because we are in case 4 not 1,
            if (iMenu == 5)(SIXTH = 1);
            break;

        default:
            drawPoint(3,3, 180);

        }// End switch iMenu
    }// End while

    CloseTimer0();
    CloseTimer1();
}//end main