KHMMParameters::~KHMMParameters()
{
    free_matrix(training_data.state_transitions);
}
Пример #2
0
/*======== void parse_file () ==========
	Inputs:   char * filename 
	struct matrix * transform, 
	struct matrix * pm,
	screen s
	Returns: 
	Goes through the file named filename and performs all of the actions listed in that file.
	The file follows the following format:
	Every command is a single character that takes up a line
	Any command that requires arguments must have those arguments in the second line.
	The commands are as follows:
	line: add a line to the edge matrix - 
	takes 6 arguemnts (x0, y0, z0, x1, y1, z1)
	circle: add a circle to the edge matrix - 
	takes 3 arguments (cx, cy, r)
	hermite: add a hermite curve to the edge matrix -
	takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3)
	bezier: add a bezier curve to the edge matrix -
	takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3)
	sphere: add a sphere to the edge matrix - 
	takes 3 arguemnts (cx, cy, r)
	torus: add a torus to the edge matrix - 
	takes 4 arguemnts (cx, cy, r1, r2)
	box: add a rectangular prism to the edge matrix - 
	takes 6 arguemnts (x, y, z, width, height, depth)
	clear: clear the currnt edge matrix -
	takes 0 arguments
	ident: set the transform matrix to the identity matrix - 
	scale: create a scale matrix, 
	then multiply the transform matrix by the scale matrix - 
	takes 3 arguments (sx, sy, sz)
	translate: create a translation matrix, 
	then multiply the transform matrix by the translation matrix - 
	takes 3 arguments (tx, ty, tz)
	xrotate: create an x-axis rotation matrix,
	then multiply the transform matrix by the rotation matrix -
	takes 1 argument (theta)
	yrotate: create an y-axis rotation matrix,
	then multiply the transform matrix by the rotation matrix -
	takes 1 argument (theta)
	zrotate: create an z-axis rotation matrix,
	then multiply the transform matrix by the rotation matrix -
	takes 1 argument (theta)
	apply: apply the current transformation matrix to the 
	edge matrix
	display: draw the lines of the edge matrix to the screen
	display the screen
	save: draw the lines of the edge matrix to the screen
	save the screen to a file -
	takes 1 argument (file name)
	quit: end parsing
	See the file script for an example of the file format
	IMPORTANT MATH NOTE:
	the trig functions int math.h use radian mesure, but us normal
	humans use degrees, so the file will contain degrees for rotations,
	be sure to conver those degrees to radians (M_PI is the constant
	for PI)
	====================*/
