Esempio n. 1
0
void fit_plot(double upres,double lowres,double upcen,double lowcen){
double p0[4],p[4],half,width,max;
int i,j,k,ud,info;
char str1[256];

	FitGraceinit(); 
	half=0.0;
	GracePrintf("focus g0");
	for(i=0;i<NCH;i++) dis[i]=0;
	for(j=0;j<4;j++)
   {
		for(k=0;k<NCH;k++)
      {
		  max=fits[j][k][3]+2.0*fits[j][k][0];
		  if ((fits[j][k][1]>=lowcen)&&(fits[j][k][1]<=upcen)&&(fits[j][k][2]>=lowres)&&(fits[j][k][2]<=upres))
        {
         printf("In: k=%i  Center=%lg  width=%lg  min=%lg  max=%lg\n",k,fits[j][k][1],fits[j][k][2],max);
         sprintf(str1,"g0.s0 point %lg, %lg",fits[j][k][1],fits[j][k][2]);
         GracePrintf(str1);
        }
		  else 
        {
		  	dis[k]=1;
			printf("Out:k=%i Center=%lg  width=%lg  max=%lg  min=%lg\n",k,fits[j][k][1],fits[j][k][2],max);
		  	sprintf(str1,"g0.s1 point %lg, %lg",fits[j][k][1],fits[j][k][2]);
			GracePrintf(str1);
        }
		} // for k
      GracePrintf("autoscale");
      GracePrintf("redraw");
	} // for j
printf("%lg  %lg %lg %lg\n",upcen, lowcen,upres,lowres);
std_dev();
}
Esempio n. 2
0
void fitall(){
double p0[4],p[4],half,width;
int i,j,k,ud,info;
char str1[256];

	FitGraceinit();
	half=0.0;
	GracePrintf("focus g0");
	
	for(j=0;j<4;j++){
		for(k=0;k<NCH;k++){
			mn=10000000;
			mx=0;
			for(i=0;i<NPOINTS;i++){
				fitdat[i]=data[j][k][i];
				if(fitdat[i]>=mx) mx=fitdat[i];
				if(fitdat[i]<=mn) mn=fitdat[i];
				}
			half=(mn+mx)/2.0;
			if((j==0) || (j==2)){
			  fitud=1;
			  for(i=0;i<NPOINTS-1;i++){
                        	if((fitdat[i]>=half) && (fitdat[i+1]<=half)){
                                	/*printf("LoMid = %i\n",i);*/
                                	p0[1]=x[i]; /* center */
                                	p0[2]=60.0; /* width (V) */
					p0[0]=(mx-mn)/2;/* height */
					p0[3]=mn;   /* baseline */
					}
				}
			  }

			if((j==1) || (j==3)){
			  fitud=-1;
                  	  for(i=0;i<NPOINTS-1;i++){
                        	if((fitdat[i]<=half) && (fitdat[i+1]>=half)){
                                	/*printf("LoMid = %i\n",i);*/
                                	p0[1]=x[i]; /* center */
                                	p0[2]=60.0; /* width (V) */
					p0[0]=(mx-mn)/2;/* height */
					p0[3]=mn;   /* baseline */
					}
				}
			  }

			printf("Before: p0=%g p1=%g p2=%g p3=%g\n",p0[0],p0[1],p0[2],p0[3]);
			fit(p0,&info);
			printf("After: p0=%g p1=%g p2=%g p3=%g info=%i\n",p0[0],p0[1],p0[2],p0[3],info);
			for(i=0;i<4;i++) fits[j][k][i]=p0[i];
                        /*printf("Center=%g  width=%g  max=%g  min=%g  info=%i\n",fits[j][k][1],fits[j][k][2],fits[j][k][0]+fits[j][k][3],info);*/
                        sprintf(str1,"g0.s%i point %g, %g",j,fits[j][k][1],fits[j][k][2]);
			GracePrintf(str1);
			}
	GracePrintf("autoscale");
	GracePrintf("redraw");
	}
	if(save_fits()) printf("save fits error\n");
}
static int printXMGConcentrationTimeCourse(cvodeData_t *data)
{
  int i,j,n;
  double maxY;
  double minY;

  cvodeResults_t *results;

  maxY = 1.0;
  minY = 0.0;

  fprintf(stderr, "Printing results to XMGrace!\n");
  if ( Opt.Sensitivity  && results->sensitivity != NULL )
    fprintf(stderr, "SORRY: sensitivities can not be printed to XMGrace\n");
  
  results = data->results;
  
  if ( openXMGrace(data) > 0 ){
    fprintf(stderr,
	    "Error: Couldn't open XMGrace\n");
    return 1;     
  }
  if ( printXMGLegend(data, data->nvalues-data->model->nconst) > 0 ){
    fprintf(stderr,
	    "Warning: Couldn't print legend\n");
    return 1;
  }
  
  for ( i=0; i<=results->nout; ++i ) {
    n=1; 
    for ( j=0; j<data->nvalues-data->model->nconst; j++ ) {
      if ( results->value[j][i] > maxY ) {
	maxY = results->value[j][i];
	GracePrintf("world ymax %g", 1.25*maxY);	
      }
      if ( results->value[j][i] < minY ) {
	minY = results->value[j][i];
	GracePrintf("world ymin %g", 1.25*minY);
      }
      GracePrintf("g0.s%d point %g, %g", 
		  n, results->time[i], results->value[j][i]);
      n++;
    }
  
    /*  if ( i%10 == 0 ) {
      GracePrintf("yaxis tick major %g", 1.25*(fabs(maxY)+fabs(minY))/10);
      GracePrintf("redraw");
      }
    */
  }
  GracePrintf("yaxis tick major %g", 1.25*(fabs(maxY)+fabs(minY))/10);
  GracePrintf("redraw");
  closeXMGrace(data, "species");

  return 0;
}
Esempio n. 4
0
void FitGraceinit(){
/* set up to plot edge position vs edge width for all channels, different color
 for upper and lower thresholds and sca1 and sca2.
*/

int j;
char str1[256];

  if(GraceIsOpen()){
        GraceClose();
	}
  GraceOpen(32768);
  GracePrintf("page size 500,400");
  GracePrintf("redraw");
  GracePrintf("g0 on");
  GracePrintf("focus g0");
  GracePrintf("xaxis ticklabel char size 0.6");
  GracePrintf("yaxis ticklabel char size 0.6");
  for(j=0;j<4;j++){
       sprintf(str1,"s%i on",j);
       GracePrintf(str1);
       sprintf(str1,"s%i symbol %i",j,j+1);
       GracePrintf(str1);
       sprintf(str1,"s%i line type 0",j);
       GracePrintf(str1);
       }
#ifdef DEBUG
	printf("leaving FitGraceinit()\n");
#endif
}
Esempio n. 5
0
void ScanGraceinit(){
/* set up to plot data for all channels, different color
 for upper and lower thresholds and sca1 and sca2.
*/

int i,j;
char str1[256];
#ifdef DEBUG
	printf("entering ScanGraceinit()\n");
#endif

  if (GraceIsOpen()) GraceClose();
  GraceOpen(32768);
  GracePrintf("page size 450,350");
  GracePrintf("arrange(2,2,0.1,0.1,0.1)");
  GracePrintf("redraw");
  for(j=0;j<4;j++){
	sprintf(str1,"g%i on",j);
	GracePrintf(str1);
	sprintf(str1,"focus g%i",j);
	GracePrintf(str1);
	GracePrintf("xaxis ticklabel char size 0.6");
	GracePrintf("yaxis ticklabel char size 0.6");
	for(i=0;i<NPLT;i++){
		sprintf(str1,"g%i.s%i symbol %i",j,i,j+1);
		GracePrintf(str1);
		}
	}
#ifdef DEBUG
	printf("leaving ScanGraceinit()\n");
#endif

}
Esempio n. 6
0
void grace_draw_plot (int npoints, Array x, Array y, char *yname, char *timestr, char *legend,
                     double xmin, double xmax, double ymin, double ymax) 
{
    int i;
    int xxlen=npoints;
    char xstr[128], ystr[128];

    // Note grSets is now the index of this plot set. 
    // Will be incremented at the end to indicate the number of sets drawn
    
    if (!grInited) {
        fprintf (stderr, "Error: grace draw was called before init\n");
        return;
    }
    // printf("grace_draw_plot %d: %s\n", grSets, yname);
    // printf("   x: %lf - %lf\n   y: %lf - %lf\n",
    //       xmin, xmax, ymin, ymax);
    
    // If the whole data is undefined, do not produce image (would be empty)
    if ( Array_is_data_undef_all(y) ) {
        printf("All data is undef for this variable: %s %s\n", yname, timestr);
        return;
    }

    // recalc min/max
    if (xmin < grXMin) grXMin = xmin;
    if (xmax > grXMax) grXMax = xmax;
    if (ymin < grYMin) grYMin = ymin;
    if (ymax > grYMax) grYMax = ymax;

    if (!grSubtitleGiven)
        GracePrintf("subtitle \"T=%s, [%6.2le:%6.2le],[%6.2le:%6.2le]\"",timestr,xmin,xmax,ymin,ymax);

    for (i = 0; i < xxlen && GraceIsOpen(); i++) {
        Array_strvalue(x, i, xstr);
        Array_strvalue(y, i, ystr);
        GracePrintf("g0.s%d point %s, %s",grSets,xstr,ystr);
    }
    GracePrintf("s%d line linewidth 4.0", grSets);
    GracePrintf("s%d line color %d", grSets, grSets%15+1);
    if (legend != NULL)
        GracePrintf("s%d legend \"%s\"", grSets, legend);

    //GracePrintf("redraw");
    //GracePrintf("print to \"i%d.png\"",grSets);
    //GracePrintf("print");

    grSets++;
}
Esempio n. 7
0
void grace_save_plot (char *outputpath, bool save_to_agr) 
{
    int i;
    double yedge, xedge; // 2% of the ymax-ymin, xmax-xmin, resp.
    if (!grInited) 
        return;  // silently, so no warning if only 2D plots were done in main

    //printf("grace_save_plot: %s\n", outputpath);
    if (grSets > 0) {
        // draw the graphs now (if we have any data)
        // add 2% edge to the min/max values 
        yedge = (grYMax-grYMin)*0.02;
        xedge = (grXMax-grXMin)*0.02;
        // if function is constant, yedge is zero and plot would be empty
        if (yedge == 0) yedge = grYMax/2.0 + 0.55;
        //printf("\n   x: %lf - %lf\n   y: %lf - %lf\n   xedge: %lf\n   yedge: %lf\n",
        //       grXMin, grXMax, grYMin, grYMax, xedge, yedge);

        //GracePrintf("autoscale");
        GracePrintf("world xmin %le", grXMin-xedge);
        GracePrintf("world xmax %le", grXMax+xedge);
        GracePrintf("world ymin %le", grYMin-yedge);
        GracePrintf("world ymax %le", grYMax+yedge);
        GracePrintf("autoticks");
        GracePrintf("redraw");
    }
    //if (save_to_png) {
        GracePrintf("print to \"%s.png\"",outputpath);
        GracePrintf("print");
        if (print_provenance)
            printf("--ProvenanceInfo name=\"%s.png\" size=0 date=0\n", outputpath);
    //}
    if (GraceIsOpen() && save_to_agr) {
        /* Tell Grace to save the data */
        GracePrintf("saveall \"%s.agr\"",outputpath);
    }
    // clear plot (for next init, draws, save cycle)
    for (i=0; i<grSets; i++) {
        GracePrintf("kill g0.s%d", i);
    }

    grInited = false;
}
static int closeXMGrace(cvodeData_t *data, char *safename)
{
  if ( Opt.Write ) {
    fprintf(stderr, "Saving XMGrace file as \"%s_%s_t%g.agr\"\n",
	    Opt.ModelFile,
	    safename,
	    data->results->time[data->results->nout]);
    GracePrintf("saveall \"%s_%s_t%g.agr\"",
		Opt.ModelFile,
		safename,
		data->results->time[data->results->nout]);
  }

  GraceClosePipe();
  return(0);
}
static int printXMGLegend(cvodeData_t *data, int nvalues)
{
  int i, found;
  odeModel_t *om = data->model;
  Model_t *m = om->simple;
  Species_t *s;
  Parameter_t *p;
  Compartment_t *c;

  
  for ( i=0; i<nvalues; i++ ) {
    found = 0;
    if ( (s = Model_getSpeciesById(m, om->names[i])) != NULL ) {
      if ( Species_isSetName(s) ) {
	GracePrintf("g0.s%d legend  \"%s: %s\"\n", i+1,
		    om->names[i], Species_getName(s));
	found++;
      }
    }
    else if ( (c = Model_getCompartmentById(m, om->names[i])) ) {
      if ( Compartment_isSetName(c) ) {
	GracePrintf("g0.s%d legend  \"%s: %s\"\n", i+1,
		    om->names[i], Compartment_getName(c));
	found++;
      }
    }
    else if ( (p = Model_getParameterById(m, om->names[i])) ) {
      if ( Parameter_isSetName(p) ) {
	GracePrintf("g0.s%d legend  \"%s: %s\"\n", i+1,
		    om->names[i], Parameter_getName(p));
	found++;
      }
    }
    if ( found == 0 )
      GracePrintf("g0.s%d legend  \"%s\"\n", i+1, om->names[i]);
  }


  GracePrintf("legend 1.155, 0.85");
  GracePrintf("legend font 8");
  GracePrintf("legend char size 0.6");

  return 0;
}
Esempio n. 10
0
void scan_levels(){
int ud,i,j,res,leng,len2;
int y[640]; /* max no. of channels */
char str1[256];
float x_i;
FILE *fd;
int nrep;

#ifdef DEBUG
	printf("entering scan_levels()\n");
#endif
    
    makex();
    ScanGraceinit();
    ud=1;
    
#ifdef DEBUG
	printf("putting dishi\n");
#endif

    // ezcaPut("det1:ao2",ezcaFloat,1,&dishi);
    // ezcaPut("det1:ao4",ezcaFloat,1,&dishi);
   ezcaPut("det1.VH1",ezcaFloat,1,&dishi);
   ezcaPut("det1.VH2",ezcaFloat,1,&dishi);

#ifdef DEBUG
	printf("put dishi\n");
#endif

   for(i=0;i<NPOINTS;i++)
   {
      x_i=(float)x[i];

#ifdef DEBUG
      printf("putting thresholds\n");
#endif

      // ezcaPut("det1:ao1",ezcaFloat,1,&x_i);
      // ezcaPut("det1:ao3",ezcaFloat,1,&x_i);
      ezcaPut("det1.VL1",ezcaFloat,1,&x_i);
      ezcaPut("det1.VL2",ezcaFloat,1,&x_i);
#ifdef DEBUG
      printf("about to count %g at %g...\n",cnt_time, x[i]);
#endif
      count();

#ifdef DEBUG
   printf("getting NCH\n");
#endif

      res=ezcaGet("det1.NCH",ezcaShort,1,&NCH);
      if(res!=0) printf("get NCH: CA error %i",res);

#ifdef DEBUG
      printf("NCH= %i\n",NCH);
#endif

      NPLT=NCH;

#ifdef DEBUG
      printf("getting data\n");
#endif

// YF 9/25/13 -- add mechanism to repeat if get bad data
     
      res=ezcaGet_KeepTrying("det1.S2",ezcaLong,NCH,y);

      for(j=0;j<NCH;j++)
      {
         data[0][j][i]=y[j];
#ifdef DEBUG
         printf("%i   %i\n", y[j], data[0][j][i]);
#endif
      }
      printf("\n");
      
      res=ezcaGet_KeepTrying("det1.S3",ezcaLong,NCH,y);
      
      for(j=0;j<NCH;j++)
      {
         data[2][j][i]=y[j];
#ifdef DEBUG
         printf(" %i",data[2][j][i]);
#endif
      }
      printf("\n");

#ifdef DEBUG
      printf("Plotting point %i..\n",i);
#endif
      GracePrintf("focus g0");
      for(j=0;j<NPLT;j++)
      {
         sprintf(str1,"g0.s%i point %g, %i",j,x[i],data[0][j][i]);
         /* printf("%s\n",str1);*/
         GracePrintf(str1);
      }
      GracePrintf("autoscale");
      GracePrintf("redraw");

      GracePrintf("focus g2");
      for(j=0;j<NPLT;j++)
      {
         sprintf(str1,"g2.s%i point %g, %i",j,x[i],data[2][j][i]);
         /* printf("%s\n",str1);*/
         GracePrintf(str1);
      }
      GracePrintf("autoscale");
      GracePrintf("redraw");
	}  // for(i=0;i<NPOINTS;i++)
   

   GraceFlush();
   ud=-1;
#ifdef DEBUG
	printf("Putting dislo\n");
#endif
    // ezcaPut("det1:ao1",ezcaFloat,1,&dislo);
    // ezcaPut("det1:ao3",ezcaFloat,1,&dislo);
   ezcaPut("det1.VL1",ezcaFloat,1,&dislo);
   ezcaPut("det1.VL2",ezcaFloat,1,&dislo);
   for(i=0;i<NPOINTS;i++)
   {
      x_i=(float)x[i];
      // ezcaPut("det1:ao2",ezcaFloat,1,&x_i);
      // ezcaPut("det1:ao4",ezcaFloat,1,&x_i);
      ezcaPut("det1.VH1",ezcaFloat,1,&x_i);
      ezcaPut("det1.VH2",ezcaFloat,1,&x_i);
#ifdef DEBUG
      printf("about to count %g at %g\n",cnt_time, x[i]);
#endif
      count();
#ifdef DEBUG
      printf("getting data\n");
#endif
      res=ezcaGet_KeepTrying("det1.S2",ezcaLong,NCH,y);

      for(j=0;j<NCH;j++)
      {
         data[1][j][i]=y[j];
      }
      res=ezcaGet_KeepTrying("det1.S3",ezcaLong,NCH,y);

      for(j=0;j<NCH;j++)
      {
         data[3][j][i]=y[j];
      }
#ifdef DEBUG
      printf("plotting point %i\n",i);
#endif
      GracePrintf("focus g1");
      for(j=0;j<NPLT;j++)
      {
         sprintf(str1,"g1.s%i point %g, %i",j,x[i],data[1][j][i]);
         GracePrintf(str1);
      }
      GracePrintf("autoscale");
      GracePrintf("redraw");

      GracePrintf("focus g3");
      for(j=0;j<NPLT;j++)
      {
         sprintf(str1,"g3.s%i point %g, %i",j,x[i],data[3][j][i]);
         GracePrintf(str1);
      }
      GracePrintf("autoscale");
      GracePrintf("redraw");
   }  // for(i=0;i<NPOINTS;i++)
   GraceFlush();
   /*	for(i=0;i<NPLT;i++){
     for(j=0;j<NPOINTS;j++){
      printf(" %i",data[0][i][j]);
      }
      printf("\n");
   } */
#ifdef DEBUG
   printf("Saving scan data\n");
#endif

   fd=fopen("scan_data.dat","wb");
   if(fd==NULL) printf("%s\n",strerror(errno));
   if(fd != NULL)
   {
      leng=sizeof(data)/sizeof(int);
      printf("File size: %i\n", leng * sizeof(int));
      len2=fwrite(data, sizeof(int), sizeof(data)/sizeof(int), fd);
      if(len2 != leng) 
         printf("Write error %s \n", strerror(errno));
   }
   fclose(fd);	  
}
Esempio n. 11
0
static int printXMGReactionTimeCourse ( cvodeData_t *data )
{

  int i, j, k, n;
  double maxY, minY, result;
  
  Model_t *m;
  Reaction_t *r;
  KineticLaw_t *kl;
  ASTNode_t **kls;
  
  odeModel_t *om = data->model;
  cvodeResults_t *results = data->results;

  maxY = 0.0;
  minY = 0.0;

  fprintf(stderr,
	  "Printing time development of reaction fluxes to XMGrace!\n");


  if ( om->m == NULL ) {
    fprintf(stderr, "Error: No reaction model availabe\n");
    return 1;
  }
  else m = om->m;

  if ( openXMGrace(data) > 0 ) {
    fprintf(stderr,  "Error: Couldn't open XMGrace\n");
    return 1;
  }
  
  GracePrintf("yaxis label \"%s\"", "flux [substance/time]");
  if ( Model_isSetName(m) )
    GracePrintf("subtitle \"%s, %s\"", Model_getName(m),
		"reaction flux time courses");
  else if  ( Model_isSetId(m) )
    GracePrintf("subtitle \"%s, %s\"", Model_getId(m),
		"reaction flux time courses");
  else 
    GracePrintf("subtitle \"model has no name, %s/id\"",
		"reaction flux time courses");


  /* print legend */  
  for ( i=0; i<Model_getNumReactions(m); i++ ) {
    r = Model_getReaction(m, i);
    if ( Reaction_isSetName(r) )
      GracePrintf("g0.s%d legend  \"%s: %s \"\n", i+1,
		  Reaction_getId(r), Reaction_getName(r));
    else
      GracePrintf("g0.s%d legend  \"%s \"\n", i+1, Reaction_getId(r));      
  }  
  GracePrintf("legend 1.155, 0.85");
  GracePrintf("legend font 8");
  GracePrintf("legend char size 0.6");

  if(!(kls = (ASTNode_t **)calloc(Model_getNumReactions(m),
				  sizeof(ASTNode_t *)))) 
    fprintf(stderr, "failed!\n");
  
  for ( i=0; i<Model_getNumReactions(m); i++ ) {
    r = Model_getReaction(m, i);
    kl = Reaction_getKineticLaw(r);
    kls[i] = copyAST(KineticLaw_getMath(kl));
    AST_replaceNameByParameters(kls[i], KineticLaw_getListOfParameters(kl));
    AST_replaceConstants(m, kls[i]);
  }
  
  /* evaluate flux for each time point and print to XMGrace */
  
  for ( i=0; i<=results->nout; i++ ) {  
    n = 1;
    /* set time and variable values to values at time[k] */
    data->currenttime = results->time[i];
    for ( j=0; j<data->model->neq; j++ )
      data->value[j] = results->value[j][i];

    /* evaluate kinetic law expressions */
    for ( j=0; j<Model_getNumReactions(m); j++ ) {
      result = evaluateAST(kls[j], data);
      if ( result > maxY ) {
	maxY = result;
	GracePrintf("world ymax %g", 1.25*maxY);
      }
      if ( result < minY ) {
	minY = result;
	GracePrintf("world ymin %g", 1.25*minY);
      }
      GracePrintf("g0.s%d point %g, %g",
		  n, results->time[i], result);
      n++;
    }
  }

  GracePrintf("yaxis tick major %g", 1.25*(fabs(maxY)+fabs(minY))/10);
  GracePrintf("redraw");
  closeXMGrace(data, "flux");

  /* free temporary ASTNodes */
  for ( i=0; i<Model_getNumReactions(m); i++ ) 
    ASTNode_free(kls[i]);
  free(kls);

  return 0;
  
}
Esempio n. 12
0
void printPhase(cvodeData_t *data)
{

#if !USE_GRACE

  fprintf(stderr,
	  "odeSolver has been compiled without XMGRACE functionality.\n");
  fprintf(stderr,
	  "Phase diagrams can only be printed to XMGrace at the moment.\n");

#else
  
  int i,j;
  double maxY;
  double minY;
  double maxX;
  char *x;
  double xvalue;
  char *y;
  double yvalue;

  cvodeResults_t *results;

  maxY = 1.0;
  maxX = 1.0;
  minY = 0.0;
  
  if ( data==NULL || data->results==NULL ) {
    Warn(stderr,
	 "No data available to print! Please integrate model first!\n");
    return;
  }

  results = data->results;

  if ( openXMGrace(data) > 0 ) {
    fprintf(stderr,
	    "Error: Couldn't open XMGrace\n");
    return;
  }

  GracePrintf("world xmax %g", 1.25*maxX);
  GracePrintf("world ymax %g", 1.25*maxY);

  GracePrintf("xaxis tick major %g", (1.25*maxX)/12.5);
  /*     GracePrintf("xaxis tick minor %d", (int) data->currenttime/100); */
  GracePrintf("yaxis tick major %g", (1.25*maxY)/12.5 );

  if ( Model_isSetName(data->model->m) )
    GracePrintf("subtitle \"%s, %s\"", Model_getName(data->model->m),
		"phase diagram");
  else if  ( Model_isSetId(data->model->m) )
    GracePrintf("subtitle \"%s, %s\"", Model_getId(data->model->m),
		"phase diagram");
  else
    GracePrintf("subtitle \"model has no name, %s/id\"", "phase diagram");
      
  GracePrintf("xaxis label \"species 1\"");
  GracePrintf("yaxis label \"species 2\"");

  printf("Please enter the IDs and NOT the NAMES of species!\n");
  printf("In interactive mode press 'c' to see ID/NAME pairs.\n\n");
  printf("Please enter the ID of the species for the x axis: ");
  x = get_line(stdin);
  x = util_trim(x);
  GracePrintf("xaxis label \"%s\"", x);
  GracePrintf("redraw");
  
  printf("Please enter the ID of the species for the y axis: ");
  y = get_line(stdin);
  y = util_trim(y);
  GracePrintf("yaxis label \"%s\"", y);
  GracePrintf("redraw");
  
  /* check if species exist */
  xvalue = 1;
  yvalue = 1;
  for ( j=0; j<data->model->neq; j++ ) {
    if ( !strcmp(x, data->model->names[j]) ) {
      xvalue = 0;
      GracePrintf("xaxis label \"%s\"", data->model->names[j]);
    }
    if ( !strcmp(y, data->model->names[j]) ) {
      yvalue = 0;
      GracePrintf("yaxis label \"%s\"", data->model->names[j]);
    }
  }
  if ( xvalue || yvalue ) {
    fprintf(stderr, "One of the entered species does not exist.\n");
    GraceClose();
    fprintf(stderr, "XMGrace subprocess closed. Please try again");
    free(x);
    free(y);
    return;
  }

  fprintf(stderr, "Printing phase diagram to XMGrace!\n");

  for ( i=0; i<=results->nout; ++i ) {     
    for ( j=0; j<data->model->neq; j++ ){
      if ( !strcmp(x, data->model->names[j]) ) {
	xvalue = results->value[j][i];
      }
      if ( !strcmp(y, data->model->names[j]) ) {
	yvalue = results->value[j][i];
      }
    }
    GracePrintf("g0.s1 point %g, %g", xvalue, yvalue);

    if ( yvalue > maxY ) {
      maxY = 1.25*yvalue;
      GracePrintf("world ymax %g", maxY);
      GracePrintf("yaxis tick major %g", maxY/10);      
    }
    if ( xvalue > maxX ) {
      maxX = 1.25*xvalue;
      GracePrintf("world xmax %g", maxX);
      GracePrintf("xaxis tick major %g", maxX/10);
    }

    /*
      redrawing on each 10th step gives an impression,
      how fast the two values change within the phase
      diagram.
    */
    if ( i%10 == 0 ) {
      GracePrintf("redraw");
    }
  }

  GracePrintf("redraw");
  closeXMGrace(data, "phase");
  free(x);  
  free(y);

#endif

  return;
}
Esempio n. 13
0
void grace_init_plot (char *title, char *subtitle, char *xname, char *yname, float legendwidth) 
{
    float boxpos_right; // right view pos of the graph frame
    //printf("grace_init_plot: %s\n", title);
    if (!grace_started) grace_start();
    grXMin = INFINITY;
    grXMax = -INFINITY;
    grYMin = INFINITY;
    grYMax = -INFINITY;
    grSets = 0; 

    /* Send some initialization commands to Grace */
    GracePrintf("device \"PNG\" OP \"compression:9\"");
    //GracePrintf("device \"JPEG\" OP \"quality:50\"");
    GracePrintf("hardcopy device \"PNG\"");
    //GracePrintf("hardcopy device \"JPEG\"");
    //GracePrintf("page size 360,300"); 
    GracePrintf("page size %d,%d", grimgSizeX, grimgSizeY); 
    /*     GracePrintf("xaxis tick off"); */
    /*     GracePrintf("yaxis tick off"); */
    /*     GracePrintf("xaxis ticklabel off"); */
    /*     GracePrintf("yaxis ticklabel off"); */
    /*GracePrintf("view 0.137821, 0.051282, 1.157051, 0.868590");*/
    boxpos_right = 1.157051;
    if (legendwidth > 0.0) {
        GracePrintf("view 0.15, 0.051282, %f, 0.868590", boxpos_right-legendwidth);
        GracePrintf("legend on");
        GracePrintf("legend loctype view");
        GracePrintf("legend x1 %f", boxpos_right-legendwidth+0.02);
        GracePrintf("legend y1 0.86");
    } else {
        GracePrintf("view 0.15, 0.051282, %f, 0.868590", boxpos_right);
    }
    /*     GracePrintf("s0 on"); */
    /*     GracePrintf("s0 symbol 1"); */
    /*     GracePrintf("s0 symbol size 0.3"); */
    /*     GracePrintf("s0 symbol fill pattern 1"); */
    /*     GracePrintf("s1 on"); */
    /*     GracePrintf("s1 symbol 1"); */
    /*     GracePrintf("s1 symbol size 0.3"); */
    /*     GracePrintf("s1 symbol fill pattern 1"); */
    GracePrintf("title size 1.4");
    GracePrintf("xaxis  ticklabel char size 1.36");
    GracePrintf("yaxis  ticklabel char size 1.36");
    GracePrintf("title \"%s\"",title);
    if (subtitle) {
        GracePrintf("subtitle \"%s\"",subtitle);
        grSubtitleGiven = true;
    } else {
        grSubtitleGiven = false;
    }
    //GracePrintf("xaxis label \"%s\"",xname);
    //GracePrintf("yaxis label \"%s\"",yname);
    GracePrintf("map color 0 to (%d,%d,%d), \"background\"", 
                grBackgroundRGB[0], grBackgroundRGB[1], grBackgroundRGB[2]);
    GracePrintf("map color 1 to (%d,%d,%d), \"foreground\"", 
                grForegroundRGB[0], grForegroundRGB[1], grForegroundRGB[2]);
    GracePrintf("background color 0");

    GracePrintf("xaxis  tick major linewidth 3.0");
    GracePrintf("yaxis  tick major linewidth 3.0");
    GracePrintf("frame linewidth 2.0");
    GracePrintf("xaxis bar linewidth 3.0");

    grInited = true;
}
Esempio n. 14
0
static int printXMGOdeTimeCourse(cvodeData_t *data)
{  
  int i, j, n;
  double maxY;
  double minY; 
  double result;

  cvodeResults_t *results;

  maxY = 0.01;
  minY = 0.0;
  

  fprintf(stderr,
	  "Printing time development of the ODEs (rates) to XMGrace!\n");

  results = data->results;

  if ( openXMGrace(data) > 0 ) {
    fprintf(stderr,
	    "Error: Couldn't open XMGrace\n");
    return 1;     
  }

  GracePrintf("yaxis label \"%s\"", "ODE values");
  if ( Model_isSetName(data->model->m) )
    GracePrintf("subtitle \"%s, %s\"", Model_getName(data->model->m),
		  "ODEs time course");
  else if  ( Model_isSetId(data->model->m) )
    GracePrintf("subtitle \"%s, %s\"", Model_getId(data->model->m),
		  "ODEs time course");
  else 
    GracePrintf("subtitle \"model has no name/id, %s\"",
		  "ODEs time course");

  /* print legend */  
  if ( printXMGLegend(data, data->model->neq) > 0 ){
    fprintf(stderr,
	    "Warning: Couldn't print legend\n");
    return 1;
  }


  /* evaluate ODE at each time point and print to XMGrace */

  for ( i=0; i<=results->nout; ++i ) {
    n = 1;
    data->currenttime = results->time[i];
    for ( j=0; j<data->model->neq; j++ ) {
      data->value[j] = results->value[j][i];
    }
    for ( j=0; j<data->model->neq; j++ ) {
      result = evaluateAST(data->model->ode[j],data);
      if ( result > maxY ) {
	maxY = result;
	GracePrintf("world ymax %g", 1.25*maxY);
      }
      if ( result < minY ) {
	minY = result;
	GracePrintf("world ymin %g", 1.25*minY);
      }

      GracePrintf("g0.s%d point %g, %g",
		  n, results->time[i], result);
      n++;     
    }

    /*
    if ( i%10 == 0 ) {
      GracePrintf("yaxis tick major %g", 1.25*(fabs(maxY)+fabs(minY))/10);
      GracePrintf("redraw");
    }
    */
  }
  GracePrintf("yaxis tick major %g", 1.25*(fabs(maxY)+fabs(minY))/10);
  GracePrintf("redraw");
  closeXMGrace(data, "rates");

  return 0;
}
Esempio n. 15
0
static int printXMGJacobianTimeCourse ( cvodeData_t *data )
{
  int i, j, k, n;
  double maxY;
  double minY; 
  double result;

  cvodeResults_t *results;

  maxY = 0.0;
  minY = 0.0;
  

  fprintf(stderr,
	  "Printing time development of the jacobian matrix to XMGrace!\n");

  results = data->results;

  if ( openXMGrace(data) > 0 ) {
    fprintf(stderr,
	    "Error: Couldn't open XMGrace\n");
    return 1;
  }
  
  GracePrintf("yaxis label \"%s\"", "jacobian matrix value");
  if ( Model_isSetName(data->model->m) )
    GracePrintf("subtitle \"%s, %s\"", Model_getName(data->model->m),
		"jacobian matrix time course");
  else if  ( Model_isSetId(data->model->m) )
    GracePrintf("subtitle \"%s, %s\"", Model_getId(data->model->m),
		"jacobian matrix time course");
  else 
    GracePrintf("subtitle \"model has no name, %s/id\"",
		"jacobian matrix time course");


  /* print legend */  
  n = 1;  
  for ( i=0; i<data->model->neq; i++ ) {
    for ( j=0; j<data->model->neq; j++ ) {
      GracePrintf("g0.s%d legend  \"%s / %s\"\n",
		  n, data->model->names[i], data->model->names[j]);
      n++;
    }
  }  
  GracePrintf("legend 1.155, 0.85");
  GracePrintf("legend font 8");
  GracePrintf("legend char size 0.6");

  /* evaluate jacobian matrix for each time point and print to XMGrace */
  
  for ( k = 0; k<=results->nout; k++ ) {  
    n = 1;
    data->currenttime = results->time[i];
    for ( i=0; i<data->model->neq; i++ ) {
      
      /* set specie values to values at time[k] */
      data->value[i] = results->value[i][k];
      
      for ( j=0; j<data->model->neq; j++ ) {
	
	result =  evaluateAST(data->model->jacob[i][j], data);
	
	if ( result > maxY ) {	  
	  maxY = result;
	  GracePrintf("world ymax %g", 1.25*maxY);
	}
	if ( result < minY ) {
	  minY = result;
	  GracePrintf("world ymin %g", 1.25*minY);
	}
	
	GracePrintf("g0.s%d point %g, %g",
		    n, results->time[k], result);
	n++;

      }
    }
    /*
    if ( k%10 == 0 ) {
      GracePrintf("yaxis tick major %g", 1.25*(fabs(maxY)+fabs(minY))/10);
      GracePrintf("redraw");
    }
    */
  }
  GracePrintf("yaxis tick major %g", 1.25*(fabs(maxY)+fabs(minY))/10);
  GracePrintf("redraw");
  closeXMGrace(data, "jac");


  return 0;
}
Esempio n. 16
0
void grace_plot (char *outputpath, char *title, char *subtitle, char *xname, char *yname,  
                 int npoints, Array x, Array y, char *timestr,
                 double xmin, double xmax, double ymin, double ymax,
                 bool save_to_agr) {
    int i;
    double yedge, xedge; // 2% of the ymax-ymin, xmax-xmin, resp.
    int xxlen=npoints;
    char xstr[128], ystr[128];

    if (!grace_started) grace_start();
    
    // If the whole data is undefined, do not produce image (would be empty)
    if ( Array_is_data_undef_all(y) ) {
        printf("All data is undef for this variable: %s %s\n", yname, timestr);
        return;
    }

    // now just plot these in grace!
    yedge = (ymax-ymin)*0.02;
    xedge = (xmax-xmin)*0.02;
    // if function is constant, yedge is zero and plot would be empty
    if (yedge == 0) yedge = ymax/2.0 + 0.55;
    //printf("\n   x: %lf - %lf\n   y: %lf - %lf\n   xedge: %lf\n   yedge: %lf\n",
    //       xmin, xmax, ymin, ymax, xedge, yedge);


    /* Send some initialization commands to Grace */


    GracePrintf("device \"PNG\" OP \"compression:9\"");
    //GracePrintf("device \"JPEG\" OP \"quality:50\"");
    GracePrintf("hardcopy device \"PNG\"");
    //GracePrintf("hardcopy device \"JPEG\"");
    //GracePrintf("page size 360,300"); 
    GracePrintf("page size %d,%d", grimgSizeX, grimgSizeY); 
    /*     GracePrintf("xaxis tick off"); */
    /*     GracePrintf("yaxis tick off"); */
    /*     GracePrintf("xaxis ticklabel off"); */
    /*     GracePrintf("yaxis ticklabel off"); */
    /*GracePrintf("view 0.137821, 0.051282, 1.157051, 0.868590");*/
    GracePrintf("view 0.15, 0.051282, 1.157051, 0.868590");
    /*     GracePrintf("s0 on"); */
    /*     GracePrintf("s0 symbol 1"); */
    /*     GracePrintf("s0 symbol size 0.3"); */
    /*     GracePrintf("s0 symbol fill pattern 1"); */
    /*     GracePrintf("s1 on"); */
    /*     GracePrintf("s1 symbol 1"); */
    /*     GracePrintf("s1 symbol size 0.3"); */
    /*     GracePrintf("s1 symbol fill pattern 1"); */
    GracePrintf("title size 1.4");
    GracePrintf("xaxis  ticklabel char size 1.36");
    GracePrintf("yaxis  ticklabel char size 1.36");
    GracePrintf("title \"%s\"",title);
    if (subtitle)
        GracePrintf("subtitle \"%s\"",subtitle);
    else
        GracePrintf("subtitle \"T=%s, [%6.2le:%6.2le],[%6.2le:%6.2le]\"",timestr,xmin,xmax,ymin,ymax);
    //GracePrintf("xaxis label \"%s\"",xname);
    //GracePrintf("yaxis label \"%s\"",yname);
    GracePrintf("map color 0 to (%d,%d,%d), \"background\"", 
                grBackgroundRGB[0], grBackgroundRGB[1], grBackgroundRGB[2]);
    GracePrintf("map color 1 to (%d,%d,%d), \"foreground\"", 
                grForegroundRGB[0], grForegroundRGB[1], grForegroundRGB[2]);
    GracePrintf("background color 0");


    for (i = 0; i < xxlen && GraceIsOpen(); i++) {
        Array_strvalue(x, i, xstr);
        Array_strvalue(y, i, ystr);
        GracePrintf("g0.s0 point %s, %s",xstr,ystr);
    }
    //GracePrintf("autoscale");
    GracePrintf("world xmin %le", xmin-xedge);
    GracePrintf("world xmax %le", xmax+xedge);
    GracePrintf("world ymin %le", ymin-yedge);
    GracePrintf("world ymax %le", ymax+yedge);
    GracePrintf("autoticks");
    GracePrintf("s0 line linewidth 4.0");
    GracePrintf("xaxis  tick major linewidth 3.0");
    GracePrintf("yaxis  tick major linewidth 3.0");
    GracePrintf("frame linewidth 2.0");
    GracePrintf("xaxis bar linewidth 3.0");
    GracePrintf("redraw");
    //if (save_to_png) {
        GracePrintf("print to \"%s.png\"",outputpath);
        GracePrintf("print");
        if (print_provenance)
            printf("--ProvenanceInfo name=\"%s.png\" size=0 date=0\n", outputpath);
    //}
    if (GraceIsOpen() && save_to_agr) {
        /* Tell Grace to save the data */
        GracePrintf("saveall \"%s.agr\"",outputpath);
    }
    GracePrintf("kill g0.s0");

}
Esempio n. 17
0
static int openXMGrace(cvodeData_t *data)
{
  double maxY;

  /* Open XMGrace */
  if ( !GraceIsOpen() ) {     
    GraceRegisterErrorFunction(grace_error); 
    /* Start Grace with a buffer size of 2048 and open the pipe */
    if ( GraceOpen(2048) == -1 ) {
      fprintf(stderr, "Can't run Grace. \n");
      return 1;
    }
    else if ( GraceIsOpen() ) {
      maxY = 1.0;
      /*
	"with g%d" might become useful, when printing multiple
	graphs into one XMGrace subprocess.
      */
      /* GracePrintf("with g%d", data->results->xmgrace); */
      GracePrintf("world xmax %g", data->currenttime);
      GracePrintf("world ymax %g", 1.25*maxY);
      GracePrintf("xaxis tick major %g", data->currenttime/10);
      /* GracePrintf("xaxis tick minor %d", (int) data->currenttime/100); */
      GracePrintf("yaxis tick major %g", (1.25*maxY)/12.5 );
      GracePrintf("xaxis label font 4");
      GracePrintf("xaxis label \"time\"");
      GracePrintf("xaxis ticklabel font 4");
      GracePrintf("xaxis ticklabel char size 0.7");
      GracePrintf("yaxis label font 4");
      GracePrintf("yaxis label \"concentration\"");    
      GracePrintf("yaxis ticklabel font 4");
      GracePrintf("yaxis ticklabel char size 0.7");
      if ( Model_isSetName(data->model->simple) )
	GracePrintf("subtitle \"%s\"", Model_getName(data->model->simple));
      else if  ( Model_isSetId(data->model->simple) )
	GracePrintf("subtitle \"%s\"", Model_getId(data->model->simple));
      else 
	GracePrintf("subtitle \"model has no name/id\"");
      GracePrintf("subtitle font 8");   
    }
  }
  else {
    fprintf(stderr, "Please close XMGrace first.\n");
    return 1;
  }

  return 0;
}
int main(int argc, char** argv)
{
    //reading data values 
    int fd;
    int ctr_numhits=0;
    int num_records=0;
    ssize_t numbytes;
    int compare = 1;
    off_t offset = 0;
    char error_buf[ERROR_BUF_SIZE];
    int headersize=DR_HEAER_SIZE;
    int next_buffer_size=1;
    int datasize=next_buffer_size;
    char *header = (char *) malloc(DR_HEAER_SIZE);
    char *data = (char *) malloc(MAX_DATA_SIZE);

    //plotting variables
    int maxbin = 0;
    int maxvalue = 0;
    int xmax = (int) BINS;

    //data values
    int finebin = 0 ;
    int bytesread = 1;
    int value;
    int pfb_bin = 0;
    int fft_bin = 0;
    int fft_bin_loc= 0;
    int over_thresh = 0;
    int blank = 0;
    int event = 0;
    unsigned int pfb_fft_power = 0;
    unsigned int fields;
    long int i = 0;
    int j = 0;
    int k = 0;
    int ctr = 0;
    int counter=0;
    int beamnum = 0;
    double fstep,fscoarse = 0.0;
    double rfmin,rfctr = 0.0;
    double freq_fft_bin = 0.0;
    double bary_freq = 0.0;
    char rawfile[] = "largefile_MMMDDYYYY_HHMM";
    int gooddata=1;
    int goodfreq=1;

    long int fileposition=0;   //position in input file
    long int filesize;   //position in input file

    FILE *fout;
    //create buffers
    struct spectral_data spectra;

    struct data_vals *data_ptr;
    data_ptr = (struct data_vals *)data;

    //create header structure
    struct setidata frame;

    // create time structure
    tm hittime;
    double spec_time;

    // create SQL structures
    unsigned long int specid;
    //strcpy(def_password, argv[2]);
    char sqlquery[1024];
    char hitquery[1024];

    // file variables
    FILE *datatext;


    // connect to mySQL database
    dbconnect();

#ifdef GRACE
    // Initialize grace plotting windows
    grace_init();
//    grace_open_deux(8192);
//    grace_init_deux(maxbin,maxvalue,xmax);
#endif

    //check for error opening file
    fd = open(argv[1], O_RDONLY);

    if(fd==-1)
    {
        snprintf(error_buf, ERROR_BUF_SIZE, "Error opening file %s", argv[1]);
        perror(error_buf);
        return 0;
    }

    //if we can't find a header, nothing to be done
    if(find_first_header(fd)==-1) return 0;

    //read header
    //make sure we are reading as much data as expected, otherwise might be at eof
    while(headersize==DR_HEAER_SIZE && datasize==next_buffer_size)
    {
        k = k+1;
	//reset dataflag to "good"
	gooddata=1;

	// read in the header data
        headersize = read(fd, (void *) header, DR_HEAER_SIZE);
	fileposition+=headersize;

//        int iii=0;
//        for(iii=0; iii<DR_HEAER_SIZE; iii++)
//            printf("%c", header[iii]);

	//get the size of spectra and parse header values
        next_buffer_size = read_header(header);

        read_header_data(header, &frame);

	//Read in data
        datasize = read(fd, (void *) data, next_buffer_size);
	fileposition+=datasize;

//        printf("Buffersize, datasize: %d %d\n", next_buffer_size, datasize);
//	int iii=0;
//	printf("Printing data header\n");
//	for(iii=0; iii<datasize; iii++)
//		printf("%c", data[iii]);

	//Parse data header
        beamnum = read_beam(data, datasize);
        read_data_header(data, &frame);

	//Convert to RA and Dec
        scramAzZatoRaDec(frame.agc_systime, frame.agc_time, frame.agc_az, frame.agc_za, 
                frame.alfashm_alfamotorposition, beamnum/2, 0, &frame.ra, &frame.dec,  &hittime);

	get_filename(argv[1], rawfile);
//	printf("%s\n", rawfile);

	//Calculate MJD
	spec_time = time2mjd(frame.agc_systime, frame.agc_time);

        // creates query to config table
        // set digital_lo and board to be constants, because we figured we knew
        // what they were and that they weren't changing
        char bid[] = "B2";
        sprintf(sqlquery, "INSERT INTO config (thrscale, thrlimit, fftshift, pfbshift, beamnum, obstime, ra, decl, digital_lo, board, AGC_SysTime, AGC_Time, AGC_Az, AGC_Za, AlfaFirstBias, AlfaSecondBias, AlfaMotorPosition, IF1_rfFreq, synI_freqHz, IF1_synI_ampDB, IF1_if1FrqMHz, IF1_alfaFb, TT_TurretEncoder, TT_TurretDegrees, rawfile) VALUES (%ld, %ld, %ld, %ld, %d, %lf, %lf, %lf, %ld, '%s', %ld, %ld, %lf, %lf, %ld, %ld, %lf, %9.1lf, %9.1lf, %ld, %lf, %ld, %ld, %lf, '%s')", 
                frame.thrscale, frame.thrlimit, frame.fft_shift, frame.pfb_shift,
                beamnum, (double) ((int) spec_time), frame.ra, frame.dec, 200000000, bid, frame.agc_systime, frame.agc_time, 
                frame.agc_az, frame.agc_za, frame.alfashm_alfafirstbias, frame.alfashm_alfasecondbias, 
                frame.alfashm_alfamotorposition, frame.if1_rffreq, frame.if1_syni_freqhz_0, frame.if1_syni_ampdb_0, 
                frame.if1_if1frqmhz, frame.if1_alfafb, frame.tt_turretencoder, frame.tt_turretdegrees, rawfile);

#ifndef DEBUG
        // insert header data into serendipvv config table
        if (mysql_query(conn, sqlquery)) {
            fprintf(stderr, "Error inserting data into sql database... \n");
            exiterr(3);
        }

        // saves specid to be inserted at index in other sql tables
        if ((res = mysql_store_result(conn))==0 && mysql_field_count(conn)==0 && mysql_insert_id(conn)!=0) {
            specid = (unsigned long int) mysql_insert_id(conn);
        }
#endif

#ifdef DEBUG
	printf("%s\n", sqlquery);
	printf("Spec id: %d\n", specid);
#endif
        //doesn't do any bounds checking yet...
        spectra.numhits = read_data(data, datasize) - 4096;

	//printf("size of spectra %d\n",spectra.numhits);
	//header,data
	data_ptr = (struct data_vals *) (data+SETI_HEADER_SIZE_IN_BYTES);

    //======================== TEST FILE DATA DUMP ================

    /*
        FILE *datafile;
        char dataf[100];
        sprintf(dataf,"datafiles/datafile%d.dat",counter);
        datafile = fopen(dataf,"wb");
        fwrite(data,spectra.numhits,1,(FILE *)datafile);
        fflush(datafile);
        fclose(datafile);  
    */

		
    //==============================================

        num_records = read_data(data,datasize);
	ctr_numhits=0;

        //create file spectraldata and print file header
/*        char filename[BUFSIZ];
        sprintf(filename, "spectraldata%d", beamnum);
        datatext = fopen(filename,"w");
        fprintf(datatext, "specnum,beamnum,coarsebin,coarsepower,hitpower,fftbin\n");
*/
        //Calc values for freq_topo calc
        //Freq chan resolution
        fstep = 200000000.0/134217728;
        fscoarse = 200000000.0/4096;
	//Center of the BEE2 bandpass
        rfctr = frame.if1_rffreq - 50000000.0;
	//Right edge of the last bin is the lowest freq
	//because the RF band is flipped in the IF
//	rfmin=rfctr-0.5*fscoarse;
        rfmin=rfctr+0.5*fscoarse;

	//Check to see if there are too many hits
	if(num_records>0.9*frame.thrlimit*4096) {
	    gooddata=0;
	    fprintf(stderr, "Data bad...more than %5.0lf hits.\n",  0.9*frame.thrlimit*4096);
	}

//****OPEN FILE TO WRITE HITS TO
        fout=fopen("hits_list.txt", "w");
//============================
//         LOOP OVER HITS
//=============================
	for(i=0;i< num_records ;i++)
	{
	    goodfreq=1;
	    fields = ntohl(data_ptr->raw_data);
	    fft_bin = slice(fields,15,0);
	    pfb_bin = slice(fields,12,15);
	    over_thresh = slice(fields,1,27);
	    blank = slice(fields,3,28);
	    event = slice(fields,1,31);
	    
	    pfb_fft_power = ntohl(data_ptr->overflow_cntr); //32.0
//	    pfb_fft_power = data_ptr->overflow_cntr; //32.0

	    //Rearrange the bins
	    //1) Reorder the FFT output order
	    //2) Reverse bins due to RF/IF flip
            pfb_bin = (pfb_bin + 2048) % 4096;
//	    pfb_bin = 4096 - pfb_bin;
	    pfb_bin = 4095 - pfb_bin;
	    fft_bin = (fft_bin + 16384) % 32768;
//	    fft_bin = 32768 - fft_bin;
	    fft_bin = 32767 - fft_bin;
            fft_bin_loc = fft_bin;
            fft_bin+=pfb_bin*32768;

	    freq_fft_bin =  rfmin + fstep*fft_bin;

	    //Check that the freq of the hit falls within the valid ranges
	    if(frame.if1_alfafb==1){
	        if(freq_fft_bin < NBF_FREQ_LO || freq_fft_bin > NBF_FREQ_HI)  goodfreq=0;
	    }
	    else if(frame.if1_alfafb==0){
                if(freq_fft_bin < ALFA_FREQ_LO || freq_fft_bin > ALFA_FREQ_HI)  goodfreq=0;
	    }
           
            value = (int) (pfb_fft_power);
            //printf("%d %d %d %d %d %d\n", pfb_bin, fft_bin, pfb_fft_power, blank, event, over_thresh);

	    if(value < 1)
	    {
                value = 1;
	    }

	    if(value > maxvalue)
	    {
                maxvalue = value;
                maxbin = fft_bin;
	    }

	   //populate coarse bin power
	    if(fft_bin_loc==16383)
	    {
                spectra.coarse_spectra[pfb_bin] = value;
	    }

            //Only generate string and insert into database if hit valid
	    if(fft_bin_loc!=16383 && goodfreq==1 && gooddata==1)
	    {
//                spectra.hits[ctr_numhits][0] = value;  
//                spectra.hits[ctr_numhits][1] = fft_bin;  

		//Calculate the frequency of the fine bins and barycenter
		bary_freq=freq_fft_bin+seti_dop_FreqOffsetAtBaryCenter(freq_fft_bin, 
			spec_time+2400000.5, frame.ra, frame.dec, 2000.0, AO_LAT, AO_LONG, AO_ELEV);


                //Prepare mysql query to insert hits
                sprintf(hitquery, "INSERT INTO hit (eventpower, meanpower, binnum, topocentric_freq, barycentric_freq, specid) VALUES (%f, %e, %d, %lf, %lf, %ld)", (double) value, (double) spectra.coarse_spectra[pfb_bin], fft_bin, freq_fft_bin, bary_freq, specid);

                //Write row to tmp file
                fprintf(fout, "\\N\t %f\t %e\t %d\t %lf\t %lf\t 0\t 0\t 0\t 0\t 0\t %ld\t \n", (double) value, (double) spectra.coarse_spectra[pfb_bin], fft_bin, freq_fft_bin, bary_freq, specid);
/*
#ifndef DEBUG
                // insert header data into serendipvv config table
                if (mysql_query(conn, hitquery)) {
                    fprintf(stderr, "Error inserting data into sql database... \n");
                    exiterr(3);
                }
#endif */

            }

            // fill spectraldata with available data and close file
//            fprintf(datatext, "%d, %d, %d, %e, %f, %d\n", k, beamnum, pfb_bin, (double) spectra.coarse_spectra[pfb_bin], (double) value, fft_bin);
	
            ctr_numhits++;
	    data_ptr++;
	    ctr++;		
	}//for(i=0; i<num_records; i++)

        fclose(fout);

        sprintf(hitquery, "LOAD DATA LOCAL INFILE 'hits_list.txt' INTO TABLE hit");
//        printf("%s\n", hitquery);

        if (mysql_query(conn, hitquery)) {
            fprintf(stderr, "Error inserting data into sql database... \n");
            exiterr(3);
        }

//        fclose(datatext);
#ifndef DEBUG
       if(load_blob(conn, specid, spectra.coarse_spectra)!=0)
       {
               fprintf(stderr, "Blob not loaded\n");
               specid=0;
       }
#endif

//	GracePrintf("autoticks");
//	GracePrintf("redraw");
//	GracePrintf("updateall");
//	GracePrintf("kill g0.s0");
//	GracePrintf("saveall \"plots/sample%d.agr\"",counter);
//	grace_init_deux(maxbin,log10(maxvalue),xmax);	

	counter++;
        
        for(i=0;i<4094;i++) {
            spectra.coarse_spectra[i] = spectra.coarse_spectra[i+1];
        }

#ifdef GRACE	
    	plot_beam(&spectra,beamnum);
        printf("num_records: %d spectra.numhits %d\n",num_records,spectra.numhits);
        usleep(200000);
    
	if(counter%10 == 0) { 
            printf("autoscaling...\n");
            GracePrintf("redraw");
            GracePrintf("updateall");
            GracePrintf("autoscale");

            /*
            //output pdf via grace

            GracePrintf("HARDCOPY DEVICE \"EPS\"");
            printf("start eps create\n");
            GracePrintf("PAGE SIZE 600, 600");
            GracePrintf("saveall \"sample.agr\"");
            GracePrintf("PRINT TO \"%s\"", "plot.eps");
            GracePrintf("PRINT");
            */

	}
#endif
    }
//=====================================================
/*
    // play with some text 
    for(i=0; i<10; i++){
         GracePrintf("WITH STRING %d", i);
         GracePrintf("STRING COLOR 0");
         GracePrintf("STRING FONT 8");

         GracePrintf("STRING DEF \"TEST\"");
         GracePrintf("STRING ON");

         GracePrintf("STRING LOCTYPE view");
         GracePrintf("STRING 0.70, %f", 0.95 - (((float) i) / 40.0) );
    }

    GracePrintf("redraw");

    sleep(5);
*/
//===========================================================

#ifdef GRACE
     if (GraceIsOpen()) {
         //Flush the output buffer and close Grace 
         GraceClose();
         // We are done 
         exit(EXIT_SUCCESS);
     } else {
         exit(EXIT_FAILURE);
     }
#endif

    //close file
    close(fd);
    
    return 0;
}