Exemplo n.º 1
0
int cFileData::getPointColorData(std::vector<float> *vertex, std::vector<GLubyte> *color) {
    cDataFieldT<vtkPoint>* df_p =
        static_cast<cDataFieldT<vtkPoint>*>(getDatafield("POINTS"));
    if (!df_p)
        return 0;
    cDataFieldT<float>* df_a =
        static_cast<cDataFieldT<float>*>(getDatafield("altitude"));
    if (!df_a)
        return 0;
    cDataFieldT<unsigned char>* df_d =
        static_cast<cDataFieldT<unsigned char>*>(getDatafield("detection"));
    if (!df_d)
        return 0;

    int pos = 0;
    vertex->reserve(df_p->numEntries()*3);
    float scaleFac = 5.0*(float)WORLD_SPHERE_RADIUS/EARTH_RADIUS;
    for (int i=0; i < df_p->numEntries(); ++i) {
        switch(df_d->getValueAt(i)) {
        case 0:
            color->push_back(GLubyte(255));
            color->push_back(GLubyte(255));
            color->push_back(GLubyte(178));
            break;
        case 1:
            color->push_back(GLubyte(254));
            color->push_back(GLubyte(204));
            color->push_back(GLubyte(92));
            break;
        case 2:
            color->push_back(GLubyte(253));
            color->push_back(GLubyte(141));
            color->push_back(GLubyte(60));
            break;
        case 4:
            color->push_back(GLubyte(227));
            color->push_back(GLubyte(26));
            color->push_back(GLubyte(28));
            break;
        }
        vtkPoint p = df_p->getValueAt(i);
        float a = df_a->getValueAt(i)*scaleFac;
        vertex->push_back((WORLD_SPHERE_RADIUS+a)*sin(THETA(p.y))*sin(PHI(p.x)));
        vertex->push_back((WORLD_SPHERE_RADIUS+a)*cos(THETA(p.y)));
        vertex->push_back((WORLD_SPHERE_RADIUS+a)*sin(THETA(p.y))*cos(PHI(p.x)));
        pos+=3;
    }
    return pos;
}
Exemplo n.º 2
0
int noekeon_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
#endif
{
   ulong32 a,b,c,d, temp;
   int r;

   LTC_ARGCHK(skey != NULL);
   LTC_ARGCHK(pt   != NULL);
   LTC_ARGCHK(ct   != NULL);

   LOAD32H(a,&ct[0]); LOAD32H(b,&ct[4]);
   LOAD32H(c,&ct[8]); LOAD32H(d,&ct[12]);


#define ROUND(i) \
       THETA(skey->noekeon.dK, a,b,c,d); \
       a ^= RC[i]; \
       PI1(a,b,c,d); \
       GAMMA(a,b,c,d); \
       PI2(a,b,c,d);

   for (r = 16; r > 0; --r) {
       ROUND(r);
   }

#undef ROUND

   THETA(skey->noekeon.dK, a,b,c,d);
   a ^= RC[0];
   STORE32H(a,&pt[0]); STORE32H(b, &pt[4]);
   STORE32H(c,&pt[8]); STORE32H(d, &pt[12]);
   return CRYPT_OK;
}
Exemplo n.º 3
0
void noekeon_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *key)
#endif
{
   unsigned long a,b,c,d,temp;
   int r;

   _ARGCHK(key != NULL);
   _ARGCHK(pt != NULL);
   _ARGCHK(ct != NULL);
   
   LOAD32L(a,&pt[0]); LOAD32L(b,&pt[4]);
   LOAD32L(c,&pt[8]); LOAD32L(d,&pt[12]);
   
#define ROUND(i) \
       a ^= RC[r+i]; \
       THETA(key->noekeon.K, a,b,c,d); \
       PI1(a,b,c,d); \
       GAMMA(a,b,c,d); \
       PI2(a,b,c,d);

   for (r = 0; r < 16; r += 2) {
       ROUND(0);
       ROUND(1);
   }

#undef ROUND

   a ^= RC[16];
   THETA(key->noekeon.K, a, b, c, d);
   
   STORE32L(a,&ct[0]); STORE32L(b,&ct[4]);
   STORE32L(c,&ct[8]); STORE32L(d,&ct[12]);
}
Exemplo n.º 4
0
int noekeon_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
{
   unsigned long temp;
   
   _ARGCHK(key != NULL);
   _ARGCHK(skey != NULL);
   
   if (keylen != 16) {
      return CRYPT_INVALID_KEYSIZE;
   }
   
   if (num_rounds != 16 && num_rounds != 0) {
      return CRYPT_INVALID_ROUNDS;
   }
   
   LOAD32L(skey->noekeon.K[0],&key[0]);
   LOAD32L(skey->noekeon.K[1],&key[4]);
   LOAD32L(skey->noekeon.K[2],&key[8]);
   LOAD32L(skey->noekeon.K[3],&key[12]);
   
   LOAD32L(skey->noekeon.dK[0],&key[0]);
   LOAD32L(skey->noekeon.dK[1],&key[4]);
   LOAD32L(skey->noekeon.dK[2],&key[8]);
   LOAD32L(skey->noekeon.dK[3],&key[12]);

   THETA(zero, skey->noekeon.dK[0], skey->noekeon.dK[1], skey->noekeon.dK[2], skey->noekeon.dK[3]);

   return CRYPT_OK;
}
Exemplo n.º 5
0
void noekeon_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
#endif
{
   ulong32 a,b,c,d,temp;
   int r;

   LTC_ARGCHK(skey != NULL);
   LTC_ARGCHK(pt   != NULL);
   LTC_ARGCHK(ct   != NULL);

   LOAD32H(a,&pt[0]); LOAD32H(b,&pt[4]);
   LOAD32H(c,&pt[8]); LOAD32H(d,&pt[12]);

#define ROUND(i) \
       a ^= RC[i]; \
       THETA(skey->noekeon.K, a,b,c,d); \
       PI1(a,b,c,d); \
       GAMMA(a,b,c,d); \
       PI2(a,b,c,d);

   for (r = 0; r < 16; ++r) {
       ROUND(r);
   }

#undef ROUND

   a ^= RC[16];
   THETA(skey->noekeon.K, a, b, c, d);

   STORE32H(a,&ct[0]); STORE32H(b,&ct[4]);
   STORE32H(c,&ct[8]); STORE32H(d,&ct[12]);
}
Exemplo n.º 6
0
//to get the gernike moments of order p and repetition q
double* zernike::CalculateZernike(int p, int q )
{
	double * V = (double*) malloc (2* sizeof(double ));
	V[0]=0.0;V[1]=0.0;
	double** ro = RHO() ;
	double** theta = THETA();	
	int s = (p-abs(q))/2;
	for(int i =0; i<M;i++)
	{
		for(int j=0;j<N;j++)
		{
			double temp = 0.0;
			if(ro[i][j]<=1.0)
			{
				for(int k = 0 ; k<=s;k++)
				{
					temp += B(p,q,k)*pow(ro[i][j],p-2*k);
				}
				V[0] +=temp*cos(theta[i][j]*q)*f[i][j];
				V[1] -=temp*sin(theta[i][j]*q)*f[i][j];
			}
			else
			{
				V[0] += 0.0;
				V[0] += 0.0;
			}
		}
	}
	double  b = G00();
	V[0] = V[0]*(p+1)/(3.14259265*b);
	V[1] = V[1]*(p+1)/(3.14259265*b);
	free(ro);
	free(theta);
	return V;
}
Exemplo n.º 7
0
GLuint cFileData::getDisplayList() {
    cDataFieldT<vtkPoint>* df_p =
        static_cast<cDataFieldT<vtkPoint>*>(getDatafield("POINTS"));
    if (!df_p)
        return 0;
    cDataFieldT<float>* df_a =
        static_cast<cDataFieldT<float>*>(getDatafield("altitude"));
    if (!df_a)
        return 0;
    cDataFieldT<unsigned char>* df_d =
        static_cast<cDataFieldT<unsigned char>*>(getDatafield("detection"));
    if (!df_d)
        return 0;
    GLuint n;
    glNewList(n, GL_COMPILE);
    GLUquadricObj *gSphere = gluNewQuadric();
    gluQuadricNormals(gSphere, GLU_SMOOTH);
    float mat_emission_detection4[4] = {0.8f, 0.2f, 0.2f, 0.0f};
    float mat_emission[4] = {0.2f, 0.2f, 0.8f, 0.0f};
    float scaleFac = WORLD_SPHERE_RADIUS/EARTH_RADIUS;
    glEnable(GL_LIGHTING);
    for (int i=0; i < df_p->numEntries(); ++i) {
        vtkPoint p = df_p->getValueAt(i);
        float a = df_a->getValueAt(i)*scaleFac;
        if (df_d->getValueAt(i) == 4)
            glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_emission_detection4);
        else
            glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_emission);
        glPushMatrix();
        glTranslatef((WORLD_SPHERE_RADIUS+a)*sin(THETA(p.y))*sin(PHI(p.x)),
                     (WORLD_SPHERE_RADIUS+a)*cos(THETA(p.y)),
                     (WORLD_SPHERE_RADIUS+a)*sin(THETA(p.y))*cos(PHI(p.x)));
        gluSphere(gSphere, 0.1f, 6, 6);
        glPopMatrix();
    }
    glEnable(GL_LIGHTING);
    gluDeleteQuadric(gSphere);
    glEndList();

    return n;
}
Exemplo n.º 8
0
int cFileData::getPointData(std::vector<float> *vertex) {
    cDataFieldT<vtkPoint>* df_p =
        static_cast<cDataFieldT<vtkPoint>*>(getDatafield("POINTS"));
    if (!df_p)
        return 0;
    cDataFieldT<float>* df_a =
        static_cast<cDataFieldT<float>*>(getDatafield("altitude"));
    if (!df_a)
        return 0;
    int pos = 0;
    vertex->reserve(df_p->numEntries()*3);
    float scaleFac = 5.0*(float)WORLD_SPHERE_RADIUS/EARTH_RADIUS;
    for (int i=0; i < df_p->numEntries(); ++i) {
        vtkPoint p = df_p->getValueAt(i);
        float a = df_a->getValueAt(i)*scaleFac;
        vertex->push_back((WORLD_SPHERE_RADIUS+a)*sin(THETA(p.y))*sin(PHI(p.x)));
        vertex->push_back((WORLD_SPHERE_RADIUS+a)*cos(THETA(p.y)));
        vertex->push_back((WORLD_SPHERE_RADIUS+a)*sin(THETA(p.y))*cos(PHI(p.x)));
        pos+=3;
    }
    return pos;
}
Exemplo n.º 9
0
/*
  input: alpha:   k*dx (wavenumber * grid spacing)
         points:  points to evaluate bessles at
         npoints: number of points in points
	 M:       highest order bessel function to use

  output: return value: matrix A where
          A[i][j] = J_{j'}(alpha*r_i) /  * f(j'*\theta_i) where
	    0 <= i < npoints
	    0 <= j <= M
	    j' = j     if j <= M
	         j - M if j > M
	    f = 1   if j = 0
	        sin if 1 <= j <= M
	        cos if j > M
 */