void parse_file ( char * filename, 
                  struct matrix * transform, 
                  struct matrix * pm,
                  screen s) {

  FILE *f;
  char line[256];
  struct matrix * tmp;
  double angle;
  color g;

  struct stack * origins = new_stack();
  struct matrix * tmp_poly = new_matrix(4,1);
  struct matrix * tmp_edges = new_matrix(4,1);

  g.red = 0;
  g.green = 255;
  g.blue = 0;
  
  clear_screen(s);

  if ( strcmp(filename, "stdin") == 0 ) 
    f = stdin;
  else
    f = fopen(filename, "r");
  
  while ( fgets(line, 255, f) != NULL ) {
    line[strlen(line)-1]='\0';
    //printf(":%s:\n",line);
    double x, y, z, x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4;
    if ( strncmp(line, "push", strlen(line)) == 0 ) {
      //fgets(line, 255, f);
      push(origins);
    }
    else if ( strncmp(line, "pop", strlen(line)) == 0 ) {
      //fgets(line, 255, f);
      pop(origins);
    }
    else if ( strncmp(line, "line", strlen(line)) == 0 ) {
      //      printf("LINE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &x1, &y1, &z1);
      add_edge(tmp_edges, x, y, z, x1, y1, z1);
      matrix_mult(origins->data[origins->top], tmp_edges);
      draw_lines(tmp_edges, s, g);
      ident(tmp_edges);
      // printf( "%lf %lf %lf %lf %lf %lf\n", x, y, z, x1, y1, z1);
    }
    else if ( strncmp(line, "circle", strlen(line)) == 0 ) {
      //printf("CIRCLE\n");
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      add_circle(tmp_edges, x, y, z, 0.01);
      matrix_mult(origins->data[origins->top], tmp_edges);
      draw_lines(tmp_edges, s, g);
      ident(tmp_edges);
      //printf( "%lf %lf %lf\n", x, y, z);
    }    
    else if ( strncmp(line, "bezier", strlen(line)) == 0 ) {
      //printf("BEZIER\n");
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf",
						 &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
      add_curve(tmp_edges, x1, y1, x2, y2, x3, y3, x4, y4, 0.01, BEZIER_MODE );
      matrix_mult(origins->data[origins->top],tmp_edges);
      draw_lines(tmp_edges,s,g);
      ident(tmp_edges);
      //printf( "%lf %lf %lf\n", x, y, z);
    }    
    else if ( strncmp(line, "hermite", strlen(line)) == 0 ) {
      //printf("HERMITE\n");
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf",
						 &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
      add_curve(tmp_edges, x1, y1, x2, y2, x3, y3, x4, y4, 0.01, HERMITE_MODE );
      matrix_mult(origins->data[origins->top],tmp_edges);
      draw_lines(tmp_edges,s,g);
      ident(tmp_edges);
      //printf( "%lf %lf %lf\n", x, y, z);
    }
    else if ( strncmp(line, "box", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &x1, &y1, &z1);
      add_box(tmp_poly, x, y, z, x1, y1, z1);
      matrix_mult(origins->data[origins->top], tmp_poly);
      draw_polygons(tmp_poly, s, g);
      ident(tmp_poly);
      // printf( "%lf %lf %lf %lf %lf %lf\n", x, y, z, x1, y1, z1);
    }
    else if (strncmp(line, "sphere", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      add_sphere(tmp_poly, x, y, z, 5);
      matrix_mult(origins->data[origins->top], tmp_poly);
      draw_polygons(tmp_poly, s, g);
      ident(tmp_poly);
      //printf( "%lf %lf %lf\n", x, y, z);
    }
    else if (strncmp(line, "torus", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf", &x, &y, &z, &z1);
      add_torus(tmp_poly, x, y, z, z1, 5);
      matrix_mult(origins->data[origins->top], tmp_poly);
      draw_polygons(tmp_poly, s, g);
      ident(tmp_poly);
      //printf( "%lf %lf %lf\n", x, y, z);
    }
    else if ( strncmp(line, "scale", strlen(line)) == 0 ) {
      //printf("SCALE\n");
      fgets(line, 255, f);
      //line[strlen(line)-1]='\0';      
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      tmp = make_scale(x, y, z);
      matrix_mult(origins->data[origins->top],tmp);
      copy_matrix(tmp,origins->data[origins->top]);
      //print_matrix(transform);
    }
    else if ( strncmp(line, "translate", strlen(line)) == 0 ) {
      //printf("TRANSLATE\n");
      fgets(line, 255, f);
      //      line[strlen(line)-1]='\0';      
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      tmp = make_translate(x, y, z);
      matrix_mult(origins->data[origins->top],tmp);
      copy_matrix(tmp,origins->data[origins->top]);
    }
    else if ( strncmp(line, "xrotate", strlen(line)) == 0 ) {
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotX( angle);
      matrix_mult(origins->data[origins->top],tmp);
      copy_matrix(tmp,origins->data[origins->top]);
    }
    else if ( strncmp(line, "yrotate", strlen(line)) == 0 ) {
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotY( angle);
      matrix_mult(origins->data[origins->top],tmp);
      copy_matrix(tmp,origins->data[origins->top]);
    }
    else if ( strncmp(line, "zrotate", strlen(line)) == 0 ) {
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotZ( angle);
      matrix_mult(origins->data[origins->top],tmp);
      copy_matrix(tmp,origins->data[origins->top]);
    }/*
			 else if ( strncmp(line, "ident", strlen(line)) == 0 ) {
			 ident(transform);
			 }
			 else if ( strncmp(line, "apply", strlen(line)) == 0 ) {
			 matrix_mult(transform, pm);
			 }*/
    else if ( strncmp(line, "display", strlen(line)) == 0 ) {
      //clear_screen(s);
      //draw_polygons(pm, s, g);
      display(s);
    }
    else if ( strncmp(line, "save", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      // line[strlen(line)-1] = '\0';
      //clear_screen(s);
      //draw_polygons(pm, s, g);
      save_extension(s, line);
    }
    else if ( strncmp(line, "clear", strlen(line)) == 0 ) {
      pm->lastcol = 0;
    }
    else if ( strncmp(line, "quit", strlen(line)) == 0 ) {
      return;
    }
    else if ( line[0] != '#' ) {
      printf("Invalid command\n");
    }
  }
  
  free_matrix(tmp);
  fclose(f);
  //printf("END PARSE\n");
}
Пример #3
0
gmx_bool mrqmin_new(real x[], real y[], real sig[], int ndata, real a[],
                    int ia[], int ma, real **covar, real **alpha, real *chisq,
                    void (*funcs)(real, real [], real *, real []),
                    real *alamda)
/* Levenberg-Marquardt method, attempting to reduce the value Chi^2
 * of a fit between a set of data points x[1..ndata], y[1..ndata]
 * with individual standard deviations sig[1..ndata], and a nonlinear
 * function dependent on ma coefficients a[1..ma]. The input array
 * ia[1..ma] indicates by nonzero entries those components of a that
 * should be fitted for, and by zero entries those components that
 * should be held fixed at their input values. The program returns
 * current best-fit values for the parameters a[1..ma], and
 * Chi^2 = chisq. The arrays covar[1..ma][1..ma], alpha[1..ma][1..ma]
 * are used as working space during most iterations. Supply a routine
 * funcs(x,a,yfit,dyda,ma) that evaluates the fitting function yfit,
 * and its derivatives dyda[1..ma] with respect to the fitting
 * parameters a at x. On the first call provide an initial guess for
 * the parameters a, and set alamda < 0 for initialization (which then
 * sets alamda=.001). If a step succeeds chisq becomes smaller and
 * alamda de-creases by a factor of 10. If a step fails alamda grows by
 * a factor of 10. You must call this routine repeatedly until
 * convergence is achieved. Then, make one final call with alamda=0,
 * so that covar[1..ma][1..ma] returns the covariance matrix, and alpha
 * the curvature matrix.
 * (Parameters held fixed will return zero covariances.)
 */
{
    void covsrt(real **covar, int ma, int ia[], int mfit);
    gmx_bool gaussj(real **a, int n, real **b, int m);
    void mrqcof_new(real x[], real y[], real sig[], int ndata, real a[],
                    int ia[], int ma, real **alpha, real beta[], real *chisq,
                    void (*funcs)(real, real [], real *, real []));
    int         j, k, l;
    static int  mfit;
    static real ochisq, *atry, *beta, *da, **oneda;

    if (*alamda < 0.0)                    /* Initialization. */
    {
        atry = rvector(1, ma);
        beta = rvector(1, ma);
        da   = rvector(1, ma);
        for (mfit = 0, j = 1; j <= ma; j++)
        {
            if (ia[j])
            {
                mfit++;
            }
        }
        oneda   = matrix1(1, mfit, 1, 1);
        *alamda = 0.001;
        mrqcof_new(x, y, sig, ndata, a, ia, ma, alpha, beta, chisq, funcs);
        ochisq = (*chisq);
        for (j = 1; j <= ma; j++)
        {
            atry[j] = a[j];
        }
    }
    for (j = 1; j <= mfit; j++) /* Alter linearized fitting matrix, by augmenting. */
    {
        for (k = 1; k <= mfit; k++)
        {
            covar[j][k] = alpha[j][k]; /* diagonal elements. */
        }
        covar[j][j] = alpha[j][j]*(1.0+(*alamda));
        oneda[j][1] = beta[j];
    }
    if (!gaussj(covar, mfit, oneda, 1)) /* Matrix solution. */
    {
        return FALSE;
    }
    for (j = 1; j <= mfit; j++)
    {
        da[j] = oneda[j][1];
    }
    if (*alamda == 0.0) /* Once converged, evaluate covariance matrix. */
    {
        covsrt_new(covar, ma, ia, mfit);
        free_matrix(oneda, 1, mfit, 1);
        free_vector(da, 1);
        free_vector(beta, 1);
        free_vector(atry, 1);
        return TRUE;
    }
    for (j = 0, l = 1; l <= ma; l++) /* Did the trial succeed? */
    {
        if (ia[l])
        {
            atry[l] = a[l]+da[++j];
        }
    }
    mrqcof_new(x, y, sig, ndata, atry, ia, ma, covar, da, chisq, funcs);
    if (*chisq < ochisq)
    {
        /* Success, accept the new solution. */
        *alamda *= 0.1;
        ochisq   = (*chisq);
        for (j = 1; j <= mfit; j++)
        {
            for (k = 1; k <= mfit; k++)
            {
                alpha[j][k] = covar[j][k];
            }
            beta[j] = da[j];
        }
        for (l = 1; l <= ma; l++)
        {
            a[l] = atry[l];
        }
    }
    else                 /* Failure, increase alamda and return. */
    {
        *alamda *= 10.0;
        *chisq   = ochisq;
    }
    return TRUE;
}
Пример #4
0
void main(int argc, char **argv) {
    // ***** DECLARATION *****//
    int dim = 4;
    double *vstart, *spkTimes;;
    double x1 = 0, // simulation start time
      x2 = 100, // simulation end time
      thetaStep = 0;
    int nSteps, nThetaSteps;
    FILE *fp;
    int kNeuron, clmNo, loopIdx=0;
    long idem;
    // ***** INITIALIZATION *****//
    dt = DT;
    nSteps = (int)((x2 - x1) / dt);
    xx = vector(1, nSteps);
    y = matrix(1, N_StateVars * N_Neurons, 1, nSteps);
    input_cur = vector(1, nSteps);
    vstart = vector(1, N_StateVars * N_Neurons);
    IF_SPK = vector(1, N_Neurons);   
    expSum = vector(1, N_Neurons); // synap input
    iSynap = vector(1, N_Neurons); 
    gEE = vector(1, NE);   
    gEI = vector(1, NE);   
    gIE = vector(1, NI);   
    gII = vector(1, NI);
    spkTimes = vector(1, nSteps);
    conMat = matrix(1, N_Neurons, 1, N_Neurons);
    gaussNoiseE = vector(1, NE);
    gaussNoiseI = vector(1, NI);
    iBg = vector(1, N_Neurons);
    gFF = vector(1, N_Neurons);
    iFF = vector(1, N_Neurons);
    rTotal = vector(1, N_Neurons);
    rTotalPrev = vector(1, N_Neurons);
    tempRandnPrev = vector(1, N_Neurons);
    tempRandnNew = vector(1, N_Neurons);
    tempCurE = vector(1, N_Neurons);
    tempCurI = vector(1, N_Neurons);
    Itgrl = vector(1, N_Neurons);
    ItgrlOld = vector(1, N_Neurons);
    randnXiA = vector(1, N_Neurons);
    randwZiA = matrix(1, N_Neurons, 1, 4);
    randuDelta = vector(1, N_Neurons);
    randuPhi = matrix(1, N_Neurons, 1, 3);
    spkTimesFp = fopen("/home/shrisha/Documents/cnrs/results/network_model_outFiles/spkTimes","w");
    outVars = fopen("/home/shrisha/Documents/cnrs/results/network_model_outFiles/outvars", "w");
    isynapFP = fopen("/home/shrisha/Documents/cnrs/results/network_model_outFiles/isynapEI", "w");
    rTotalFP = fopen("/home/shrisha/Documents/cnrs/results/network_model_outFiles/rTotal", "w");
    gbgrndFP = fopen("/home/shrisha/Documents/cnrs/results/network_model_outFiles/gBg", "w");
    srand(time(NULL)); // set the seed for random number generator
    //    genConMat(); // Generate conection matrix
    GenConMat02();
    AuxRffTotal(); /* auxillary function, generates random variables for the 
                      simulation run; which are used approximating FF input */
    if(thetaStep > 0) {
      thetaVec = vector(1, 360 / thetaStep);
      LinSpace(0, 360, thetaStep, thetaVec, &nThetaSteps); 
    }
    else {
      thetaVec = vector(1, 1);
      thetaVec[1] = 0;
      nThetaSteps = 1;
    }
    printf("theta = %f %d\n", thetaVec[1], nThetaSteps);
    /* /\********\/ */
    //conMat[1][1] = 0; 
    //    conMat[1][2] = 1; 
    //for(loopIdx = 3; loopIdx <=N_Neurons; ++loopIdx) {
    //conMat[loopIdx][2] = 1;
    //    }
    // conMat[1][3] = 1; */
    //    conMat[2][1] = 0; 
    //conMat[2][2] = 0; 
    /* conMat[2][3] = 1; */
    /* conMat[3][1] = 1; */
    /* conMat[3][2] = 0; */
    /* conMat[3][3] = 0; */
    // compute
    printf("\nNE = %d\n", NE);
    printf("\nNI = %d\n", NI);
    printf("\nK = %d\n", (int)K);
    printf("computing...\n");
    //***** PARSE INPUT ARGS *****//
    if(argc > 1) {
      theta = atof(argv[2]);
      contrast = atof(argv[3]);
      muE = atof(argv[4]);
      muI = atof(argv[5]);
      // current pulse - tStart, tStop, stepSize
      for(loopIdx = 1; loopIdx < nSteps+1;  ++loopIdx) {
        if(loopIdx * dt > atof(argv[6]) && loopIdx *dt <= atof(argv[7])) { 
          input_cur[loopIdx] = atof(argv[8]); 
        }
        else { 
          input_cur[loopIdx] = 0;
        }
      }
    }
    else {
      theta = 0;
      contrast = 0.25;
      muE = 0.1;
      muI = 0.1;
      for(loopIdx =1; loopIdx < nSteps+1;  ++loopIdx) {
        input_cur[loopIdx] = 0; 
      }
    }
    //***** INITIALIZE STATE VARIABLES *****//
    for(kNeuron = 1; kNeuron < N_Neurons + 1; ++kNeuron) {
      clmNo =  (kNeuron - 1) * N_StateVars;
      idem = -1 * rand();
      vstart[1 + clmNo] = -70 +  40 * ran1(&idem); // Vm(0) ~ U(-70, -30)
      vstart[2 + clmNo] = 0.3176;
      vstart[3 + clmNo] = 0.1;
      vstart[4 + clmNo] = 0.5961;
    }
    //***** INTEGRATE *****//
    for(loopIdx = 1; loopIdx <= nThetaSteps; ++loopIdx) {
      theta = thetaVec[loopIdx];
      fprintf(spkTimesFp, "%f %f\n", theta, theta);
      rkdumb(vstart, N_StateVars * N_Neurons, x1, x2, nSteps, derivs);
      fprintf(spkTimesFp, "%d %d\n", 11, 11); // delimiters for thetas 
      fprintf(spkTimesFp, "%d %d\n", 73, 73);
    }
    printf("Done! \n");
    fclose(spkTimesFp);
    //***** SAVE TO DISK *****//
    fp = fopen("/home/shrisha/Documents/cnrs/results/network_model_outFiles/outputFile.csv", "w");
    for(loopIdx = 1; loopIdx < nSteps+1; ++loopIdx) {
      fprintf(fp, "%f ", xx[loopIdx]);
      for(kNeuron = 1; kNeuron < N_Neurons + 1; ++kNeuron) {
        clmNo =  (kNeuron - 1) * N_StateVars;
        // y = [t, V_m, n, z, h, I_input]
	  //	  fprintf(fp, "%f %f %f %f %f ", y[1 + clmNo][loopIdx], y[2 + clmNo][loopIdx], y[3 + clmNo][loopIdx], y[4 + clmNo][loopIdx], input_cur[loopIdx]);
	  fprintf(fp, "%f ", y[1 + clmNo][loopIdx]);
      }
       fprintf(fp, "\n");
       if(loopIdx%100 == 0) {
         printf("\r%d", loopIdx);
       }
      }
    printf("\n");
    printf("nSteps = %d \n", loopIdx);
    
    fclose(fp);
    fclose(outVars);
    fclose(isynapFP);
    fclose(rTotalFP);
    fclose(gbgrndFP);
    //***** FREE MEMORY *****//
    free_vector(expSum, 1, N_Neurons);
    free_vector(iSynap, 1, N_Neurons); 
    free_vector(gEE, 1, NE);   
    free_vector(gIE, 1, NI);   
    free_vector(gEI, 1, NE);   
    free_vector(gII, 1, NI);   
    free_vector( gaussNoiseE, 1, NE);
    free_vector(gaussNoiseI, 1, NI);
    free_vector(rTotal, 1, N_Neurons);
    free_vector(rTotalPrev, 1, N_Neurons);
    free_vector(tempRandnPrev, 1, N_Neurons);
    free_vector(tempRandnNew, 1, N_Neurons);
    free_vector(iBg, 1, N_Neurons);
    free_vector(gFF, 1, N_Neurons);
    free_vector(iFF, 1, N_Neurons);
    free_vector(tempCurI, 1, N_Neurons);
    free_vector(tempCurE, 1, N_Neurons);
    free_matrix(conMat, 1, N_Neurons, 1, N_Neurons);
    free_matrix(randwZiA, 1, N_Neurons, 1, 4);
    free_matrix(randuPhi, 1, N_Neurons, 1, 3);
}
Пример #5
0
Файл: main.c Проект: dxhunter/GC
int main (int argc, char* argv[]) {

	int n;
	double *b;					
	Cel *A = NULL;
	FILE *input;
	char opt;

 	/* Tratamento da entrada */
	if(argc < 2) {
		error(NO_OPTION);
	}
	else {
		opt = argv[1][0];
		switch(opt) {
			case '1':
				n = MATRIX_TEST_SIZE;
				A = malloc_matrix(n);
				b = malloc_vector(n);
				build_test_matrix(A,0.01,n);
				build_test_vector(b,n);
				conjugate_gradient(A,b,n);
				free_matrix(n,A);
				free(b);
				break;
			case '2':
				n = MATRIX_TEST_SIZE;
				A = malloc_matrix(n);
				b = malloc_vector(n);
				build_test_matrix(A,0.05,n);
				build_test_vector(b,n);
				conjugate_gradient(A,b,n);
				free_matrix(n,A);
				free(b);
				break;
			case '3':
				n = MATRIX_TEST_SIZE;
				A = malloc_matrix(n);
				b = malloc_vector(n);
				build_test_matrix(A,0.1,n);
				build_test_vector(b,n);
				conjugate_gradient(A,b,n);
				free_matrix(n,A);
				free(b);
				break;
			case '4':
				n = MATRIX_TEST_SIZE;
				A = malloc_matrix(n);
				b = malloc_vector(n);
				build_test_matrix(A,0.3,n);
				build_test_vector(b,n);
				conjugate_gradient(A,b,n);
				free_matrix(n,A);
				free(b);
				break;
			case 'r':
				if(argc < 3) error(NO_FILE);
				else {
					input = fopen(argv[2],"r");
					if(input == NULL) error(OPENING_FILE);
					n = read_dimension(input);
					A = malloc_matrix(n);
					b = malloc_vector(n);
					read_matrix_system(input,n,A,b);
					fclose(input);
					conjugate_gradient(A,b,n);
					free_matrix(n,A);
					print_vector(n,b);
					free(b);
					break;
				}
			default:
				printf("Opcao nao reconhecida\n");
				exit(EXIT_FAILURE);
		}
	}
	return 1;
}
Пример #6
0
void free_floatmatrix( FLOATMATRIX *m)





{


		


		   if(m==NULL || m->co==NULL){


		  


		  		t_error("This matrix was never allocated");


		  	


		   }else if(m->isdynamic==1){





			free_matrix(m->co,NL,NL);


			


			m->isdynamic=m->nrl=m->ncl=m->nrh=m->nch=-1;


			


			free(m);





			return;


		  


		  }else{


			printf("\nWarning::An attemp was made to free a non dynamic matrix\n");


		  }


}
int main(int argc, char *argv[]) {
	//SETUP CODE
        int i,j,ii,jj, istart,iend,jstart, jend;
	double **A;
	double t1,t2;
	int numthreads,tid;

        #pragma omp parallel
        {
                numthreads = omp_get_num_threads();
                tid = omp_get_thread_num();
                if(tid==0)
                        printf("Running transpose with %d threads\n",numthreads);
        }

	A = create_matrix();

        /* Creating matrix B which will contained the transposed version of A */
	double** B = (double**) malloc(sizeof(double*)*n);
	for (i=0;i<n;i++) {
		B[i] = (double*) malloc(sizeof(double)*n);
	}
       
        int bsize = 32, r; 
        int loop_unroll_limit = 6;

        printf("Working with bsize = %d\t", bsize);

        for(loop_unroll_limit = 1 ; loop_unroll_limit < 100 ; loop_unroll_limit ++) {
            printf("Working with loop_unroll_limit = %d\t",loop_unroll_limit);

	    t1 = get_clock();

	    //BEGIN MAIN ROUTINE
            for (ii = 0; ii<n; ii+=bsize) {
              istart = ii ; iend = MIN(ii+bsize, n);
              for (jj = 0; jj<n; jj+=bsize) {
                jstart = jj ; jend = MIN(jj+bsize, n);

                /* For each block, execute the remainder loop sequentially
                ** without using loop unroll
                */
                int remainder = MIN(bsize, n - istart)%loop_unroll_limit;
                for (r = istart ; r < istart + remainder ; r ++) {
                  for(j = jstart ; j < jend; j ++) {
                    B[r][j] = A[j][r];
                  }
                } 
	        for(i = r;i < iend; i = i + loop_unroll_limit) {
		  for(j=jstart ;j < jend;j++) {
                        int h;
                        for(h = 0 ; h < loop_unroll_limit; h++) {
			B[i  + h][j] = A[j][i  +  h];
                        }
	          }
                }
	      }
            }
	//END MAIN ROUTINE

	    t2 = get_clock();
	    printf("Time: %lf\n",(t2-t1));
}

	if(SAVE) {
                // Output Result
                char outfile[100];
                sprintf(outfile,"transpose_out_%d.txt",numthreads);
                printf("Outputting solution to %s\n",outfile);
                FILE *fp = fopen(outfile,"w");
                for(i=0; i<n; i++) {
			for(j=0; j<n; j++) {
                        	fprintf(fp,"%lf\n",B[i][j]);
			}
		}
                fclose(fp);
        }

	//CLEANUP CODE
	free_matrix(A);
	return 0;

}
Пример #8
0
int
main(void)
{
    int plot;
    int i, j;
    float x, y;
    float *rt, *ct;
    float **m;
    int xsize, ysize;
    char buf[256];
    FILE *fout;
/*  Create a few standard test interfaces */

    for (plot = 0; plot < NUM_PLOTS; plot++) {
	xsize = (TheRange[plot].xmax - TheRange[plot].xmin) * ISOSAMPLES + 1;
	ysize = (TheRange[plot].ymax - TheRange[plot].ymin) * ISOSAMPLES + 1;

	rt = alloc_vector(0, xsize - 1);
	ct = alloc_vector(0, ysize - 1);
	m = matrix(0, xsize - 1, 0, ysize - 1);

	for (y = TheRange[plot].ymin, j = 0; j < ysize; j++, y += 1.0 / (double) ISOSAMPLES) {
	    ct[j] = y;
	}

	for (x = TheRange[plot].xmin, i = 0; i < xsize; i++, x += 1.0 / (double) ISOSAMPLES) {
	    rt[i] = x;
	    for (y = TheRange[plot].ymin, j = 0; j < ysize; j++, y += 1.0 / (double) ISOSAMPLES) {
		m[i][j] = function(plot, x, y);
	    }
	}

	sprintf(buf, "binary%d", plot + 1);
	if (!(fout = fopen(buf, "wb")))
	    int_error(0, "Could not open file");
	else {
	    fwrite_matrix(fout, m, 0, xsize - 1, 0, ysize - 1, rt, ct);
	}
	free_vector(rt, 0);
	free_vector(ct, 0);
	free_matrix(m, 0, xsize - 1, 0);
    }

    /* Show that it's ok to vary sampling rate, as long as x1<x2, y1<y2... */
    xsize = (TheRange[plot].xmax - TheRange[plot].xmin) * ISOSAMPLES + 1;
    ysize = (TheRange[plot].ymax - TheRange[plot].ymin) * ISOSAMPLES + 1;

    rt = alloc_vector(0, xsize - 1);
    ct = alloc_vector(0, ysize - 1);
    m = matrix(0, xsize - 1, 0, ysize - 1);

    for (y = TheRange[plot].ymin, j = 0; j < ysize; j++, y += 1.0 / (double) ISOSAMPLES) {
	ct[j] = y > 0 ? 2 * y : y;
    }
    for (x = TheRange[plot].xmin, i = 0; i < xsize; i++, x += 1.0 / (double) ISOSAMPLES) {
	rt[i] = x > 0 ? 2 * x : x;
	for (y = TheRange[plot].ymin, j = 0; j < ysize; j++, y += 1.0 / (double) ISOSAMPLES) {
	    m[i][j] = function(plot, x, y);
	}
    }

    sprintf(buf, "binary%d", plot + 1);
    if (!(fout = fopen(buf, "wb")))
	int_error(0, "Could not open file");
    else {
	fwrite_matrix(fout, m, 0, xsize - 1, 0, ysize - 1, rt, ct);
    }
    free_vector(rt, 0);
    free_vector(ct, 0);
    free_matrix(m, 0, xsize - 1, 0);

    return EXIT_SUCCESS;
}
Пример #9
0
int main(void)  /* Program sfroid */
{
	float plgndr(int l, int m, float x);
	void solvde(int itmax, float conv, float slowc, float scalv[],
		int indexv[], int ne, int nb, int m, float **y, float ***c, float **s);
	int i,itmax,k,indexv[NE+1];
	float conv,deriv,fac1,fac2,q1,slowc,scalv[NE+1];
	float **y,**s,***c;

	y=matrix(1,NYJ,1,NYK);
	s=matrix(1,NSI,1,NSJ);
	c=f3tensor(1,NCI,1,NCJ,1,NCK);
	itmax=100;
	conv=5.0e-6;
	slowc=1.0;
	h=1.0/(M-1);
	printf("\nenter m n\n");
	scanf("%d %d",&mm,&n);
	if (n+mm & 1) {
		indexv[1]=1;
		indexv[2]=2;
		indexv[3]=3;
	} else {
		indexv[1]=2;
		indexv[2]=1;
		indexv[3]=3;
	}
	anorm=1.0;
	if (mm) {
		q1=n;
		for (i=1;i<=mm;i++) anorm = -0.5*anorm*(n+i)*(q1--/i);
	}
	for (k=1;k<=(M-1);k++) {
		x[k]=(k-1)*h;
		fac1=1.0-x[k]*x[k];
		fac2=exp((-mm/2.0)*log(fac1));
		y[1][k]=plgndr(n,mm,x[k])*fac2;
		deriv = -((n-mm+1)*plgndr(n+1,mm,x[k])-
			(n+1)*x[k]*plgndr(n,mm,x[k]))/fac1;
		y[2][k]=mm*x[k]*y[1][k]/fac1+deriv*fac2;
		y[3][k]=n*(n+1)-mm*(mm+1);
	}
	x[M]=1.0;
	y[1][M]=anorm;
	y[3][M]=n*(n+1)-mm*(mm+1);
	y[2][M]=(y[3][M]-c2)*y[1][M]/(2.0*(mm+1.0));
	scalv[1]=fabs(anorm);
	scalv[2]=(y[2][M] > scalv[1] ? y[2][M] : scalv[1]);
	scalv[3]=(y[3][M] > 1.0 ? y[3][M] : 1.0);
	for (;;) {
		printf("\nEnter c**2 or 999 to end.\n");
		scanf("%f",&c2);
		if (c2 == 999) {
			free_f3tensor(c,1,NCI,1,NCJ,1,NCK);
			free_matrix(s,1,NSI,1,NSJ);
			free_matrix(y,1,NYJ,1,NYK);
			return 0;
		}
		solvde(itmax,conv,slowc,scalv,indexv,NE,NB,M,y,c,s);
		printf("\n %s %2d %s %2d %s %7.3f %s %10.6f\n",
			"m =",mm,"  n =",n,"  c**2 =",c2,
			" lamda =",y[3][1]+mm*(mm+1));
	}
}
Пример #10
0
/* This routine computes standard and nonstandard earthquake location 
error estimates.  standard error estimate returned is the covariance 
matrix of the predicted errors that can be used to derive standard
error ellipses.  The covariance that is returned is unscaled.  It is the
true covariance only when the weights are ideal 1/sigma weighting.
(Note residual (robust) weighting does not really alter this as the goal
of residual weighting is to downweight outliers and reshape the residual
distribution to be closer to a normal disltribution.  

The nonstandard error that is returned is the "model error" defined
in Pavlis (1986) BSSA, 76, 1699-1717.  

It would be preferable in some ways to split these into two modules, but
it is more efficient to compute them together.

Arguments:
-input-
h - hypocenter location of point to appraise errors from
attbl- Associate array of Arrival structures
utbl - associate array of slowness structures
o- Location options structure 
-output-
C - 4x4 covariance matrix.  Assumed allocated externally and 
passed here.  alloc with modified numerical recipes "matrix" routine.
emodel - 4 vector of x,y,z model error estimates 

Both error estimates have 0 in positions where fix is set.  

Returns 0 if no problems are encountered.  Nonzero return
indicates a problem.  

+1 - Inverse matrix was singular to machine precision, error results
	are unreliable as svd truncation was need to stabilize 
	calculations.


Author:  Gary L. Pavlis
Written:  June 25, 1998
*/
void predicted_errors(Hypocenter h, 
	Tbl *attbl, Tbl *utbl,
	Location_options o,
	double **C, float *emodel)
{
        Arrival *atimes;
	Slowness_vector *slow;
	int natimes;
	int nslow;
	int npar, nused, ndata_feq;

	float **U, **V, s[4];  /* SVD of A = USVT */
	float **Agi;  /* holds computed generalized inverse */
	float *b;  /* weighted residual vector (rhs of Ax=b)*/
	float *r,*w;  /* r=raw residual and w= vector of total weights */
	float *reswt;  /* we store residual weights seperately to calculate
			effective degrees of freedom */
	int m;  /* total number of data points = natimes+2*nslow */
	Robust_statistics statistics;
	int mode;
	int i,ii,j;

	/* because o is a dynamic variable, we force the
	plain pseudoinverse soltuion */
	o.generalized_inverse = PSEUDOINVERSE;

	natimes = maxtbl(attbl);
	nslow = maxtbl(utbl);

	m = 2*nslow + natimes;
	for(i=0,npar=0;i<4;++i)
		if(!o.fix[i]) ++npar; 

	Agi = matrix(0,3,0,m-1);
	U = matrix(0,m-1,0,3);
	V = matrix(0,3,0,3);


	b=(float *)calloc(m,sizeof(float));
	r=(float *)calloc(m,sizeof(float));
	w=(float *)calloc(m,sizeof(float));
	reswt=(float *)calloc(m,sizeof(float));

	if ( (b==NULL) || (r==NULL)
		|| (w==NULL) || (reswt==NULL) )
		elog_die(1,"Alloc errors in location error function\n");

	statistics = form_equations(ALL, h, attbl,utbl,
			o, U, b, r, w, reswt,&ndata_feq);
	svdcmp(U,m,npar,s,V);
	/* This computes the generalized inverse as the pseudoinverse.
	This version forces this to be the true pseudoinverse no
	matter what the user selected as a location option.  This is
	my (glp) prejudice that reporting anything else is a lie.*/

	nused = pseudoinverse(U,s,V,m,npar,Agi);
	if(nused != npar ) 
	{
		elog_log(0,"predicted_errors function found system of equations was singular, Errors estimates are unreliable\n");
	}
	compute_covariance(Agi,m,npar,4,C,o.fix);

	/* Now we compute the emodel vector defined in 
	 Pavlis (1986) BSSA, 76, 1699-1717. A complication is that
	we need to do a complex rescan of the arrival and slowness
	data tables.  This is necessary to allow different 
	bounding terms for different phases and to obtain most
	easily the computed travel time to each stations.  
	We just recompute the travel times and use an associated
	scale factor.  For slowness we just enter a fixed value
	under and assumption slowness errors do not increase 
	with distance as travel times tend to do. */
	mode = RESIDUALS_ONLY;
	for(i=0;i<natimes;++i)
        {
                Travel_Time_Function_Output tto;
                atimes = (Arrival *) gettbl(attbl,i);
                tto = calculate_travel_time(*atimes, h,mode);
                if(tto.time == TIME_INVALID)
			b[i] = 0.0;
		else
		{
			b[i] = tto.time;
			b[i] *= w[i]*reswt[i]*atimes->phase->deltat_bound;
		}
	}
	for(i=0,j=natimes;i<nslow;++i,j+=2)
        {
                slow = (Slowness_vector *) gettbl(utbl,i);
		b[j] = slow->phase->deltau_bound;
		b[j+1]=b[j];
	}
	/* we recycle w here blindly assuming m>n */
	compute_emodel(Agi, m, npar, b, w);
	for(i=0,ii=0;i<4;++i)
		if(o.fix[i])
			emodel[i] = 0.0;
		else
		{
			emodel[i] = b[ii];
			++ii;
		}
        free_matrix((char **)Agi,0,3,0);
        free_matrix((char **)U,0,m-1,0);
        free_matrix((char **)V,0,3,0);
        free(b);
        free(r);
        free(w);
        free(reswt);
}
Пример #11
0
/*
 * Returns maximal element of m1 * m2.
 */
struct elem_pos_t* max_res_elem(struct matrix_t* m1, struct matrix_t* m2) {
    msize_t row, col;
    elem_t* restrict res;

    msize_t max_row, max_col;
    elem_t max_res;

#ifndef NDEBUG
    max_row = max_col = -1;
#endif
    max_res = MIN_ELEM;

#ifndef NDEBUG
    print_matrix(m1);
    print_matrix(m2);
#endif

    assert (m1->n_cols == m2->n_rows);

    /* Optimize for cache misses */
    if ((m2 = transpose(m2)) == NULL) {
	return NULL;
    }

    if ((res = (elem_t*) _mm_malloc(sizeof(elem_t) * m1->n_rows * m2->n_rows, ELEM_ALIGN)) == NULL) {
	return NULL;
    }

    {
        msize_t m1_nrows, m2_nrows, m1_ncols;
        m1_nrows = m1->n_rows;
        m2_nrows = m2->n_rows;
        m1_ncols = m1->n_cols;

        /* no dependencies between iterations */
        #pragma parallel
        for (row = 0; row < m1_nrows; row++) {
            #pragma parallel
            for (col = 0; col < m2_nrows; col++) {
                res[row * m2_nrows + col] = 
                            mult_vect(m1->data[row], m2->data[col], m1_ncols);
            }
        }
    

	for (row = 0; row < m1_nrows; row++) {
            for (col = 0; col < m2_nrows; col++) {
		if (res[row * m2_nrows + col] > max_res) {
	            max_res = res[row * m2_nrows + col];
		    max_row = row;
		    max_col = col;
    	        }
            }
        }
    }
    free_matrix(m2);
    _mm_free(res);

    assert ((max_row >= 0) && (max_col >= 0));
    return elem_pos(max_row, max_col, max_res);
}
Пример #12
0
int main(void){
    
    
    int NC, NR,NC2,i,j,ii,jj;
    double **A,**B,**C,**D,**E,**F,**G,**H,**I,t1,t2,t3,t4,t5,t6,f;
    clock_t start1,start2,start3,start4,start5,start6;
    clock_t end1,end2,end3,end4,end5,end6;
    
    printf("Enter NR, NC, NC2 and entries of 1st matrix:\n");
    scanf("%d %d %d\n", &NR, &NC, &NC2);
    A=make_matrix(NR,NC);
    
    for(i=1;i<=NR;i++){
        for(j=1;j<=NC;j++){
            scanf("%lf",&A[i][j]);
        }
    }
    print_matrix(A,NR,NC);
    printf("Enter entries of 2nd matrix:\n");
    B=make_matrix(NC,NC2);
    
    for(ii=1;ii<=NC;ii++){
        for(jj=1;jj<=NC2;jj++){
            scanf("%lf",&B[ii][jj]);
        }
    }
    
    
    print_matrix(B,NC,NC2);
    
    //C=make_random_matrix(NR,NR);
    //print_matrix(C,NR,NR);
    
    start1=clock();
    D=mymatmul1(A,B,NR,NC,NC2);
    printf("Mymatmul1:\n");
    print_matrix(D,NR,NC2);
    end1 = clock();
    
    start2=clock();
    E=mymatmul2(A,B,NR,NC,NC2);
    printf("Mymatmul2:\n");
    print_matrix(E,NR,NC2);
    end2 = clock();
    
    
    start3=clock();
    F=mymatmul3(A,B,NR,NC,NC2);
    printf("Mymatmul3\n");
    print_matrix(F,NR,NC2);
    end3 = clock();
    
    start4=clock();
    G=mymatmul4(A,B,NR,NC,NC2);
    printf("Mymatmul4\n");
    print_matrix(G,NR,NC2);
    end4 = clock();
    
    start5=clock();
    H=mymatmul5(A,B,NR,NC,NC2);
    printf("Mymatmul5\n");
    print_matrix(H,NR,NC2);
    end5 = clock();
    
    start6=clock();
    I=mymatmul6(A,B,NR,NC,NC2);
    printf("Mymatmul6\n");
    print_matrix(I,NR,NC2);
    end6 = clock();
    
    
    
    free_matrix(A);free_matrix(B);
    free_matrix(D);
    free_matrix(E);
    free_matrix(F);
    free_matrix(G);
    free_matrix(H);
    free_matrix(I);

    
    
    /*
    t1=(double)(end1 - start1);
    t2=(double)(end2 - start2);
    t3=(double)(end3 - start3);
    t4=(double)(end4 - start4);
    t5=(double)(end5 - start5);
    t6=(double)(end6 - start6);
    f=NC*NR*(NC+(NC-1));
    
    printf("t1= %f\n",t1);
    printf("t2= %f\n",t2);
    printf("t3= %f\n",t3);
    printf("t4= %f\n",t4);
    printf("t5= %f\n",t5);
    printf("t6= %f\n",t6);
    
    
    //printf("%e\n \n",f/(t*1000000000));*/
    exit(0);
    
}
Пример #13
0
/*======== void my_main() ==========
  Inputs:   int polygons  
  Returns: 
  This is the main engine of the interpreter, it should
  handle most of the commadns in mdl.
  If frames is not present in the source (and therefore 
  num_frames is 1, then process_knobs should be called.
  If frames is present, the enitre op array must be
  applied frames time. At the end of each frame iteration
  save the current screen to a file named the
  provided basename plus a numeric string such that the
  files will be listed in order, then clear the screen and
  reset any other data structures that need it.
  Important note: you cannot just name your files in 
  regular sequence, like pic0, pic1, pic2, pic3... if that
  is done, then pic1, pic10, pic11... will come before pic2
  and so on. In order to keep things clear, add leading 0s
  to the numeric portion of the name. If you use sprintf, 
  you can use "%0xd" for this purpose. It will add at most
  x 0s in front of a number, if needed, so if used correctly,
  and x = 4, you would get numbers like 0001, 0002, 0011,
  0487
  05/17/12 09:41:35
  jdyrlandweaver
  ====================*/
void my_main( int polygons ) {

  int red,green,blue;
  double vx,vy,vz;
  vx = 0;
  vy = 0;
  vz = -1;
  int i, f, j;
  double* vector;
  double step;
  double xval, yval, zval, knob_value;
  struct matrix *transform;
  struct matrix *tmp;
  struct matrix *zbuffer = new_Zmatrix(XRES,YRES);
  //print_matrix(zbuffer);
  struct stack *s;
  screen t;
  color g;
  struct light* light=(struct light*)malloc(sizeof(struct light));
  light->l[0]=0;light->l[1]=0;light->l[2]=0;
  light->c[0]=0;light->c[0]=0;light->c[0]=0;
  light->next=NULL;
  struct light* cur_light;

  int ind;
  struct constants* constants=(struct constants*)malloc(sizeof(struct constants));
  constants->red=1.0;constants->blue=1.0;constants->green=1.0;
  struct vary_node **knobs;
  struct vary_node *vn;
  char frame_name[128];

  num_frames = 1;
  step = 5;
 
  g.red = 0;
  g.green = 0;
  g.blue = 0;


  first_pass();

  if (num_frames == 1)
    process_knobs();
  else
    knobs = second_pass();

  for (i=0;i<lastop;i++) {
    switch (op[i].opcode) {
    case LIGHT:
      cur_light = light;
      for (;cur_light->next!=NULL;cur_light=cur_light->next){}
      cur_light->next=lookup_symbol(op[i].op.light.p->name)->s.l;
      break;
    case AMBIENT:
      g.red += op[i].op.ambient.c[0];
      g.green += op[i].op.ambient.c[1];
      g.blue += op[i].op.ambient.c[2];
      break;      
    }
  }
  
  for ( f=0; f < num_frames; f++ ) {

    s = new_stack();
    tmp = new_matrix(4, 1000);
    clear_screen( t );

    //if there are multiple frames, set the knobs
    if ( num_frames > 1 ) {
      
      vn = knobs[f];
      while ( vn ) {
	printf("knob: %s value:%lf\n", vn->name, vn->value);
	set_value( lookup_symbol( vn->name ), vn->value );
	vn = vn-> next;
      }
    }
    
    for (i=0;i<lastop;i++) {
      switch (op[i].opcode) {

      case SET:
	set_value( lookup_symbol( op[i].op.set.p->name ), 
		   op[i].op.set.p->s.value );
	break;
	
      case SETKNOBS:
	for ( j=0; j < lastsym; j++ ) 
	  if ( symtab[j].type == SYM_VALUE )
	    symtab[j].s.value = op[i].op.setknobs.value;
	break;
	
      case CONSTANTS:
	//constants=lookup_symbol(op[i].op.constants.p->name)->s.c;
	break;
	/*
      case LIGHT:
	cur_light = light;
	for (;light->next!=NULL;light=light->next){}
	light->next=lookup_symbol(op[i].op.light.p->name)->s.l;
	break;
	*/
      case CAMERA:
	vx = op[i].op.camera.eye[0] - op[i].op.camera.aim[0];
	vy = op[i].op.camera.eye[1] - op[i].op.camera.aim[1];
	vz = op[i].op.camera.eye[2] - op[i].op.camera.aim[2];
	vector = normalize(vx,vy,vz);
	vx = vector[0];
	vy = vector[1];
	vz = vector[2];
	break;
      case SPHERE:
	add_sphere( tmp,op[i].op.sphere.d[0], //cx
		    op[i].op.sphere.d[1],  //cy
		    op[i].op.sphere.d[2],  //cz
		    op[i].op.sphere.r,
		    step);
	//apply the current top origin
	matrix_mult( s->data[ s->top ], tmp );
	Zdraw_polygons( tmp, t, g ,zbuffer, light, constants,vx,vy,vz);
	tmp->lastcol = 0;
	//printf("%s\n","drawing sphere");
	break;

      case TORUS:
	add_torus( tmp, op[i].op.torus.d[0], //cx
		   op[i].op.torus.d[1],     //cy
		   op[i].op.torus.d[2],    //cz
		   op[i].op.torus.r0,
		   op[i].op.torus.r1,
		   step);
	matrix_mult( s->data[ s->top ], tmp );
	Zdraw_polygons( tmp, t, g ,zbuffer, light, constants,vx,vy,vz);
	tmp->lastcol = 0;
	printf("%s\n","drawing torus");
	break;

      case BOX:
	add_box( tmp, op[i].op.box.d0[0],
		 op[i].op.box.d0[1],
		 op[i].op.box.d0[2],
		 op[i].op.box.d1[0],
		 op[i].op.box.d1[1],
		 op[i].op.box.d1[2]);
	matrix_mult( s->data[ s->top ], tmp );
	Zdraw_polygons( tmp, t, g ,zbuffer,light, constants,vx,vy,vz);
	tmp->lastcol = 0;
	printf("%s\n","drawing box");
	break;

      case LINE:
	add_edge( tmp, op[i].op.line.p0[0],
		  op[i].op.line.p0[1],
		  op[i].op.line.p0[1],
		  op[i].op.line.p1[0],
		  op[i].op.line.p1[1],
		  op[i].op.line.p1[1]);
	Zdraw_lines( tmp, t, g ,zbuffer);
	tmp->lastcol = 0;
	break;

      case MOVE:
	//get the factors
	xval = op[i].op.move.d[0];
	yval =  op[i].op.move.d[1];
	zval = op[i].op.move.d[2];
      
	//get knob if it exists
	if ( op[i].op.move.p != NULL ) {
	  knob_value = lookup_symbol( op[i].op.move.p->name )->s.value;
	  xval = xval * knob_value;
	  yval = yval * knob_value;
	  zval = zval * knob_value;
	}

	transform = make_translate( xval, yval, zval );
	//multiply by the existing origin
	matrix_mult( s->data[ s->top ], transform );
	//put the new matrix on the top
	copy_matrix( transform, s->data[ s->top ] );
	free_matrix( transform );
	break;

      case SCALE:
	xval = op[i].op.scale.d[0];
	yval = op[i].op.scale.d[1];
	zval = op[i].op.scale.d[2];
      
	//get knob if it exists
	if ( op[i].op.scale.p != NULL ) {
	  knob_value = lookup_symbol( op[i].op.scale.p->name )->s.value;
	  xval = xval * knob_value;
	  yval = yval * knob_value;
	  zval = zval * knob_value;
	}

	transform = make_scale( xval, yval, zval );
	matrix_mult( s->data[ s->top ], transform );
	//put the new matrix on the top
	copy_matrix( transform, s->data[ s->top ] );
	free_matrix( transform );
	break;

      case ROTATE:
	xval = op[i].op.rotate.degrees * ( M_PI / 180 );

	//get knob if it exists
	if ( op[i].op.rotate.p != NULL ) {
	  knob_value = lookup_symbol( op[i].op.rotate.p->name )->s.value;
	  xval = xval * knob_value;
	}

	//get the axis
	if ( op[i].op.rotate.axis == 0 ) 
	  transform = make_rotX( xval );
	else if ( op[i].op.rotate.axis == 1 ) 
	  transform = make_rotY( xval );
	else if ( op[i].op.rotate.axis == 2 ) 
	  transform = make_rotZ( xval );

	matrix_mult( s->data[ s->top ], transform );
	//put the new matrix on the top
	copy_matrix( transform, s->data[ s->top ] );
	free_matrix( transform );
	break;
	/*
      case AMBIENT:
	g.red += op[i].op.ambient.c[0];
	g.green += op[i].op.ambient.c[1];
	g.blue += op[i].op.ambient.c[2];
	break;
	*/
      case PUSH:
	push( s );
	break;
      case POP:
	pop( s );
	break;
      case SAVE:
	save_extension( t, op[i].op.save.p->name );
	break;
      case DISPLAY:
	display( t );
	break;
      }
    }
  
    free_stack( s );
    free_matrix( tmp );
    //free_matrix( transform );
 
    //save the image with the correct filename
    if ( num_frames > 1 ) {
      printf("Drawing frome: %d\n", f );
      sprintf( frame_name, "anim/%s%03d.png", name, f );
      save_extension( t, frame_name );
    }
    
  } //end frame loop

}
Пример #14
0
int main( int argc, char **argv )
{
    int i;
    int retval = 0;
    int nread;
    ssize_t errval;
    ssize_t raster_offset;
    pixelval_t **raster;
    long long sum;
    ssize_t ix, iy;
    long long linesum;

    progname = argv[0];

    if( argc > 1 ) {
	for( i = 1; i < argc; i++ ) {
	    struct RigakuHeader header;
	    FILE *in = fopen( argv[i], "r" );
	    if( !in ) {
		fprintf( stderr, "%s: %s: ERROR, can not open file "
			 "'%s' for input - %s\n", progname, argv[i],
			 argv[i], strerror(errno) );
		retval = 1;
		continue;
	    }
	    nread = fread( &header, sizeof(header), 1, in );
	    if( nread != 1 ) {
		fprintf( stderr, "%s: %s: ERROR, failed to read "
			 "%d bytes from the file\n", progname, argv[i],
			 sizeof(header));
		retval = 2;
		fclose( in );
		continue;
	    }

	    swapint( &header.xpxl, 1 );
	    swapint( &header.zpxl, 1 );

	    printf( "X size = %d\n", header.xpxl );
	    printf( "Y size = %d\n", header.zpxl );

	    raster = alloc_matrix( header.xpxl, header.zpxl );

	    if( !raster ) {
		fprintf( stderr, "%s: %s: ERROR, failed to allocate "
			 "raster %d x %d\n", progname, argv[i],
			 header.xpxl, header.zpxl );
		retval = 3;
		fclose( in );
		continue;		
	    }

	    raster_offset = header.xpxl * 2;

	    if( (errval = load_raster( in, raster, header.xpxl, header.zpxl,
				       raster_offset )) != 0 ) {
		fprintf( stderr, "%s: %s: ERROR, could not read "
			 "raster %d x %d at line %d - %s\n", progname, argv[i],
			 header.xpxl, header.zpxl, errval,
			 errno == 0 ? "file too short" : strerror(errno));
		retval = 3;
		fclose( in );
		continue;		
	    }

	    printf( "%d %d %d\n", raster[0][0], raster[0][1], raster[0][2] );
	    printf( "%d %d %d\n",
		    raster[100][100], raster[100][101], raster[100][102] );

	    sum = 0;
	    for( ix = 0; ix < header.xpxl; ix ++ ) {
		linesum = 0;
		for( iy = 0; iy < header.zpxl; iy ++ ) {
		    linesum += (int)(raster[ix][iy]);
		}
		sum += linesum;
	    }
	    printf( "%s: pixel sum %lld\n", argv[i], sum );
	    printf( "%s: number of pixels %d\n", argv[i],
		    header.xpxl * header.zpxl );
	    printf( "%s: average pixel value %g\n", argv[i],
		    (double)sum / (double)(header.xpxl * header.zpxl) );

	    free_matrix( raster, header.xpxl );
	    fclose( in );
	}
    } else {
	fprintf( stderr, "%s: WARNING, no file names provided "
		 "on the command line\n", progname );
    }

    return retval;
}
Пример #15
0
int main(int argc, char **argv)
{
    double t;
    int i, j, n, p;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &n);
    MPI_Comm_rank(MPI_COMM_WORLD, &p);

    if (n != 2) {
        printf("Must be run on exactly 2 processors.\n");
        MPI_Finalize();
        return 1;
    }

    t = MPI_Wtime();

    /* Allocate an COLS * ROWS array. */
    float **matrix;
    matrix = alloc_floatmatrix(COLS, ROWS);

    /* Fill processor 1's matrix with numbers */
    for (i = 0; i < COLS; i++) {
        for ( j = 0; j < ROWS; j++) {
            matrix[i][j] = (i * 10) + j;
        }
    }

    /* Define two MPI_Datatypes for rows that we use later */
    MPI_Datatype fullrowtype, partrowtype;
    MPI_Type_vector(ROWS, 1, ROWS, MPI_FLOAT, &fullrowtype);
    MPI_Type_commit(&fullrowtype);
    MPI_Type_vector(3, 1, ROWS, MPI_FLOAT, &partrowtype);
    MPI_Type_commit(&partrowtype);

    if (p == 0) {
        MPI_Status s;

        zeromatrix(matrix);
        MPI_Recv(matrix[4], ROWS, MPI_FLOAT, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving column 4:", matrix);

        zeromatrix(matrix);
        MPI_Recv(&matrix[6][2], 4, MPI_FLOAT, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving column 6, rows 3-5:", matrix);

        zeromatrix(matrix);
        MPI_Recv(matrix[3], ROWS*2, MPI_FLOAT, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving column 3 and 4:", matrix);

        zeromatrix(matrix);
        MPI_Recv(matrix[0], ROWS*COLS, MPI_FLOAT, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving all columns:", matrix);

        zeromatrix(matrix);
        MPI_Recv(&matrix[0][6], 1, fullrowtype, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving row 6:", matrix);
       
        zeromatrix(matrix); 
        MPI_Recv(&matrix[0][1], 1, partrowtype, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving row 1 cols 0-2:", matrix);
        
        zeromatrix(matrix); 
        MPI_Recv(&matrix[4][1], 1, partrowtype, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving row 1 cols 4-6:", matrix);
    } else {
        /* Send all of column 4 to processor 0 */
        MPI_Send(matrix[4], ROWS, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);

        /* Send column 6 rows 2-5 to processor 0 */
        MPI_Send(&matrix[6][2], 4, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);

        /* Send columns 3 and 4 to processor 0 */
        MPI_Send(matrix[3], ROWS*2, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);

        /* Send the entire matrix (ie all columns) to processor 0 */
        MPI_Send(matrix[0], ROWS*COLS, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);

        /* Send row 6 to processor 0 */
        MPI_Send(&matrix[0][6], 1, fullrowtype, 0, 0, MPI_COMM_WORLD);
        
        /* Send row 1 cols 0-2 to processor 0 */
        MPI_Send(&matrix[0][1], 1, partrowtype, 0, 0, MPI_COMM_WORLD);
        
        /* Send row 1 cols 4-6 to processor 0 */
        MPI_Send(&matrix[4][1], 1, partrowtype, 0, 0, MPI_COMM_WORLD);
    }
    if (p == 0) {
        t = MPI_Wtime() - t;
        printf("Program took %f secs to run.\n", t);
    }

    /* Free the matrix we allocated */
    free_matrix(matrix);

    /* Free the derived MPI_Datatypes */
    MPI_Type_free(&fullrowtype);
    MPI_Type_free(&partrowtype);

    MPI_Finalize();
    return 0;
}
Пример #16
0
void my_main( int polygons ) {

  int i, axis;
  double step = 0.01;
  double xval, yval, zval, degrees, radius, r0, r1, x, y, z, h, w, d;
  struct matrix *transform;
  struct matrix *tmp;
  struct stack *s;
  screen t;
  color g;
  s = new_stack();
  tmp = new_matrix(4, 1000);
  clear_screen( t );
  g.red = 110;
  g.green = 115;
  g.blue = 120;
  s = new_stack();
  tmp = new_matrix(4, 1000);
  clear_screen( t );
  for (i=0;i<lastop;i++) {  
    switch (op[i].opcode) {   
    case PUSH:
      push(s);
      break;    
    case POP:
      pop(s);
      break; 
    case MOVE:
      xval = op[i].op.move.d[0];
      yval = op[i].op.move.d[1];
      zval = op[i].op.move.d[2];
      transform = make_translate(xval, yval, zval);
      matrix_mult(transform, s->data[s->top]);
      break;
    case SCALE:
      xval = op[i].op.scale.d[0];
      yval = op[i].op.scale.d[1];
      zval = op[i].op.scale.d[2];
      transform = make_scale(xval, yval, zval);
      matrix_mult(transform, s->data[s->top]);
      break;
    case ROTATE:
      axis = op[i].op.rotate.axis;
      degrees = op[i].op.rotate.degrees * M_PI / 180;
      if (axis == 0)
	transform = make_rotX(degrees);
      if (axis == 1)
	transform = make_rotY(degrees);
      if (axis == 2)
	transform = make_rotZ(degrees);
      matrix_mult(transform, s->data[s->top]);
      break;
    case SPHERE:
      free_matrix(tmp);
      tmp = new_matrix(4, 1000);
      xval = op[i].op.sphere.d[0];
      yval = op[i].op.sphere.d[1];
      zval = op[i].op.sphere.d[2];
      radius = op[i].op.sphere.r;
      add_sphere(tmp, xval, yval, zval, radius, step);
      matrix_mult(s->data[s->top], tmp);
      draw_polygons(tmp, t, g);
      break;
    case BOX:
      free_matrix(tmp);
      tmp = new_matrix(4,1000);
      xval = op[i].op.box.d0[0];
      yval = op[i].op.box.d0[1];
      zval = op[i].op.box.d0[2];
      w = op[i].op.box.d1[0];
      h = op[i].op.box.d1[1];
      d = op[i].op.box.d1[2];
      add_box(tmp, xval, yval, zval, w, h, d);
      matrix_mult(s->data[s->top], tmp);
      draw_polygons(tmp, t, g);
      break;
    case TORUS:
      free_matrix(tmp);
      tmp = new_matrix(4, 1000);
      xval = op[i].op.torus.d[0];
      yval = op[i].op.torus.d[1];
      zval = op[i].op.torus.d[2];
      r0 = op[i].op.torus.r0;
      r1 = op[i].op.torus.r1;
      add_torus(tmp, xval, yval, zval, r0, r1, step);
      matrix_mult(s->data[s->top], tmp);
      draw_polygons(tmp, t, g);
      break;
    case LINE:
      free_matrix(tmp);
      tmp = new_matrix(4, 1000);
      xval = op[i].op.line.p0[0];
      yval = op[i].op.line.p0[1];
      zval = op[i].op.line.p0[2];
      x = op[i].op.line.p1[0];
      y = op[i].op.line.p1[1];
      z = op[i].op.line.p1[2];
      add_edge(tmp, xval, yval, zval, x, y, z);
      matrix_mult(s->data[s->top], tmp);
      draw_lines(tmp, t, g);
      break;
    case SAVE:
      display(t);
      save_extension(t, op[i].op.save.p->name);
      break;
    case DISPLAY:
      display(t);
      break;
    }
  }
}
Пример #17
0
void test_classifier(char *datacfg, char *cfgfile, char *weightfile, int target_layer)
{
    int curr = 0;
    network net = parse_network_cfg(cfgfile);
    if(weightfile){
        load_weights(&net, weightfile);
    }
    srand(time(0));

    list *options = read_data_cfg(datacfg);

    char *test_list = option_find_str(options, "test", "data/test.list");
    int classes = option_find_int(options, "classes", 1000);

    list *plist = get_paths(test_list);

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    clock_t time;

    data val, buffer;

    load_args args = {0};
    args.w = net.w;
    args.h = net.h;
    args.paths = paths;
    args.classes = classes;
    args.n = net.batch;
    args.m = 0;
    args.labels = 0;
    args.d = &buffer;
    args.type = CLASSIFICATION_DATA;

    pthread_t load_thread = load_data_in_thread(args);
    for(curr = net.batch; curr < m; curr += net.batch){
        time=clock();

        pthread_join(load_thread, 0);
        val = buffer;

        if(curr < m){
            args.paths = paths + curr;
            if (curr + net.batch > m) args.n = m - curr;
            load_thread = load_data_in_thread(args);
        }
        fprintf(stderr, "Loaded: %d images in %lf seconds\n", val.X.rows, sec(clock()-time));

        time=clock();
        matrix pred = network_predict_data(net, val);
        
        int i, j;
        if (target_layer >= 0){
            //layer l = net.layers[target_layer];
        }

        for(i = 0; i < pred.rows; ++i){
            printf("%s", paths[curr-net.batch+i]);
            for(j = 0; j < pred.cols; ++j){
                printf("\t%g", pred.vals[i][j]);
            }
            printf("\n");
        }

        free_matrix(pred);

        fprintf(stderr, "%lf seconds, %d images, %d total\n", sec(clock()-time), val.X.rows, curr);
        free_data(val);
    }
}
Пример #18
0
/*======== void parse_file () ==========
Inputs: char * filename
struct matrix * transform,
struct matrix * pm,
screen s
Returns:

Goes through the file named filename and performs all of the actions listed in that file.
The file follows the following format:
Every command is a single character that takes up a line
Any command that requires arguments must have those arguments in the second line.
The commands are as follows:
l: add a line to the edge matrix -
takes 6 arguemnts (x0, y0, z0, x1, y1, z1)
c: add a circle to the edge matrix -
takes 3 arguments (cx, cy, r)
h: add a hermite curve to the edge matrix -
takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3)
b: add a bezier curve to the edge matrix -
takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3)
i: set the transform matrix to the identity matrix -
s: create a scale matrix,
then multiply the transform matrix by the scale matrix -
takes 3 arguments (sx, sy, sz)
t: create a translation matrix,
then multiply the transform matrix by the translation matrix -
takes 3 arguments (tx, ty, tz)
x: create an x-axis rotation matrix,
then multiply the transform matrix by the rotation matrix -
takes 1 argument (theta)
y: create an y-axis rotation matrix,
then multiply the transform matrix by the rotation matrix -
takes 1 argument (theta)
z: create an z-axis rotation matrix,
then multiply the transform matrix by the rotation matrix -
takes 1 argument (theta)
a: apply the current transformation matrix to the
edge matrix
v: draw the lines of the edge matrix to the screen
display the screen
g: draw the lines of the edge matrix to the screen
save the screen to a file -
takes 1 argument (file name)
q: end parsing

See the file script for an example of the file format


IMPORTANT MATH NOTE:
the trig functions int math.h use radian mesure, but us normal
humans use degrees, so the file will contain degrees for rotations,
be sure to conver those degrees to radians (M_PI is the constant
for PI)

03/08/12 16:22:10
jdyrlandweaver
====================*/
void parse_file ( char * filename,
                  struct matrix * transform,
                  struct matrix * pm,
                  screen s) {

  FILE *f;
  char line[256];
  struct matrix * tmp;
  double angle;
  color g;

  g.red = 255;
  g.green = 0;
  g.blue = 255;
  
  clear_screen(s);

  if ( strcmp(filename, "stdin") == 0 )
    f = stdin;
  else
    f = fopen(filename, "r");
  
  while ( fgets(line, 255, f) != NULL ) {
    line[strlen(line)-1]='\0';
    //printf(":%s:\n",line);
    char c;
    double x, y, z, x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4;
   
    c = line[0];

    switch (c) {
    case 'l':
      // printf("LINE!\n");
      fgets(line, 255, f);
      // printf("\t%s", line);
      //line[strlen(line)-1]='\0';
      sscanf(line, "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &x1, &y1, &z1);
      add_edge(pm, x, y, z, x1, y1, z1);
      // printf( "%lf %lf %lf %lf %lf %lf\n", x, y, z, x1, y1, z1);
      break;
    case 's':
      //printf("SCALE\n");
      fgets(line, 255, f);
      //line[strlen(line)-1]='\0';
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      tmp = make_scale(x, y, z);
      matrix_mult(tmp, transform);
      //print_matrix(transform);
      break;
    case 't':
      //printf("TRANSLATE\n");
      fgets(line, 255, f);
      // line[strlen(line)-1]='\0';
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      tmp = make_translate(x, y, z);
      matrix_mult(tmp, transform);
      //print_matrix(transform);
      break;
    case 'x':
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotX( angle);
      matrix_mult(tmp, transform);
      break;
    case 'y':
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotY( angle);
      matrix_mult(tmp, transform);
      break;
    case 'z':
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotZ( angle);
      matrix_mult(tmp, transform);
      break;
    case 'i':
      ident(transform);
      break;
    case 'c':
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      add_circle(pm, x, y, z, .001);
      break;
    case 'h': //hermite
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf", &x, &y, &x1, &y1, &x2, &y2, &x3, &y3);
      add_curve(pm, x, y, x1, y1, x2, y2, x3, y3, .001, 0);
      break;
    case 'b': //bezier
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf", &x, &y, &x1, &y1, &x2, &y2, &x3, &y3);
      add_curve(pm, x, y, x1, y1, x2, y2, x3, y3, .001, 1);
      break;
    case 'a':
      //printf("APPLY!\n");
      //print_matrix( transform );
      // print_matrix(pm);
      matrix_mult(transform, pm);
      break;
    case 'v':
      clear_screen(s);
      draw_lines(pm, s, g);
      display(s);
      break;
    case 'g':
      fgets(line, 255, f);
      // line[strlen(line)-1] = '\0';
      clear_screen(s);
      draw_lines(pm, s, g);
      save_extension(s, line);
      break;
    case 'q':
      return;
    default:
      printf("Invalid command\n");
      break;
    }
  }

  free_matrix(tmp);
  fclose(f);
  //printf("END PARSE\n");
}
Пример #19
0
TEXTURE * Extract_Texture_Features(int distance, int angle,
		 		register u_int8_t **grays, int rows, int cols, int max_val)
{
	int tone_LUT[PGM_MAXMAXVAL+1]; /* LUT mapping gray tone(0-255) to matrix indicies */
	int tone_count=0; /* number of tones actually in the img. atleast 1 less than 255 */
	int itone;
	int row, col, i;
	double **P_matrix;
	double sum_entropy;
	TEXTURE *Texture;
	Texture = (TEXTURE *) calloc(1,sizeof(TEXTURE));
	if (!Texture) {
		printf("\nERROR in TEXTURE structure allocate\n");
		exit(1);
	}

	/* Determine the number of different gray tones (not maxval) */
	for (row = PGM_MAXMAXVAL; row >= 0; --row)
		tone_LUT[row] = -1;
	for (row = rows - 1; row >= 0; --row)
		for (col = 0; col < cols; ++col)
			tone_LUT[grays[row][col]] = grays[row][col];

	for (row = PGM_MAXMAXVAL, tone_count = 0; row >= 0; --row)
		if (tone_LUT[row] != -1)
			  tone_count++;

	/* Use the number of different tones to build LUT */
	for (row = 0, itone = 0; row <= PGM_MAXMAXVAL; row++)
		if (tone_LUT[row] != -1)
		  tone_LUT[row] = itone++;

	/* compute gray-tone spatial dependence matrix */
	if (angle == 0)
		P_matrix = CoOcMat_Angle_0   (distance, grays, rows, cols, tone_LUT, tone_count);
	else if (angle == 45)
		P_matrix = CoOcMat_Angle_45  (distance, grays, rows, cols, tone_LUT, tone_count);
	else if (angle == 90)
		P_matrix = CoOcMat_Angle_90  (distance, grays, rows, cols, tone_LUT, tone_count);
	else if (angle == 135)
		P_matrix = CoOcMat_Angle_135 (distance, grays, rows, cols, tone_LUT, tone_count);
	else {
		fprintf (stderr, "Cannot created co-occurence matrix for angle %d. Unsupported angle.\n", angle);
		return NULL;
	}

	/* compute the statistics for the spatial dependence matrix */
  	Texture->ASM           = f1_asm       (P_matrix, tone_count);
  	Texture->contrast      = f2_contrast  (P_matrix, tone_count);
 	Texture->correlation   = f3_corr      (P_matrix, tone_count);
  	Texture->variance      = f4_var       (P_matrix, tone_count);
  	Texture->IDM           = f5_idm       (P_matrix, tone_count);
  	Texture->sum_avg       = f6_savg      (P_matrix, tone_count);

  	/* T.J.M watch below the cast from float to double */ 
  	sum_entropy            = f8_sentropy  (P_matrix, tone_count); 
  	Texture->sum_entropy   = sum_entropy;
	Texture->sum_var       = f7_svar      (P_matrix, tone_count, sum_entropy);

  	Texture->entropy       = f9_entropy   (P_matrix, tone_count);
  	Texture->diff_var      = f10_dvar     (P_matrix, tone_count);
  	Texture->diff_entropy  = f11_dentropy (P_matrix, tone_count);
  	Texture->meas_corr1    = f12_icorr    (P_matrix, tone_count);
  	Texture->meas_corr2    = f13_icorr    (P_matrix, tone_count);
        Texture->max_corr_coef = f14_maxcorr  (P_matrix, tone_count);

        free_matrix(P_matrix,tone_count);
	return (Texture);
} 
Пример #20
0
/*======== void my_main() ==========
  Inputs:
  Returns: 

  This is the main engine of the interpreter,  it should
  handle most of the commadns in mdl.

  If frames is not present in the source (and therefore 
  num_frames is 1,  then process_knobs should be called.

  If frames is present,  the enitre op array must be
  applied frames time. At the end of each frame iteration
  save the current screen to a file named the
  provided basename plus a numeric string such that the
  files will be listed in order,  then clear the screen and
  reset any other data structures that need it.

  Important note: you cannot just name your files in 
  regular sequence,  like pic0,  pic1,  pic2,  pic3... if that
  is done,  then pic1,  pic10,  pic11... will come before pic2
  and so on. In order to keep things clear,  add leading 0s
  to the numeric portion of the name. If you use sprintf,  
  you can use "%0xd" for this purpose. It will add at most
  x 0s in front of a number,  if needed,  so if used correctly, 
  and x = 4,  you would get numbers like 0001,  0002,  0011, 
  0487

  05/17/12 09:41:35
  jdyrlandweaver
  ====================*/
void my_main( int polygons ) {

  int i, f, j;
  double step;
  double xval, yval, zval, knob_value;
  struct matrix *transform;
  struct matrix *tmp;
  struct stack *s = new_stack();
  screen t;
  clear_screen(t);
  color g;

  double factor;
  //struct vary_node **knobs;
  //struct vary_node *vn;
  char frame_name[128];

  num_frames = 1;
  step = 5;
  int animated = 0;
  
  g.red = 0;
  g.green = 255;
  g.blue = 255;
  
  first_pass(&num_frames, frame_name);
  if (num_frames!=1)
    animated=1;
  struct vary_node ** knobs=second_pass(num_frames);
  struct vary_node * current;
  j=0;
  while(j<num_frames){
    tmp=new_matrix(4, 4);
    struct stack *s=new_stack();
    if (animated){
      current=knobs[j];
      while (current->next){
	set_value(lookup_symbol(current->name), current->value);
	current=current->next;
      }
      set_value(lookup_symbol(current->name), current->value);
    }
    for (i=0;i<lastop;i++) {
      switch (op[i].opcode) {
	
      case SPHERE:
	add_sphere( tmp, op[i].op.sphere.d[0],  //x
		    op[i].op.sphere.d[1],       //y
		    op[i].op.sphere.d[2],       //z
		    op[i].op.sphere.r, 
		    step);

	matrix_mult( s->data[ s->top ], tmp );
	draw_polygons( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case TORUS:
	add_torus( tmp, op[i].op.torus.d[0],  //x
		   op[i].op.torus.d[1],       //y
		   op[i].op.torus.d[2],       //z
		   op[i].op.torus.r0, 
		   op[i].op.torus.r1, 
		   step);
	matrix_mult( s->data[ s->top ], tmp );
	draw_polygons( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case BOX:
	add_box( tmp,  op[i].op.box.d0[0], 
		 op[i].op.box.d0[1], 
		 op[i].op.box.d0[2], 
		 op[i].op.box.d1[0], 
		 op[i].op.box.d1[1], 
		 op[i].op.box.d1[2]);
	matrix_mult( s->data[ s->top ], tmp );
	draw_polygons( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case LINE:
	add_edge( tmp,  op[i].op.line.p0[0], 
		  op[i].op.line.p0[1], 
		  op[i].op.line.p0[1], 
		  op[i].op.line.p1[0], 
		  op[i].op.line.p1[1], 
		  op[i].op.line.p1[1]);
	matrix_mult( s->data[ s->top ], tmp );
	draw_lines( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case MOVE:
	//get the factor
	if (op[i].op.move.p)
	  factor=op[i].op.move.p->s.value;
	else
	  factor=1;
	if (factor != 0){
	  xval = op[i].op.move.d[0]*factor;
	  yval = op[i].op.move.d[1]*factor;
	  zval = op[i].op.move.d[2]*factor;

	  transform = make_translate( xval, yval, zval );
	  //multiply by the existing origin
	  matrix_mult( s->data[ s->top ], transform );
	  //put the new matrix on the top
	  copy_matrix( transform, s->data[ s->top ] );
	  free_matrix( transform );
	}
	break;

      case SCALE:
	if (op[i].op.scale.p)
	  factor=op[i].op.scale.p->s.value;
	else
	  factor=1;
	if (factor!=0){
	  xval = op[i].op.scale.d[0]*factor;
	  yval = op[i].op.scale.d[1]*factor;
	  zval = op[i].op.scale.d[2]*factor;
      
	  transform = make_scale( xval,  yval,  zval );
	  matrix_mult( s->data[ s->top ],  transform );
	  //put the new matrix on the top
	  copy_matrix( transform,  s->data[ s->top ] );
	  free_matrix( transform );
	}
	break;

      case ROTATE:
	if (op[i].op.rotate.p)
	  factor=op[i].op.rotate.p->s.value;
	else
	  factor=1;
	if (factor!=0){
	  xval = op[i].op.rotate.degrees * ( M_PI / 180 )*factor;

	  //get the axis
	  if ( op[i].op.rotate.axis == 0 ) 
	    transform = make_rotX( xval );
	  else if ( op[i].op.rotate.axis == 1 ) 
	    transform = make_rotY( xval );
	  else if ( op[i].op.rotate.axis == 2 ) 
	    transform = make_rotZ( xval );

	  matrix_mult( s->data[ s->top ],  transform );
	  //put the new matrix on the top
	  copy_matrix( transform,  s->data[ s->top ] );
	  free_matrix( transform );
	}
	break;

      case PUSH:
	push( s );
	break;
      case POP:
	pop( s );
	break;
      case SAVE:
	save_extension( t, op[i].op.save.p->name );
	break;
      case DISPLAY:
	display( t );
	break;
      }
    }
    if (animated){
      print_knobs();
      char * name[150];
      printf("frame number: %d\n", j);
      printf("name: %s\n", frame_name);
      if (num_frames < 10)
	sprintf(name, "animate/%s%0d.png", frame_name, j);
      else if (10 < num_frames < 100)
	sprintf(name, "animate/%s%03d.png", frame_name, j);
      //      else if (100 < num_frames < 1000)
      //sprintf(name, "animate/%s%04d.png", frame_name, j);
      printf("Saving %s\n\n", name);
      save_extension(t, name);
      clear_screen(t);
    }
    free_stack( s );
    free_matrix( tmp );
    j++;
  }
}
Пример #21
0
int main() {
  int i, j;
  screen s;
  color c;

  struct matrix *edges;
  struct matrix *transform;
  struct matrix *identity;

  edges = new_matrix(4, 4);
  transform = new_matrix(4, 4);
  identity = new_matrix(4, 4);

  /*
Different Matrices for Testing Different Matrix Operations
  struct matrix *tester;
  struct matrix *tester2;
  tester2 = new_matrix(4, 2);  
  tester = new_matrix(4, 4);
  
  clear_matrix( edges );
  printf("Edge Matrix:\n");
  print_matrix( edges );
  clear_matrix( transform );
  printf("Transform Matrix:\n");
  print_matrix( transform );
  
//////////////////////////////////
Initializations of Tester Matrices
//////////////////////////////////
  counter = 0;
  for (i = 0; i < tester->rows; i++ ) {
    for (j = 0; j < tester->cols; j++ ) {
      tester->m[i][j] = counter;
      counter += 1;
    }
  }
  printf("Tester Matrix:\n");
  print_matrix( tester );

  counter = 0;
  for (i = 0; i < tester2->rows; i++ ) {
    for (j = 0; j < tester2->cols; j++ ) {
      tester2->m[i][j] = 1;
    }
  }
  printf("Tester2 Matrix:\n");
  print_matrix( tester2 );

  printf("\n\n");

///////////////////////////////

IDENTITY
  printf("Testing Identity: Identity Matrix\n");
  print_matrix( identity );
  
SCALAR MULTIPLICATION
  printf("Testing Scalar Multiplication ( 2.5 * Tester )\n");
  scalar_mult( mult, tester );
  print_matrix( tester );
  
MATRIX MULTIPLICATION
  printf("Testing Matrix Multiplication With Identity => SAME\n");  
  matrix_mult( identity, tester );
  print_matrix( tester );
  printf("Testing Matrix Multiplication With (4x4) and (4x2)\n");  
  matrix_mult( tester, tester2 );
  print_matrix( tester2 );
  
  printf("\n\n");
  printf("Tester Before\n");
  clear_matrix( tester );
  print_matrix( tester );
  
ADDING POINTS
  printf("Adding Point to tester\n");
  add_point( tester, 1, 2, 3);
  print_matrix( tester );
  printf("\nAdding Point to tester again\n");
  add_point( tester, 4, 5, 6);
  add_point( tester, 7, 8, 9);
  add_point( tester, 10, 11, 12);
  add_point( tester, 13, 14, 15);
  print_matrix( tester );
  
ADDING EDGES
  printf("Adding Edge to Tester\n");
  add_edge( tester, 1, 1, 1, 2, 2, 2 );
  add_edge( tester, 3, 3, 3, 4, 4, 4 );
  add_edge( tester, 5, 5, 5, 6, 6, 6 );
  print_matrix( tester );

  free_matrix( tester );
  free_matrix( tester2 );


  ident( identity );
  int x0, y0, z0, x1, y1, z1;
  z0 = 0;
  z1 = 0;
  */
  
  c.red = MAX_COLOR;
  c.green = MAX_COLOR;
  c.blue = MAX_COLOR;
  clear_screen(s);

  //SCALAR MULT (DILATION)
  clear_matrix(edges);
  clear_matrix(transform);
  add_edge( edges, 1,1,0, 6,1,0 );
  add_edge( edges, 6,1,0, 6,6,0 );
  add_edge( edges, 6,6,0, 1,6,0 );
  add_edge( edges, 1,6,0, 1,1,0 );
  draw_lines(edges,s,c);
  
  for(i = 0; i < 55; i++){
    scalar_mult(1.09, edges);
    c.red = c.red - 4;
    draw_lines(edges,s,c);
  }

  //TRANSLATE
  clear_matrix(edges);
  clear_matrix(transform);
  c.red = MAX_COLOR;
  add_edge( edges, 0,YRES,0, 0,YRES-25,0 );
  add_edge( edges, 0,YRES-25,0, 25,YRES-25,0 );
  add_edge( edges, 25,YRES-25,0, 25,YRES,0 );
  add_edge( edges, 25,YRES,0, 0,YRES,0 );
  draw_lines(edges,s,c);
  
  for(i = 0; i < 20; i++){
    transform = make_translate( 25, -25, 0 );
    matrix_mult( transform, edges);
    c.green = c.green - 4;
    draw_lines(edges,s,c);
  }
  
  //ROTATION
  clear_matrix(edges);
  clear_matrix(transform);
  c.green = MAX_COLOR;
  add_edge( edges, XRES,0,0, XRES,25,0 );
  add_edge( edges, XRES,25,0, XRES-25,25,0 );
  add_edge( edges, XRES-25,25,0, XRES-25,0,0 );
  add_edge( edges, XRES-25,0,0, XRES,0,0 );
  draw_lines(edges,s,c);

  for(i = 0; i < 20; i++){
    transform = make_rotZ( 4.5 );
    matrix_mult( transform, edges);
    c.blue = c.blue - 4;
    draw_lines(edges,s,c);
  }

  //Central Flower
  clear_matrix(edges);
  clear_matrix(transform);
  c.blue = MAX_COLOR;
  c.red = 0;
  c.green = 0;
  add_edge( edges, 200,200,0, 200,300,0 );
  add_edge( edges, 200,300,0, 300,300,0 );
  add_edge( edges, 300,300,0, 300,200,0 );
  add_edge( edges, 300,200,0, 200,200,0 );
  draw_lines(edges,s,c);

  for(i = 0; i < 36; i++){
    transform = make_rotZ( 10 );
    matrix_mult( transform, edges);
    transform = make_translate( 50, -50, 0);
    matrix_mult( transform, edges);
    draw_lines(edges,s,c);
  }

  //NAME
  clear_matrix(edges);
  clear_matrix(transform);
  c.blue = MAX_COLOR;
  c.red = MAX_COLOR;
  c.green = MAX_COLOR;
  add_edge( edges, 250,0,0, 250,25,0 );//M
  add_edge( edges, 250,25,0, 263,0,0 );
  add_edge( edges, 263,0,0, 275,25,0 );
  add_edge( edges, 275,25,0, 275,0,0 );
  add_edge( edges, 280,0,0, 293,25,0 );//A
  add_edge( edges, 293,25,0, 305,0,0 );
  add_edge( edges, 287,13,0, 299,13,0 );
  add_edge( edges, 310,0,0, 325,25,0 );//Y
  add_edge( edges, 318,13,0, 305,25,0 );
  add_edge( edges, 330,0,0, 343,25,0 );//A
  add_edge( edges, 343,25,0, 355,0,0 );
  add_edge( edges, 337,13,0, 349,13,0 );
  add_edge( edges, 360,0,0, 360,25,0 );//N
  add_edge( edges, 360,25,0, 385,0,0 );
  add_edge( edges, 385,0,0, 385,25,0 );
  add_edge( edges, 390,0,0, 390,25,0 );//K
  add_edge( edges, 390,13,0, 408,25,0 );
  add_edge( edges, 395,14,0, 408,0,0 );
  draw_lines(edges,s,c);

  save_extension(s, "matrix.png" );
  display(s);

  free_matrix( transform );
  free_matrix( edges );
}  
Пример #22
0
rational scale(int dimdiff, T_LassInt *fvTree, T_LassInt * fvNew)
{   int i, j, k, l, m, n;
    int *pcol,  /* pivot columns */
        *dcol,  /* determinant columns */ 
        *frow;  /* fixed constraints (rows) */
    rational **Ascale; /* contains complete rows of scaling matrix */
    rational **Adet; /* contains square scaling matrix */
    rational r1;

   pcol = create_int_vector (dimdiff);
   dcol = create_int_vector (dimdiff);
   frow = create_int_vector (dimdiff);
	Ascale = create_matrix (dimdiff, G_d);
	Adet = create_matrix (dimdiff, dimdiff);

    /* extract index sets where projection on differing subspaces happened */

    j=l=m=n=0; 
    for (i=0; i<G_d; i++){
        while (fvTree[j]<i) j++;
	if (fvTree[j]>i) { /* i is not in fvTree */
	    for (k=0; k<dimdiff; k++){
	        if (i==p2c[k][0]){
		    pcol[l]=i;
		    frow[l]=k;   /* =p2c[k][1]; */
		    l++;
		    break;
	        }
	    }
	}
	else { /* i is in fvTree */
            while (fvNew[m]<i) m++;
	    if (fvNew[m]>i) { /* i is not in fvNew */
	        dcol[n]=i;
                n++;
	    }
	}
    }

    /* test consistent dimensionality; can be omitted */

    if (n!=l) {
        fprintf(stderr, "\n***** ERROR: Non-square scaling matrix in 'scale'\n");
	exit(1);
    };

    if (n==0) return 1; /* projection was done on the same subspace */ 

    /* Build Ascale and inverte right half by left half */

    for (i=0; i<dimdiff; i++)
        for (j=0; j<G_d; j++) Ascale[i][j] = G_Hyperplanes[p2c[i][1]][j];
    for (i=0; i<dimdiff; i++){
	r1=1/Ascale[i][p2c[i][0]];
	for (j=0; j<G_d; j++) Ascale[i][j]*=r1;  /* divide pivot-row by pivot-element */
        for (j=0; j<dimdiff; j++){
	    if (i==j) continue;
	    for (k=0; k<G_d; k++){
	        if (k!=p2c[i][0])
	            Ascale[j][k] -= Ascale[i][k]*Ascale[j][p2c[i][0]];
	    }
	}
    }

    /* extract determinant submatrix Adet */

    for (i=0; i<n; i++)
        for (j=0; j<n; j++)
            Adet[i][j]=Ascale[frow[i]][dcol[j]];
    
    if (n==1) { /* here the determinant is trivial */
        return 1/fabs(Adet[0][0]);
    }

    /* compute determinant of Adet (modulo sign due to permutation) */

    for (i=0; i<n; i++) pcol[i]=-1;
    for (i=0; i<n-1; i++){
        j=0;                     /* search for pivot column */
	while (pcol[j]>=0) j++;
	for (k=j+1; k<n; k++) { 
	    if (pcol[k]>=0) continue;
	    if (fabs(Adet[i][k])>fabs(Adet[i][j])) j=k;
	};
        pcol[j]=i;
	for (k=i+1; k<n; k++)
	    for (l=0; l<n; l++){
	        if (l!=j)
                    Adet[k][l] -= Adet[i][l]/Adet[i][j]*Adet[k][j];
	    }
    };
    
    r1=1;
    for (i=0; i<n; i++) {
        if (pcol[i]>=0) r1*=Adet[pcol[i]][i];
	else r1*=Adet[n-1][i];
    }
	 
	 free_int_vector (pcol, dimdiff);
	 free_int_vector (dcol, dimdiff);
	 free_int_vector (frow, dimdiff);
	 free_matrix (Ascale, dimdiff, G_d);
	 free_matrix (Adet, dimdiff, dimdiff);

    return 1/fabs(r1);
}
Пример #23
0
void matinv(float ** a, int n){

    /* extern variables */
    /*extern int NPROCX, NPROCY, MYID, POS[3];*/
	
    /* local variables */
    int m,i,j,p,q;
    float tem=0,temp=0,temp1=0,temp2=0,temp4=0,temp5=0, **b;
    b = matrix(1,2,1,2);
    
    for(i=1;i<=n;i++){
       for(j=1;j<=n;j++){
          if(i==j){b[i][j]=1.0;}
          if(i!=j){b[i][j]=0.0;}
       }
    }
        

	
	for(i=1;i<n;i++)
	{
		temp=a[i][i];
		if(temp<0)
		temp=temp*(-1);
		p=i;
		for(j=i+1;j<n;j++)
		{
			if(a[j][i]<0)
				tem=a[j][i]*(-1);
			else
				tem=a[j][i];
			if(temp<0)
				temp=temp*(-1);
			if(tem>temp)
			{
				p=j;
				temp=a[j][i];
			}
		}
		//row exchange in both the matrix
		for(j=1;j<n;j++)
		{
			temp1=a[i][j];
			a[i][j]=a[p][j];
			a[p][j]=temp1;
			temp2=b[i][j];
			b[i][j]=b[p][j];
			b[p][j]=temp2;
		}
		//dividing the row by a[i][i]
		temp4=a[i][i];
		for(j=1;j<n;j++)
		{
			a[i][j]=(float)a[i][j]/temp4;
			b[i][j]=(float)b[i][j]/temp4;
		}
		//making other elements 0 in order to make the matrix a[][] an indentity matrix and obtaining a inverse b[][] matrix
		for(q=1;q<n;q++)
		{
			if(q==i)
				continue;
			temp5=a[q][i];
			for(j=1;j<n;j++)
			{
				a[q][j]=a[q][j]-(temp5*a[i][j]);
				b[q][j]=b[q][j]-(temp5*b[i][j]);
			}
		}
	}

    /* output of the inverse matrix */
    for(i=1;i<=n;i++){
       for(j=1;j<=n;j++){
          a[i][j]=b[i][j];
       }
    }

free_matrix(b,1,2,1,2);    
    	

}
Пример #24
0
/*======== void my_main() ==========
  Inputs:   int polygons  
  Returns: 

  This is the main engine of the interpreter, it should
  handle most of the commadns in mdl.

  If frames is not present in the source (and therefore 
  num_frames is 1, then process_knobs should be called.

  If frames is present, the enitre op array must be
  applied frames time. At the end of each frame iteration
  save the current screen to a file named the
  provided basename plus a numeric string such that the
  files will be listed in order, then clear the screen and
  reset any other data structures that need it.

  Important note: you cannot just name your files in 
  regular sequence, like pic0, pic1, pic2, pic3... if that
  is done, then pic1, pic10, pic11... will come before pic2
  and so on. In order to keep things clear, add leading 0s
  to the numeric portion of the name. If you use sprintf, 
  you can use "%0xd" for this purpose. It will add at most
  x 0s in front of a number, if needed, so if used correctly,
  and x = 4, you would get numbers like 0001, 0002, 0011,
  0487

  05/17/12 09:41:35
  jdyrlandweaver
  ====================*/
void my_main( int polygons ) {

  int i, f, j;
  double step;
  double xval, yval, zval, knob_value;
  struct matrix *transform;
  struct matrix *tmp;
  struct stack *s;
  screen t;
  color g;
  char q;
  struct vary_node * temp;
  struct vary_node ** knobs;
  make_zbuf();
  num_frames = 1;
  step = 0.05;

  g.red = 0;
  g.green = 255;
  g.blue = 255;

  first_pass();

  if (num_frames >= 1) {
    knobs = second_pass();
  }
 
  for (f = 0; f < num_frames; f++) {
      
    s = new_stack();
    tmp = new_matrix(4, 1000);
    clear_screen( t );
    
    for (j = 0; j < lastsym; j++) {
      if (symtab[j].type == SYM_VALUE) {
	temp = knobs[f];
	while (strcmp(temp->name, symtab[j].name)) {
	  temp = temp->next;
	}
	if (tmp)
	  (&symtab[j])->s.value = temp->value;
      }
    }
    
    
    for (i=0;i<lastop;i++) {
  
      switch (op[i].opcode) {

      case SET:
	knob_value = op[i].op.set.p->s.value;
	set_value(lookup_symbol(op[i].op.set.p->name), knob_value);
	break;
	
      case SETKNOBS:
	knob_value = op[i].op.setknobs.value;
	for (j = 0; j < lastsym; j++) {
	  if (symtab[j].type == SYM_VALUE)
	    set_value(&(symtab[j]), knob_value);
	}
	break;
	
      case SPHERE:
	add_sphere( tmp,op[i].op.sphere.d[0], //cx
		    op[i].op.sphere.d[1],  //cy
		    op[i].op.sphere.d[2],  //cz
		    op[i].op.sphere.r,
		    step);
	//apply the current top origin
	matrix_mult( s->data[ s->top ], tmp );
	draw_polygons( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case TORUS:
	add_torus( tmp, op[i].op.torus.d[0], //cx
		   op[i].op.torus.d[1],     //cy
		   op[i].op.torus.d[2],    //cz
		   op[i].op.torus.r0,
		   op[i].op.torus.r1,
		   step);
	matrix_mult( s->data[ s->top ], tmp );
	draw_polygons( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case BOX:
	add_box( tmp, op[i].op.box.d0[0],
		 op[i].op.box.d0[1],
		 op[i].op.box.d0[2],
		 op[i].op.box.d1[0],
		 op[i].op.box.d1[1],
		 op[i].op.box.d1[2]);
	matrix_mult( s->data[ s->top ], tmp );
	draw_polygons( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case LINE:
	add_edge( tmp, op[i].op.line.p0[0],
		  op[i].op.line.p0[1],
		  op[i].op.line.p0[1],
		  op[i].op.line.p1[0],
		  op[i].op.line.p1[1],
		  op[i].op.line.p1[1]);
	draw_lines( tmp, t, g );
	tmp->lastcol = 0;
	break;

      case MOVE:
	knob_value = 1;
	if (op[i].op.move.p) {
	  temp = knobs[f];
	  while (strcmp(temp->name, op[i].op.move.p->name))
	    temp = temp->next;
	  if (temp)
	    knob_value = temp->value;
	}
	//get the factors
	xval = op[i].op.move.d[0] * knob_value;
	yval =  op[i].op.move.d[1] * knob_value;
	zval = op[i].op.move.d[2] * knob_value;

	transform = make_translate( xval, yval, zval );
	//multiply by the existing origin
	matrix_mult( s->data[ s->top ], transform );
	//put the new matrix on the top
	copy_matrix( transform, s->data[ s->top ] );
	free_matrix( transform );
	break;

      case SCALE:
	knob_value = 1;
	if (op[i].op.scale.p) {
	  temp = knobs[f];
	  while (strcmp(temp->name, op[i].op.scale.p->name))
	    temp = temp->next;
	  if (temp)
	    knob_value = temp->value;
	}
	xval = op[i].op.scale.d[0] * knob_value;
	yval = op[i].op.scale.d[1] * knob_value;
	zval = op[i].op.scale.d[2] * knob_value;
      
	transform = make_scale( xval, yval, zval );
	matrix_mult( s->data[ s->top ], transform );
	//put the new matrix on the top
	copy_matrix( transform, s->data[ s->top ] );
	free_matrix( transform );
	break;
	
      case ROTATE:
	knob_value = 1;
	if (op[i].op.rotate.p) {
	  temp = knobs[f];
	  while (strcmp(temp->name, op[i].op.rotate.p->name))
	    temp = temp->next;
	  if (temp)
	    knob_value = temp->value;
	}
	xval = op[i].op.rotate.degrees * ( M_PI / 180 ) * knob_value;

	//get the axis
	if ( op[i].op.rotate.axis == 0 ) 
	  transform = make_rotX( xval );
	else if ( op[i].op.rotate.axis == 1 ) 
	  transform = make_rotY( xval );
	else if ( op[i].op.rotate.axis == 2 ) 
	  transform = make_rotZ( xval );

	matrix_mult( s->data[ s->top ], transform );
	//put the new matrix on the top
	copy_matrix( transform, s->data[ s->top ] );
	free_matrix( transform );
	break;
	
      case PUSH:
	push( s );
	break;
      case POP:
	pop( s );
	break;
      case SAVE:
	save_extension( t, op[i].op.save.p->name );
	break;
      case DISPLAY:
	display( t );
	break;
      }
    }
    char dir[256];
    char s[256];
    strcpy(dir, "pics/");
    sprintf(s, "%03d", f);
    strcat(dir, name);
    strcat(dir, s);
    strcat(dir, ".png");
    save_extension(t, dir);
  }
  free_stack( s );
  free_matrix( tmp );
  //free_matrix( transform );
}
Пример #25
0
void bsstep(double y[], double dydx[], int nv, double *xx, double htry, double eps,
	double yscal[], double *hdid, double *hnext,
	void (*derivs)(double, double [], double []))
{
	void mmid(double y[], double dydx[], int nvar, double xs, double htot,
		int nstep, double yout[], void (*derivs)(double, double[], double[]));
	void pzextr(int iest, double xest, double yest[], double yz[], double dy[],
		int nv);
	int i,iq,k,kk,km;
	static int first=1,kmax,kopt;
	static double epsold = -1.0,xnew;
	double eps1,errmax,fact,h,red,scale,work,wrkmin,xest;
	double *err,*yerr,*ysav,*yseq;
	static double a[IMAXX+1];
	static double alf[KMAXX+1][KMAXX+1];
	static int nseq[IMAXX+1]={0,2,4,6,8,10,12,14,16,18};
	int reduct,exitflag=0;

	d=matrix(1,KMAXX,1,KMAXX);
	err=vector(1,KMAXX);
	x=vector(1,KMAXX);
	yerr=vector(1,nv);
	ysav=vector(1,nv);
	yseq=vector(1,nv);
	if (eps != epsold) {
		*hnext = xnew = -1.0e29;
		eps1=SAFE1*eps;
		a[1]=nseq[1]+1;
		for (k=1;k<=KMAXX;k++) a[k+1]=a[k]+nseq[k+1];
		for (iq=2;iq<=KMAXX;iq++) {
			for (k=1;k<iq;k++)
				alf[k][iq]=pow(eps1,(a[k+1]-a[iq+1])/
					((a[iq+1]-a[1]+1.0)*(2*k+1)));
		}
		epsold=eps;
		for (kopt=2;kopt<KMAXX;kopt++)
			if (a[kopt+1] > a[kopt]*alf[kopt-1][kopt]) break;
		kmax=kopt;
	}
	h=htry;
	for (i=1;i<=nv;i++) ysav[i]=y[i];
	if (*xx != xnew || h != (*hnext)) {
		first=1;
		kopt=kmax;
	}
	reduct=0;
	for (;;) {
		for (k=1;k<=kmax;k++) {
			xnew=(*xx)+h;
			if (xnew == (*xx)) nrerror("step size underflow in bsstep");
			mmid(ysav,dydx,nv,*xx,h,nseq[k],yseq,derivs);
			xest=SQR(h/nseq[k]);
			pzextr(k,xest,yseq,y,yerr,nv);
			if (k != 1) {
				errmax=TINY;
				for (i=1;i<=nv;i++) errmax=FMAX(errmax,fabs(yerr[i]/yscal[i]));
				errmax /= eps;
				km=k-1;
				err[km]=pow(errmax/SAFE1,1.0/(2*km+1));
			}
			if (k != 1 && (k >= kopt-1 || first)) {
				if (errmax < 1.0) {
					exitflag=1;
					break;
				}
				if (k == kmax || k == kopt+1) {
					red=SAFE2/err[km];
					break;
				}
				else if (k == kopt && alf[kopt-1][kopt] < err[km]) {
						red=1.0/err[km];
						break;
					}
				else if (kopt == kmax && alf[km][kmax-1] < err[km]) {
						red=alf[km][kmax-1]*SAFE2/err[km];
						break;
					}
				else if (alf[km][kopt] < err[km]) {
					red=alf[km][kopt-1]/err[km];
					break;
				}
			}
		}
		if (exitflag) break;
		red=FMIN(red,REDMIN);
		red=FMAX(red,REDMAX);
		h *= red;
		reduct=1;
	}
	*xx=xnew;
	*hdid=h;
	first=0;
	wrkmin=1.0e35;
	for (kk=1;kk<=km;kk++) {
		fact=FMAX(err[kk],SCALMX);
		work=fact*a[kk+1];
		if (work < wrkmin) {
			scale=fact;
			wrkmin=work;
			kopt=kk+1;
		}
	}
	*hnext=h/scale;
	if (kopt >= k && kopt != kmax && !reduct) {
		fact=FMAX(scale/alf[kopt-1][kopt],SCALMX);
		if (a[kopt+1]*fact <= wrkmin) {
			*hnext=h/fact;
			kopt++;
		}
	}
	free_vector(yseq,1,nv);
	free_vector(ysav,1,nv);
	free_vector(yerr,1,nv);
	free_vector(x,1,KMAXX);
	free_vector(err,1,KMAXX);
	free_matrix(d,1,KMAXX,1,KMAXX);
}
Пример #26
0
/*======== void parse_file () ==========
Inputs:   char * filename 
          struct matrix * transform, 
          struct matrix * pm,
          screen s
Returns: 
Goes through the file named filename and performs all of the actions listed in that file.
The file follows the following format:
     Every command is a single character that takes up a line
     Any command that requires arguments must have those arguments in the second line.
     The commands are as follows:
         line: add a line to the edge matrix - 
	     takes 6 arguemnts (x0, y0, z0, x1, y1, z1)
	      circle: add a circle to the edge matrix - 
	          takes 3 arguments (cx, cy, r)
		   hermite: add a hermite curve to the edge matrix -
		       takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3)
		        bezier: add a bezier curve to the edge matrix -
			    takes 8 arguments (x0, y0, x1, y1, x2, y2, x3, y3)
         sphere: add a sphere to the edge matrix - 
	     takes 3 arguemnts (cx, cy, r)
         torus: add a torus to the edge matrix - 
	     takes 4 arguemnts (cx, cy, r1, r2)
         box: add a rectangular prism to the edge matrix - 
	     takes 6 arguemnts (x, y, z, width, height, depth)
	      clear: clear the currnt edge matrix -
	          takes 0 arguments
		   ident: set the transform matrix to the identity matrix - 
		    scale: create a scale matrix, 
		        then multiply the transform matrix by the scale matrix - 
			    takes 3 arguments (sx, sy, sz)
			     translate: create a translation matrix, 
			         then multiply the transform matrix by the translation matrix - 
				     takes 3 arguments (tx, ty, tz)
				      xrotate: create an x-axis rotation matrix,
				          then multiply the transform matrix by the rotation matrix -
					      takes 1 argument (theta)
					       yrotate: create an y-axis rotation matrix,
					           then multiply the transform matrix by the rotation matrix -
						       takes 1 argument (theta)
						        zrotate: create an z-axis rotation matrix,
							    then multiply the transform matrix by the rotation matrix -
							        takes 1 argument (theta)
								 apply: apply the current transformation matrix to the 
								     edge matrix
								      display: draw the lines of the edge matrix to the screen
								          display the screen
									   save: draw the lines of the edge matrix to the screen
									       save the screen to a file -
									           takes 1 argument (file name)
										    quit: end parsing
See the file script for an example of the file format
IMPORTANT MATH NOTE:
the trig functions int math.h use radian mesure, but us normal
humans use degrees, so the file will contain degrees for rotations,
be sure to conver those degrees to radians (M_PI is the constant
for PI)
====================*/
void parse_file ( char * filename, 
                  struct matrix * transform, 
                  struct matrix * pm,
                  screen s) {

  FILE *f;
  char line[256];
  struct matrix * tmp;
  double angle;
  color g;

  g.red = 0;
  g.green = 255;
  g.blue = 0;
  
  clear_screen(s);

  if ( strcmp(filename, "stdin") == 0 ) 
    f = stdin;
  else
    f = fopen(filename, "r");
  
  while ( fgets(line, 255, f) != NULL ) {
    line[strlen(line)-1]='\0';
    //printf(":%s:\n",line);
    double x, y, z, x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4;
   
    
    if ( strncmp(line, "line", strlen(line)) == 0 ) {
      //      printf("LINE!\n");
      fgets(line, 255, f);
      //      printf("\t%s", line);
      //line[strlen(line)-1]='\0';
      sscanf(line, "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &x1, &y1, &z1);
      add_edge(pm, x, y, z, x1, y1, z1);
      // printf( "%lf %lf %lf %lf %lf %lf\n", x, y, z, x1, y1, z1);
    }
    else if ( strncmp(line, "circle", strlen(line)) == 0 ) {
      //printf("CIRCLE\n");
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      add_circle(pm, x, y, z, 0.01);
      //printf( "%lf %lf %lf\n", x, y, z);
    }    
    else if ( strncmp(line, "bezier", strlen(line)) == 0 ) {
      //printf("BEZIER\n");
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf",
	     &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
      add_curve(pm, x1, y1, x2, y2, x3, y3, x4, y4, 0.01, BEZIER_MODE );
      //printf( "%lf %lf %lf\n", x, y, z);
    }    
    else if ( strncmp(line, "hermite", strlen(line)) == 0 ) {
      //printf("HERMITE\n");
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf",
	     &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
      add_curve(pm, x1, y1, x2, y2, x3, y3, x4, y4, 0.01, HERMITE_MODE );
      //printf( "%lf %lf %lf\n", x, y, z);
    }
    else if ( strncmp(line, "box", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf %lf %lf", &x, &y, &z, &x1, &y1, &z1);
      add_box(pm, x, y, z, x1, y1, z1);
      // printf( "%lf %lf %lf %lf %lf %lf\n", x, y, z, x1, y1, z1);
    }
    else if (strncmp(line, "sphere", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      add_sphere(pm, x, y, z, 1);
      //printf( "%lf %lf %lf\n", x, y, z);
    }
    else if (strncmp(line, "torus", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      sscanf(line, "%lf %lf %lf %lf", &x, &y, &z, &z1);
      add_torus(pm, x, y, z, z1, 1);
      //printf( "%lf %lf %lf\n", x, y, z);
    }
    else if ( strncmp(line, "scale", strlen(line)) == 0 ) {
      //printf("SCALE\n");
      fgets(line, 255, f);
      //line[strlen(line)-1]='\0';      
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      tmp = make_scale(x, y, z);
      matrix_mult(tmp, transform);
      //print_matrix(transform);
    }
    else if ( strncmp(line, "translate", strlen(line)) == 0 ) {
      //printf("TRANSLATE\n");
      fgets(line, 255, f);
      //      line[strlen(line)-1]='\0';      
      sscanf(line, "%lf %lf %lf", &x, &y, &z);
      tmp = make_translate(x, y, z);
      matrix_mult(tmp, transform);
      //print_matrix(transform);
    }
    else if ( strncmp(line, "xrotate", strlen(line)) == 0 ) {
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotX( angle);
      matrix_mult(tmp, transform);
    }
    else if ( strncmp(line, "yrotate", strlen(line)) == 0 ) {
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotY( angle);
      matrix_mult(tmp, transform);
    }
    else if ( strncmp(line, "zrotate", strlen(line)) == 0 ) {
      //printf("ROTATE!\n");
      fgets(line, 255, f);
      sscanf(line, "%lf", &angle);
      angle = angle * (M_PI / 180);
      tmp = make_rotZ( angle);
      matrix_mult(tmp, transform);
    }
    else if ( strncmp(line, "ident", strlen(line)) == 0 ) {
      ident(transform);
    }
    else if ( strncmp(line, "apply", strlen(line)) == 0 ) {
      //printf("APPLY!\n");
      //print_matrix( transform );
      //      print_matrix(pm);
      matrix_mult(transform, pm);
    }
    else if ( strncmp(line, "display", strlen(line)) == 0 ) {
      clear_screen(s);
      draw_polygons(pm, s, g);
      //printf("THE ISSUE IS HERE\n");
      //display(s);
      //printf("ISSUE AVERTED\n");
      //
      //
      //so i have been having repeated issue with imagemagik and thus display doesnt work, so i test by saving as a png
      save_extension(s, "parser.png");
    }
    else if ( strncmp(line, "save", strlen(line)) == 0 ) {
      fgets(line, 255, f);
      // line[strlen(line)-1] = '\0';
      clear_screen(s);
      draw_polygons(pm, s, g);
      save_extension(s, line);
    }
    else if ( strncmp(line, "clear", strlen(line)) == 0 ) {
      pm->lastcol = 0;
    }
    else if ( strncmp(line, "quit", strlen(line)) == 0 ) {
      return;
    }
    else if ( line[0] != '#' ) {
      printf("Invalid command\n");
    }
  }
  
  free_matrix(tmp);
  fclose(f);
  //printf("END PARSE\n");
}
Пример #27
0
gmx_bool mrqmin(real x[], real y[], real sig[], int ndata, real a[],
                int ma, int lista[], int mfit,
                real **covar, real **alpha, real *chisq,
                void (*funcs)(real, real *, real *, real *),
                real *alamda)
{
    int          k, kk, j, ihit;
    static real *da, *atry, **oneda, *beta, ochisq;

    if (*alamda < 0.0)
    {
        oneda = matrix1(1, mfit, 1, 1);
        atry  = rvector(1, ma);
        da    = rvector(1, ma);
        beta  = rvector(1, ma);
        kk    = mfit+1;
        for (j = 1; j <= ma; j++)
        {
            ihit = 0;
            for (k = 1; k <= mfit; k++)
            {
                if (lista[k] == j)
                {
                    ihit++;
                }
            }
            if (ihit == 0)
            {
                lista[kk++] = j;
            }
            else if (ihit > 1)
            {
                nrerror("Bad LISTA permutation in MRQMIN-1", FALSE);
                return FALSE;
            }
        }
        if (kk != ma+1)
        {
            nrerror("Bad LISTA permutation in MRQMIN-2", FALSE);
            return FALSE;
        }
        *alamda = 0.001;
        mrqcof(x, y, sig, ndata, a, ma, lista, mfit, alpha, beta, chisq, funcs);
        ochisq = (*chisq);
    }
    for (j = 1; j <= mfit; j++)
    {
        for (k = 1; k <= mfit; k++)
        {
            covar[j][k] = alpha[j][k];
        }
        covar[j][j] = alpha[j][j]*(1.0+(*alamda));
        oneda[j][1] = beta[j];
    }
    if (!gaussj(covar, mfit, oneda, 1))
    {
        return FALSE;
    }
    for (j = 1; j <= mfit; j++)
    {
        da[j] = oneda[j][1];
    }
    if (*alamda == 0.0)
    {
        covsrt(covar, ma, lista, mfit);
        free_vector(beta, 1);
        free_vector(da, 1);
        free_vector(atry, 1);
        free_matrix(oneda, 1, mfit, 1);
        return TRUE;
    }
    for (j = 1; j <= ma; j++)
    {
        atry[j] = a[j];
    }
    for (j = 1; j <= mfit; j++)
    {
        atry[lista[j]] = a[lista[j]]+da[j];
    }
    mrqcof(x, y, sig, ndata, atry, ma, lista, mfit, covar, da, chisq, funcs);
    if (*chisq < ochisq)
    {
        *alamda *= 0.1;
        ochisq   = (*chisq);
        for (j = 1; j <= mfit; j++)
        {
            for (k = 1; k <= mfit; k++)
            {
                alpha[j][k] = covar[j][k];
            }
            beta[j]     = da[j];
            a[lista[j]] = atry[lista[j]];
        }
    }
    else
    {
        *alamda *= 10.0;
        *chisq   = ochisq;
    }
    return TRUE;
}
Пример #28
0
Файл: main.c Проект: Xodion/CFD
/**
 * The main operation reads the configuration file, initializes the scenario and
 * contains the main loop. So here are the individual steps of the algorithm:
 *
 * - read the program configuration file using read_parameters()
 * - set up the matrices (arrays) needed using the matrix() command
 * - create the initial setup init_uvp(), init_flag(), output_uvp()
 * - perform the main loop
 * - trailer: destroy memory allocated and do some statistics
 *
 * The layout of the grid is decribed by the first figure below, the enumeration
 * of the whole grid is given by the second figure. All the unknowns corresond
 * to a two dimensional degree of freedom layout, so they are not stored in
 * arrays, but in a matrix.
 *
 * @image html grid.jpg
 *
 * @image html whole-grid.jpg
 *
 * Within the main loop the following big steps are done (for some of the
 * operations a definition is defined already within uvp.h):
 *
 * - calculate_dt() Determine the maximal time step size.
 * - boundaryvalues() Set the boundary values for the next time step.
 * - calculate_fg() Determine the values of F and G (diffusion and confection).
 *   This is the right hand side of the pressure equation and used later on for
 *   the time step transition.
 * - calculate_rs()
 * - Iterate the pressure poisson equation until the residual becomes smaller
 *   than eps or the maximal number of iterations is performed. Within the
 *   iteration loop the operation sor() is used.
 * - calculate_uv() Calculate the velocity at the next time step.
 */
int main(int argn, char** args)
{
    double **U, **V, **P, **R, **F, **G;
    double t = 0.0;
    double t_end, xlength, ylength, tau, omg, alpha, eps, Re, GX, GY, PI, UI, VI, dx, dy, dt, res, dt_value;
    int n, imax, jmax, itermax, it, i, outputCount;
    double nextOutput;
    bool outputSpecified = false;

    char* paraviewOutput = "./Paraview/cavity100";
    char* inputFile = "./cavity100.dat";

    /* statistics */
    int sumIter, maxIter, minIter;
    double minTimeStep, maxTimestep;
    clock_t begin, end;
    double time_spent;
    sumIter = 0;
    maxIter = 0;
    maxTimestep = 0;


    begin = clock();

    /* Parse command line arguments */
    if (argn > 2)
    {
        for (i = 1; i < argn; i++)
        {
            if (strcmp(args[i], "-i") == 0)
            {
                inputFile = args[i + 1];
                if (!outputSpecified)
                    paraviewOutput = "./Paraview/sim";
            }

            if (strcmp(args[i], "-o") == 0)
            {
                paraviewOutput = args[i + 1];
                outputSpecified = true;
            }


        }
    }
    else if (argn == 2)
    {
        /* input file is the single argument besides fctn-name */
        inputFile = args[1];
    }

    /* Initialization */
    read_parameters(inputFile, &Re, &UI, &VI, &PI, &GX, &GY, &t_end, &xlength, &ylength, &dt, &dx, &dy, &imax, &jmax, &alpha, &omg, &tau, &itermax, &eps, &dt_value);
    U = matrix(0, imax, 0, jmax + 1);
    V = matrix(0, imax + 1, 0, jmax);
    P = matrix(0, imax + 1, 0, jmax + 1);
    R = matrix(0, imax + 1, 0, jmax + 1);
    F = matrix(0, imax, 0, jmax);
    G = matrix(0, imax, 0, jmax);
    n = 0;
    nextOutput = dt_value;


    init_uvp(UI, VI, PI, imax, jmax, U, V, P);
    minIter = itermax;
    minTimeStep = t_end;
    write_vtkFile(paraviewOutput,0,xlength,ylength,imax,jmax,dx,dy,U,V,P);
    outputCount = 1;
    while (t < t_end)
    {
        calculate_dt(Re, tau, &dt, dx, dy, imax, jmax, U, V);
        if (dt < minTimeStep)
            minTimeStep = dt;
        if (dt > maxTimestep)
            maxTimestep = dt;
        boundaryvalues(imax, jmax, U, V);
        calculate_fg(Re, GX, GY, alpha, dt, dy, dy, imax, jmax, U, V, F, G);
        calculate_rs(dt, dx, dy, imax, jmax, F, G, R);
        it = 0;
        while(++it < itermax)
        {
            sor(omg, dx, dy, imax, jmax, P, R, &res);
            if (res <= eps)
                break;
        }
        if (res > eps)
            fprintf(stderr, "WARNING: SOR did not converge in timestep %d, residual: %f\n", n + 1, res);
        if (it > maxIter)
            maxIter = it;
        if (it < minIter)
            minIter = it;
        sumIter += it;
        calculate_uv(dt, dx, dy, imax, jmax, U, V, F, G, P);
        t = t + dt;
        n++;
        if (t >= nextOutput)
        {
            write_vtkFile(paraviewOutput,outputCount,xlength,ylength,imax,jmax,dx,dy,U,V,P);
            nextOutput += dt_value;
            outputCount++;
        }

    }
    end = clock();
    time_spent = (double) (end - begin) / CLOCKS_PER_SEC;

    /* print statistics */
    printf("Simulation took %f seconds\n", time_spent);
    printf("Number of timesteps: %d\n", n);
    printf("Min. timestep: %f     Max. timestep: %f    Avg. timestep: %f\n", minTimeStep, maxTimestep, t_end/n);
    printf("Min. # iterations: %d     Max. # iterations: %d     Avg: %f\n", minIter, maxIter, sumIter/(double) n);

    /* Free memory */
    free_matrix(U, 0, imax, 0, jmax + 1);
    free_matrix(V, 0, imax + 1, 0, jmax);
    free_matrix(P, 0, imax + 1, 0, jmax + 1);
    free_matrix(R, 0, imax, 0 ,jmax);
    free_matrix(F, 0, imax, 0, jmax);
    free_matrix(G, 0, imax, 0, jmax);


    return 0;
}
Пример #29
0
/*======== void my_main() ==========
  Inputs:   int polygons  
  Returns: 

  This is the main engine of the interpreter, it should
  handle most of the commadns in mdl.

  If frames is not present in the source (and therefore 
  num_frames is 1, then process_knobs should be called.

  If frames is present, the enitre op array must be
  applied frames time. At the end of each frame iteration
  save the current screen to a file named the
  provided basename plus a numeric string such that the
  files will be listed in order, then clear the screen and
  reset any other data structures that need it.

  Important note: you cannot just name your files in 
  regular sequence, like pic0, pic1, pic2, pic3... if that
  is done, then pic1, pic10, pic11... will come before pic2
  and so on. In order to keep things clear, add leading 0s
  to the numeric portion of the name. If you use sprintf, 
  you can use "%0xd" for this purpose. It will add at most
  x 0s in front of a number, if needed, so if used correctly,
  and x = 4, you would get numbers like 0001, 0002, 0011,
  0487

  05/17/12 09:41:35
  jdyrlandweaver
  ====================*/
void my_main( int polygons ) {

    int i, f, j, x;
    double step;
    double xval, yval, zval, knob_value;
    struct matrix *transform;
    struct matrix *tmp;
    struct stack *s;
    struct vary_node ** knobs;
    struct vary_node * link;
    screen t;
    color g;
    char q;
    
    num_frames = 1;
    step = 0.05;
    
    g.red = 0;
    g.green = 255;
    g.blue = 255;
    
    s = new_stack();
    tmp = new_matrix(4, 1000);
    clear_screen( t );
    
    first_pass();
    
    if(num_frames > 1)
        knobs = second_pass();
    
    int variables;
    
    for(variables = 0; variables < num_frames; variables++){
        s = new_stack();
        tmp = new_matrix(4,1000);
        clear_screen(t);
        
        for (j = 0; j < lastsym; j++){
            if(symtab[j].type == SYM_VALUE){
                link = knobs[variables];
                while (strcmp(link->name, symtab[j].name) != 0){
                    link = link->next;
                }
                if (link){
                    (&symtab[j])->s.value = link->value;
                }
            }
        }
        for (i=0;i<lastop;i++) {
            
            switch (op[i].opcode) {
                    
                case SET:
                    x = op[i].op.set.p->s.value;
                    set_value(lookup_symbol(op[i].op.set.p->name),x);
                    break;
                    
                case SETKNOBS:
                    x = op[i].op.setknobs.value;
                    for(j = 0; j < lastsym; j++){
                        if(symtab[j].type == SYM_VALUE){
                            set_value(&(symtab[j]), x);
                        }
                    }
                    
                case SPHERE:
                    add_sphere( tmp,op[i].op.sphere.d[0], //cx
                               op[i].op.sphere.d[1],  //cy
                               op[i].op.sphere.d[2],  //cz
                               op[i].op.sphere.r,
                               step);
                    //apply the current top origin
                    matrix_mult( s->data[ s->top ], tmp );
                    draw_polygons( tmp, t, g );
                    tmp->lastcol = 0;
                    break;
                    
                case TORUS:
                    add_torus( tmp, op[i].op.torus.d[0], //cx
                              op[i].op.torus.d[1],     //cy
                              op[i].op.torus.d[2],    //cz
                              op[i].op.torus.r0,
                              op[i].op.torus.r1,
                              step);
                    matrix_mult( s->data[ s->top ], tmp );
                    draw_polygons( tmp, t, g );
                    tmp->lastcol = 0;
                    break;
                    
                case BOX:
                    add_box( tmp, op[i].op.box.d0[0],
                            op[i].op.box.d0[1],
                            op[i].op.box.d0[2],
                            op[i].op.box.d1[0],
                            op[i].op.box.d1[1],
                            op[i].op.box.d1[2]);
                    matrix_mult( s->data[ s->top ], tmp );
                    draw_polygons( tmp, t, g );
                    tmp->lastcol = 0;
                    break;
                    
                case LINE:
                    add_edge( tmp, op[i].op.line.p0[0],
                             op[i].op.line.p0[1],
                             op[i].op.line.p0[1],
                             op[i].op.line.p1[0],
                             op[i].op.line.p1[1],
                             op[i].op.line.p1[1]);
                    draw_lines( tmp, t, g );
                    tmp->lastcol = 0;
                    break;
                    
                case MOVE:
                    //get the factors
                    xval = op[i].op.move.d[0];
                    yval =  op[i].op.move.d[1];
                    zval = op[i].op.move.d[2];
                  
                    if(op[i].op.scale.p){
                        SYMTAB * variable = (lookup_symbol(op[i].op.move.p->name));
                        xval = xval * variable->s.value;
                        yval = yval * variable->s.value;
                        zval = zval * variable->s.value;
                    }
                    
                    transform = make_translate( xval, yval, zval );
                    //multiply by the existing origin
                    matrix_mult( s->data[ s->top ], transform );
                    //put the new matrix on the top
                    copy_matrix( transform, s->data[ s->top ] );
                    free_matrix( transform );
                    break;
                    
                case SCALE:
                    xval = op[i].op.scale.d[0];
                    yval = op[i].op.scale.d[1];
                    zval = op[i].op.scale.d[2];
                  
                    if(op[i].op.scale.p){
                        SYMTAB * variable = (lookup_symbol(op[i].op.move.p->name));
                        xval = xval * variable->s.value;
                        yval = yval * variable->s.value;
                        zval = zval * variable->s.value;
                    }

                    
                    transform = make_scale( xval, yval, zval );
                    matrix_mult( s->data[ s->top ], transform );
                    //put the new matrix on the top
                    copy_matrix( transform, s->data[ s->top ] );
                    free_matrix( transform );
                    break;
                    
                case ROTATE:
                    xval = op[i].op.rotate.degrees * ( M_PI / 180 );
                    
                    if(op[i].op.scale.p){
                        SYMTAB * variable = (lookup_symbol(op[i].op.move.p->name));
                        xval = xval * variable->s.value;
                    }                    

                    //get the axis
                    if ( op[i].op.rotate.axis == 0 )
                        transform = make_rotX( xval );
                    else if ( op[i].op.rotate.axis == 1 )
                        transform = make_rotY( xval );
                    else if ( op[i].op.rotate.axis == 2 )
                        transform = make_rotZ( xval );
                    
                    matrix_mult( s->data[ s->top ], transform );
                    //put the new matrix on the top
                    copy_matrix( transform, s->data[ s->top ] );
                    free_matrix( transform );
                    break;
                    
                case PUSH:
                    push( s );
                    break;
                case POP:
                    pop( s );
                    break;
                case SAVE:
                    save_extension( t, op[i].op.save.p->name );
                    break;
                case DISPLAY:
                    display( t );
                    break;
            }
        }
        char dname[256];
        char index[256];
        
        strcpy(dname, "animations/");
        strcat(dname, name);
        sprintf(index, "%03d", variables);
        strcat(dname, index);
        strcat(dname, ".png");
        save_extension(t, dname);
        printf("saved %s\n", dname);
        
    }
  
  free_stack( s );
  free_matrix( tmp );
  //free_matrix( transform );    
}
Пример #30
0
int main(int argc, char * argv[])
{
	// First, we initialize MPI
	int rank, nb_nodes;
	int return_code;
	return_code = MPI_Init(&argc, &argv);
	if(return_code != MPI_SUCCESS) {
		printf("Fail to initialize MPI\n");
		MPI_Abort(MPI_COMM_WORLD, return_code);
	}
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	MPI_Comm_size(MPI_COMM_WORLD, &nb_nodes);

	// Check the arguments
	if(!rank && argc != 4) {
		printf("Usage: %s <N> <init-value> <error>", argv[0]);
		MPI_Abort(MPI_COMM_WORLD, 1);
	}

	// Setup arguments (number of columns, initial value, error tolerance)
	// n et m are the dimension of the subdomains, we keep the size of the global matrix in N
	int n = atoi(argv[1]);
	int N = n;
	int m = n;
	n = (n-2)/nb_nodes + 2;
	double w = atof(argv[2]);
	double e = atof(argv[3]);
	
	// Check that p divides N-2. Why '-2' because we don't care of the top and bottom lines of 0
	if(!rank && (N-2) % nb_nodes != 0) {
		printf("The number of processors must divide the size of the matrix - 2\n");
		MPI_Abort(MPI_COMM_WORLD, 1);
	}

	// Compute matrices
	double ** prev_m = NULL;
	double ** new_m = init_matrix(n, m, w, rank, nb_nodes);

	// Local and global error
	double it_error = 0.0;
	double global_error = 0.0;

	int itnb = 0;
	do {
		itnb++;
		if(prev_m != NULL)
			free_matrix(prev_m, n);

		prev_m = new_m;
		new_m = init_matrix(n, m, w, rank, nb_nodes);
		compute(prev_m, new_m, n, m);
		exchange_halo(new_m, n, m, rank, nb_nodes);

		/* compute_red(new_m, n, m); */
		/* exchange_red(new_m, n, m, rank, nb_nodes); */
		/* compute_black(new_m, n, m); */
		/* exchange_black(new_m, n, m, rank, nb_nodes); */

		// Every 30 iterations we check the convergence
		if(itnb % 30 == 0) {
			it_error = error(prev_m, new_m, n, m);
			MPI_Reduce(&it_error, &global_error, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
			MPI_Bcast(&global_error, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
			if(global_error <= e)
				break;
		}
	} while(1);

	// We need to gather all the data to node 0
	// Number of lines - halo data * number of columns
	int send_size = (n-2) * m;
	int result_size = send_size * nb_nodes;
	double * send = (double*)malloc(sizeof(double) * send_size);
	double * result;
	if(!rank) {
		printf("Iterations number: %d\n", itnb);
		result = (double *)malloc(sizeof(double) * result_size);
	}

	// Some DEBUG prints
	/* printf("End partial matrix of %d\n", rank); */
	/* print_matrix(new_m, n, m); */

	for(int i = 1; i < n-1; i++)
		for(int j = 0; j < m; j++)
			send[(i-1)*m+j] = new_m[i][j];

	MPI_Barrier(MPI_COMM_WORLD);
	MPI_Gather(send, send_size, MPI_DOUBLE, result, send_size, MPI_DOUBLE, 0, MPI_COMM_WORLD);
	free(send);

	// The node 0 builds the global matrix and print the data
	if(!rank) {
		/* printf("Result\n"); */
		/* print_array(result, result_size); */
		double ** global_matrix = init_matrix_from_array(result, N);
		free(result);
		print_data_matrix(argv[0], nb_nodes, global_matrix, N);
	}

	MPI_Barrier(MPI_COMM_WORLD);
	MPI_Finalize();
	return 0;
}