gsl_matrix *bessel_matrix(double alpha, point *points, int npoints, int M, double r_typical) {
  gsl_matrix *out = gsl_matrix_alloc(npoints, 2*M+1);
  int i,j;
  double x, y, r, theta;

  double column_scale;

  for (i = 0 ; i < npoints ; i++) { // loop over rows
    x = points[i].x;
    y = points[i].y;
    r = R(x, y);
    theta = THETA(x,y);

    // loops over columns
    gsl_matrix_set(out, i, 0, gsl_sf_bessel_J0(alpha * r) / gsl_sf_bessel_J0(alpha * r_typical));
    for (j = 1 ; j <= M ; j++) {
      column_scale = gsl_sf_bessel_Jn(j, alpha * r_typical);
      gsl_matrix_set(out, i, j, gsl_sf_bessel_Jn(j, alpha * r) * sin(j * theta) / column_scale);
      gsl_matrix_set(out, i, j+M, gsl_sf_bessel_Jn(j, alpha * r) * cos(j * theta) / column_scale);
    }
  }

  return out;
}
Exemplo n.º 10
0
//============================================================================
void AAM_Basic::EstPoseGradientMatrix(CvMat* GPose, 
									  const CvMat* CParams,
									  const std::vector<AAM_Shape>& AllShapes,
									  const std::vector<IplImage*>& AllImages, 
									  const CvMat* vPoseDisps)
{
	int nExperiment = 0;
	int ntotalExp = AllShapes.size()*vPoseDisps->rows/2*vPoseDisps->cols;
    int npixels = __cam.__texture.nPixels();
	int npointsby2 = __cam.__shape.nPoints()*2;
	int smodes = __cam.__shape.nModes();
	CvMat c;									//appearance parameters
	CvMat* q = cvCreateMat(1, 4, CV_64FC1);		//pose parameters
	CvMat* q1 = cvCreateMat(1, 4, CV_64FC1);
	CvMat* q2 = cvCreateMat(1, 4, CV_64FC1);
	CvMat* p = cvCreateMat(1, smodes, CV_64FC1);//shape parameters
	CvMat* s1 = cvCreateMat(1, npointsby2, CV_64FC1);//shape vector
    CvMat* s2 = cvCreateMat(1, npointsby2, CV_64FC1);
    CvMat* t1 = cvCreateMat(1, npixels, CV_64FC1);//texture vector
    CvMat* t2 = cvCreateMat(1, npixels, CV_64FC1);
	CvMat* delta_g1 = cvCreateMat(1, npixels, CV_64FC1);
	CvMat* delta_g2 = cvCreateMat(1, npixels, CV_64FC1);
	CvMat* cDiff = cvCreateMat(1, npixels, CV_64FC1);
    std::vector<double> normFactors; normFactors.resize(4);
	CvMat* AbsPoseDisps = cvCreateMat(vPoseDisps->rows, vPoseDisps->cols, CV_64FC1);

	// for each training example in the training set
	for(int i = 0; i < AllShapes.size(); i++)
	{
		cvGetRow(CParams, &c, i);

		//calculate pose parameters
		AllShapes[i].Point2Mat(s1);
		__cam.__shape.CalcParams(s1, p, q);
		
		cvCopy(vPoseDisps, AbsPoseDisps);
		int w = AllShapes[i].GetWidth();
		int h = AllShapes[i].GetHeight();
		int W = AllImages[i]->width;
		int H = AllImages[i]->height;

		for(int j = 0; j < vPoseDisps->rows; j+=2)
		{
			//translate relative translation to abs translation about x & y
			CV_MAT_ELEM(*AbsPoseDisps, double, j, 2) *= w;
			CV_MAT_ELEM(*AbsPoseDisps, double, j, 3) *= h;
			CV_MAT_ELEM(*AbsPoseDisps, double, j+1, 2) *= w;
			CV_MAT_ELEM(*AbsPoseDisps, double, j+1, 3) *= h;

			for(int k = 0; k < vPoseDisps->cols; k++)
			{
				printf("Performing (%d/%d)\r", nExperiment++, ntotalExp);

				//shift current pose parameters 
				cvCopy(q, q1);
                cvCopy(q, q2);
				if(k == 0 || k == 1){
					double scale, theta, dscale1, dtheta1, dscale2, dtheta2;
					scale = MAG(cvmGet(q,0,0)+1,cvmGet(q,0,1));
					theta = THETA(cvmGet(q,0,0)+1,cvmGet(q,0,1));
					dscale1 = MAG(cvmGet(AbsPoseDisps,j,0)+1,cvmGet(AbsPoseDisps,j,1));
					dtheta1 = THETA(cvmGet(AbsPoseDisps,j,0)+1,cvmGet(AbsPoseDisps,j,1));
					dscale2 = MAG(cvmGet(AbsPoseDisps,j+1,0)+1,cvmGet(AbsPoseDisps,j+1,1));
					dtheta2 = THETA(cvmGet(AbsPoseDisps,j+1,0)+1,cvmGet(AbsPoseDisps,j+1,1));

					dscale1 = dscale1*scale;		dtheta1 += theta;
					dscale2 = dscale2*scale;		dtheta2 += theta;
					
					if(k == 0){
						cvmSet(q1,0,0,dscale1*cos(theta)-1);
						cvmSet(q1,0,1,dscale1*sin(theta));
						cvmSet(q2,0,0,dscale2*cos(theta)-1);
						cvmSet(q2,0,1,dscale2*sin(theta));
					}
					
					else{
						cvmSet(q1,0,0,scale*cos(dtheta1)-1);
						cvmSet(q1,0,1,scale*sin(dtheta1));
						cvmSet(q2,0,0,scale*cos(dtheta2)-1);
						cvmSet(q2,0,1,scale*sin(dtheta2));				
					}
				}
				
				else
				{
					cvmSet(q1,0,k,cvmGet(q,0,k)+cvmGet(AbsPoseDisps,j,k));
					cvmSet(q2,0,k,cvmGet(q,0,k)+cvmGet(AbsPoseDisps,j+1,k));
				}

				//generate model texture
				__cam.CalcTexture(t1, &c);
				__cam.CalcTexture(t2, &c);
//				{
//					char filename[100];
//					sprintf(filename, "a/%d.jpg", nExperiment);
//					__cam.__paw.SaveWarpImageFromVector(filename, t1);
//				}

				//generate model shape
				//__cam.__shape.CalcShape(p, q1, s1);
				//__cam.__shape.CalcShape(p, q2, s2);
				__cam.CalcLocalShape(s1, &c); __cam.__shape.CalcGlobalShape(q1,s1);
				__cam.CalcLocalShape(s2, &c); __cam.__shape.CalcGlobalShape(q2,s2);

				//sample the shape to get warped texture
				if(!AAM_Basic::IsShapeWithinImage(s1, W, H)) cvZero(delta_g1);
				else __cam.__paw.FasterGetWarpTextureFromMatShape(s1, AllImages[i],	delta_g1, true);
				__cam.__texture.AlignTextureToRef(__cam.__MeanG, delta_g1);
				
				if(!AAM_Basic::IsShapeWithinImage(s2, W, H)) cvZero(delta_g2);
				else __cam.__paw.FasterGetWarpTextureFromMatShape(s2, AllImages[i], delta_g2, true);
				__cam.__texture.AlignTextureToRef(__cam.__MeanG, delta_g2);
		
//				{
//					char filename[100];
//					sprintf(filename, "a/%d-.jpg", nExperiment);
//					__cam.__paw.SaveWarpImageFromVector(filename, delta_g1);
//					sprintf(filename, "a/%d+.jpg", nExperiment);
//					__cam.__paw.SaveWarpImageFromVector(filename, delta_g2);
//				}
				
				//calculate pixel difference(g_s - g_m)
				cvSub(delta_g1, t1, delta_g1);
				cvSub(delta_g2, t2, delta_g2);
				
				//form central displacement
				cvSub(delta_g2, delta_g1, cDiff);
				cvConvertScale(cDiff, cDiff, 1.0/(cvmGet(AbsPoseDisps,j+1,k)-cvmGet(AbsPoseDisps,j,k)));

				//accumulate into k-th row
				CvMat Gk; cvGetRow(GPose, &Gk, k);
				cvAdd(&Gk, cDiff, &Gk);

				//increment normalisation factor
				normFactors[k] = normFactors[k]+1;
			}
		}
	}

	//normalize
	for(int j = 0; j < vPoseDisps->cols; j++)
	{
		CvMat Gj; cvGetRow(GPose, &Gj, j);
		cvConvertScale(&Gj, &Gj, 1.0/normFactors[j]);
	}

	cvReleaseMat(&s1); cvReleaseMat(&s2);
	cvReleaseMat(&t1); cvReleaseMat(&t2);
	cvReleaseMat(&delta_g1); cvReleaseMat(&delta_g2);
	cvReleaseMat(&cDiff);
	cvReleaseMat(&AbsPoseDisps);
}
Exemplo n.º 11
0
int main(int argc, char **argv) {

#ifdef _OPENMP    		/* Compilation with OMP */
  int numthreads;
  numthreads = omp_get_max_threads();
  omp_set_num_threads(numthreads);
#endif  

  time_t t;   struct tm *tm;  t = time(NULL); tm = localtime(&t);
  if((argc >1) && (argv[1][1] == 'd')) {debug = 1; d_level = 1;} /* Initial debugging */

  srand(time(NULL));
  gsl_rng_env_setup();		/* Random generator initialization */
  gsl_rng_default_seed = rand()*RAND_MAX;
  sprintf(mesg,"Seed: %ld ",gsl_rng_default_seed);
  DEBUG(mesg);
  
  /* Declaration of variables */
  /* Contadores */
  int i, time, tr_TT = 0;
  int Nscan = 0;
  /* Others */
  int def = 1;			/* Default = 1 */
  int temporal_correction = 1;
  int total_spikes1 = 0, total_spikes2 = 0;

  double var_value;
  double *final_conf,  *final_conf2;

  /* Date variables */
  char day[100], hour[100];
  strftime(day, 100, "%m-%d-%Y",tm);
  sprintf(hour,"%d.%02d",tm->tm_hour,tm->tm_min);

  /* Data store */
  Create_Dir("results");
  FILE *file[8];
  
  /* System variables (magnitudes) */
  t_th *th;			/* neuron vector */
  double R = 0;			/* Kuramoto order parameter */

  double fr_volt[2];		/* Stores width and center of the Lorentzian distr. (R) */
  double fr_x;			/* Center of the Lorentzian distr. */
  double fr_y;			/* Width  " " " " */
  double perturbation = 0;

  double fr, fr2;		/* Mean field (firing rate) */
  double avg_fr1,avg2_fr1;
  int medida;
  double inst_fr_avg;
  int intervalo;
  int total_spikes_inst;

  double avg_v1 = 0, avg_v2 = 0;
  long double v1_center = 0, v2_center = 0;

  double dt, *p, phi = 0;

  double rh_final = 1, vh_final = 1; /* FR *** initial conds. for r and v ( FR equations) */

  t_data *d, *data;
  d = malloc(sizeof(*d));
  data = malloc(sizeof(*data));

  d->scan = 0;			/* Exploring is unabled by default */
  d->MaxDim = 5000000;		/* Raster plot will be disabled for higher dim */
  
  sprintf(d->file,"%s_%s",day,hour);
  sprintf(mesg2,"results/%s",d->file);
  Create_Dir(mesg2);
  Create_Dir("temp");
  sprintf(mesg2,"cp volt_avg.R ./temp");
  system(mesg2);

  /*********************************/
  /* Program arguments assignation */
  /*********************************/
  *data = Scan_Data(DATA_FILE,*d);
  d = data;

  while((argc--) != 1) {	/* Terminal arguments can be handled */
    *data = Arg(argv[argc], *d);
    d = data;
    if(argv[1][0] != '-') def = 0;
  }

#ifdef _OPENMP			/* Work is divided between the cores */
  int chunksize = d->N/numthreads;
  if(chunksize > 10) chunksize = 10;
#endif

  /* Initial tunning: step size, and scanning issues */
  Intro(d,&Nscan,&tr_TT);
  if(d_level == 4){ temporal_correction = 0; DEBUG("Temporal correction is OFF");}
  d->var_value = d->eta;
  d->scan_max = Nscan;
  d->pert = 0;

  if(d->scan_mode == 3) {
    d->pert = 1;
    d->scan_mode = 2;
  }
  double dTT = d->TT;
  double dTT2 = d->TT*2.0;

  /* Configuration at the end of simulation */
  final_conf  = (double*) malloc (d->N*sizeof(double));
  final_conf2 = (double*) malloc (d->N*sizeof(double));

  /**********************************/
  /* New simulations can start here */
  /**********************************/
  do {    
    if(d->scan_mode >= 1) 
      d = Var_update(d);
    Data_Files(&file,*d,0);
    Data_Files(&file,*d,4);
    total_spikes1 = 0;
    total_spikes2 = 0;
    
    /********************/
    /* Oscillator setup */
    /********************/
    th  = (t_th*) calloc (d->N,sizeof(t_th)); 
    for(i=0 ;i<d->N ;i++ ) {		/* The total number (N) is stored in each package */
      th[i].N = d->N;
    }
    th[0].pert = 0;
    th[0].rh = 1;
    th[0].vh = 1;                       /* FR **** Initial condition for the FR equations */

    p = (double*) malloc ((d->N+1)*sizeof(double));

    /* QIF: vr and vp and g */
    for(i=0 ;i<d->N ;i++ ) {
      th[i].vr = d->vr;
      th[i].vp = d->vp;
      th[i].g = d->g;
    }
    
    
    if(d->scan_mode == 2 && d->scan > 0) {
      for(i=0 ;i<d->N ;i++ ) {
	th[i].v = final_conf[i];                /* We mantain the last configuration of voltages */
	th[i].th = final_conf2[i];
      }
    } else {
      InitialState(th,d->init_dist);		/* Initial state configuration */
      /* InitialState(th,d->init_dist+1); */
    }

    for(i=0 ;i<d->N ;i++ ) {
      th[i].spike = 0;		                /* Spike */
      th[i].tr = 0;
      th[i].tr2 = 0;
      th[i].ph = VarChange(th[i]);
    }
    
    dt = d->dt;

    if(def == 0)		/* Debug message: data display */
      DEBUG2(DataDebug(*d,&file));

    if(d->scan_mode == 2 && d->scan > 0) {
      th[0].rh = rh_final;	/* FR **** final configuration of the pevious ... */
      th[0].vh = vh_final;	/* ... simulation is taken as the initial configuration */
    }
    
    /** Distributions *******************/   

    /* QIF: J */
    sprintf(mesg,"Building distribution for J_i. J0 = %lf ",d->J );
    if(d->J_dist == 1)  DEBUG(mesg);
    p = InitCond(p,d->N,2,d->J,d->J_sigma);
    if(d->J_dist == 0) {
      for(i=0 ;i<d->N ;i++ ) 
	th[i].J = d->J;
    } else
      for(i=0 ;i<d->N ;i++ ) 
	th[i].J = p[i];
  
    /* QIF: eta */
    sprintf(mesg,"Building distribution for eta_i. eta0 = %lf ",d->eta );
    if(d->eta_dist == 1)  DEBUG(mesg);
    p = InitCond(p,d->N,2,d->eta,d->eta_sigma);
    if(d->eta_dist == 0) {
      for(i=0 ;i<d->N ;i++ ) 
	th[i].eta = d->eta;
    } else {
      for(i=0 ;i<d->N ;i++ ) 
	th[i].eta = p[i];
    }

    /* QIF: V0 */
    sprintf(mesg,"Building distribution for V0_i. V0 = %lf ",d->v0 );
    if(d->v0_dist == 1)  DEBUG(mesg);
    p = InitCond(p,d->N,2,d->v0,d->v0_sigma);
    if(d->v0_dist == 0) {
      for(i=0 ;i<d->N ;i++ ) 
	th[i].V0 = d->v0;
    } else
      for(i=0 ;i<d->N ;i++ ) 
	th[i].V0 = p[i];


    /* Simulation */
    sprintf(mesg,"Simulating dynamics of: v' = v² + I ");    DEBUG(mesg);
    sprintf(mesg,"I = J*r + n - g*r(v - v0)");    DEBUG(mesg);
    sprintf(mesg,"I = %.3lf*r + %.3lf - %.3lf*r(v - %.3lf) ",d->J,d->eta,d->g,d->v0);    DEBUG(mesg);

    time = 0; fr = 0; fr2 = 0;  avg_fr1 = 0; 
    avg2_fr1 = 0; medida = 0;
    v1_center = 0; v2_center = 0; 
    d->voltdist = 0;
    intervalo = 0;
    inst_fr_avg = 0;
    total_spikes_inst = 0;

    do {
      /* In each step we must compute the mean field potential (r) */
      if(time%((int)((float)d->TT/(10.0*dt))) == 0) { /* Control point */
	sprintf(mesg,"%d%% ",(int)(((time*dt)/(float)d->TT)*100) );
	DEBUG(mesg);
      }
      /* Parallelizable, watch out with pointers and shared variables */
#pragma omp parallel for schedule(dynamic,chunksize)
      for(i=0 ;i<d->N ;i++ ) {	/* i represents each oscillator */
	th[i].r = fr;	
	if(th[0].pert == 1) 
	  th[i].r = th[0].FR;
	th[i].r2 = fr2;
	th[i].spike = 0;
	th[i].spike2 = 0;

	if(temporal_correction == 1) {
	  if(th[i].tr == 1) {
	    th[i].tr = 2;
	    th[i].spike = 1;
	  } else if(th[i].tr == 2) {
	    th[i].tr = 0;
	  } else 
	    th[i] = QIF(*d,th[i]);
	} else {
	  th[i] = QIF(*d, th[i]);
	  if(th[i].tr == 1) th[i].spike = 1;
	  th[i].tr = 0;
	}

	th[i] = THETA(*d,th[i]);

	if(time*dt >= (d->TT/4.0)*3.0) 
	  th[i].total_spikes += th[i].spike;
      }
      /* Simulation of rate equations */
      th[0] = Theory(*d,th[0]);
      /* Ends here */

      fr = MeanField(th,d->dt,1);   fr2 = MeanField(th,d->dt,2);
      if((time*d->dt)/d->TT > 0.9) {
	total_spikes1 += th[0].global_s1;
	total_spikes2 += th[0].global_s2;
	for(i=0 ;i<d->N ;i++ ) {
	  v1_center += th[i].v;
	  v2_center += th[i].th;
	}

	v1_center /= d->N;
	v2_center /= d->N;
	medida++;
	avg_v1 += v1_center;
	avg_v2 += v2_center;
      }
      /* Inst FR */
      total_spikes_inst += th[0].global_s1;
      intervalo++;

      if(abs(time - (int)(d->TT/d->dt)) <= 50) {
	d->voltdist++;
	Data_Files(&file,*d,2);
	for(i=0 ;i<d->N ;i++ ) 
	  fprintf(file[6],"%lf\n",th[i].v);
	Data_Files(&file,*d,3);
      }

      if(d->disable_raster == 0)
	for(i=0 ;i<d->N ;i++ ) {
	  if(th[i].spike == 1)
	    fprintf(file[2] ,"%lf\t%d\t-1\n",time*d->dt,i);
	  if(th[i].spike2 == 1)
	    fprintf(file[2] ,"%lf\t-1\t%d\n",time*d->dt,i);
	}
      R = OrderParameter(th,&phi);
      th[0].FR = 0;
      th[0].pert = 0;
      /* Perturbation introduced here */
      if((time > (d->TT/d->dt)-100) && d->pert == 1 && d->dx >= 0) {
	if(time == (d->TT/d->dt)-100 +1) {
	  avg_fr1 = (double)total_spikes1/((double)medida*d->dt);
	  avg_fr1 /= d->N;
	  printf("\n Average FR 0: %.8lf",avg_fr1);
	  fflush(stdout);	  
	}
	if(abs(time-(int)((d->TT/d->dt)-100))%5 == 0) {
	  Perturbation(&th,*d,1);
	  th[0].pert = 1;
	  printf("\nPerturbation: %lf!!",d->pert_amplitude);
	  perturbation = d->pert_amplitude;
	}
	if(time == (d->TT/d->dt)-1) {
	  d->TT = dTT2;
	  d->pert = 2;
	}
      } else if((time == (d->TT/d->dt)-1) && d->pert == 1) {
	Perturbation(&th,*d,0);
	th[0].vh += d->perturbation_FR; /* FR *** Perturbation for FR equations */
	th[0].pert = 1;
	printf("\nPerturbation: %lf!!",d->pert_amplitude);
	perturbation = d->pert_amplitude;
	d->TT = dTT2;
	avg_fr1 = (double)total_spikes1/((double)medida*d->dt);
	avg_fr1 /= d->N;
	printf("\n Average FR 0: %.8lf",avg_fr1);
	fflush(stdout);
	d->pert = 2;
      }
      fprintf(file[3] ,"%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n",time*dt,fr,R,phi,fr2,R,phi,th[0].rh,th[0].vh);
      fprintf(file[0] ,"%lf\t%lf\t%lf\t%lf\n",time*d->dt,th[d->N/4].v,th[d->N/4].th,perturbation);

      if(time%50 == 0) {
	inst_fr_avg  = (double)total_spikes_inst/(double)intervalo;
	inst_fr_avg  = inst_fr_avg/(d->N*d->dt);
	intervalo = 0;
	fprintf(file[7],"%lf\t%lf\n",time*d->dt,inst_fr_avg);
	inst_fr_avg = 0;
	total_spikes_inst = 0;
      }
      perturbation = 0;

      time++;    
    } while(time*d->dt< d->TT);

    if(d->pert == 2) {
      d->TT = dTT;
      d->pert = 1;
    }
    avg_fr1 = (double)total_spikes1/((double)medida*d->dt);
    avg_fr1 /= d->N;
    printf("\n Average FR 1: %.8lf",avg_fr1);

    avg2_fr1 = (double)total_spikes2/((double)medida*d->dt);
    avg2_fr1 /= d->N;
    printf("\n Average FR Theta: %.8lf\n",avg2_fr1);

    avg_v1 /= medida;
    avg_v2 /= medida;
    avg_v2 = tan(avg_v2*0.5);

    R_script(*d,avg2_fr1,avg_v2);
    R_calc(*d,&fr_x,&fr_y); /* fr: 0  voltage: 1 */
    fr_volt[0] = fr_x;
    fr_volt[1] = fr_y;
    fr_x = 2*fr_x/(PI);
    fr_y = 2*fr_y;

    printf("\n Average Voltage (v) : %lf\n Average Voltage (Theta) : %lf",avg_v1, avg_v2);
    printf("\n Average Voltage (v) using v distribution: %lf\n Average FR using v dist : %lf\n",fr_volt[1]*2,fr_volt[0]*(2.0/(PI)));

    
    if(d->scan_mode >= 1) {
      switch(d->variable) {
      case 1:
	var_value = d->J;
	break;
      case 2:
	var_value = d->eta;
	break;
      case 3:
	var_value = d->g;
	break;
      case 4:
	var_value = d->v0;
	break;
      }
      fprintf(file[4] ,"%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n",var_value,avg_fr1,avg2_fr1,avg_v1, avg_v2,fr_x,fr_y);
    }
    
    printf("\n");
    free(p);
    for(i=0 ;i<d->N ;i++ ) {
      fprintf(file[1] ,"%d\t%lf\t%lf\n",i,th[i].v,th[i].th);
      final_conf[i]  = th[i].v;
      final_conf2[i] = th[i].th;
    }

    free(th);
    d->scan++;
    Data_Files(&file,*d,1);
    Data_Files(&file,*d,5);
    if(d->scan_mode == 0)
      break;

  } while (d->scan < Nscan);
  /* Simulation ends here */


  free(final_conf);
  free(final_conf2);

  /* system("R -f histogram.R --quiet --slave"); */
  /* Gnuplot_Init(*d,day,hour); */
  system("rm -r ./temp");
  printf("\n");
  return 0;  
}