Beispiel #1
0
void xyline(int npts, float *x, float *y, const char *xlab, const char *ylab, int id)
{
    float xmin, xmax, ymin, ymax;
    float overy, over = 0.1;

    /* Determine min and max values to plot and scaling: */
    find_min_max_arr(npts, x, &xmin, &xmax);
    find_min_max_arr(npts, y, &ymin, &ymax);
    overy = over * (ymax - ymin);
    ymax += overy;
    ymin -= overy;

    /* Setup the plot screen: */
    cpgenv(xmin, xmax, ymin, ymax, 0, 0);

    /* Choose the font: */
    cpgscf(2);

    /* Label the axes: */
    cpglab(xlab, ylab, "");

    /* Add ID line if required */
    if (id == 1)
        cpgiden();

    /* Plot the points: */
    cpgline(npts, x, y);

}
void plot_channel_data()
{
  int samp=0;
  int pg_id;

  pg_id = cpgopen("/XSERVE");
  cpgpap(8.0, 0.8);
  cpgask(0);
  cpgpage();
  cpgslct(pg_id);
  cpgsci(3);
  cpgeras();
  cpgsvp(0.15f, 0.95f, 0.2f, 0.8f);
  cpgupdt();
  cpgsch(2.0);
  cpgswin(0, read_count, -0.1f, 0.1f);
  cpgbox("BC1NST",0.0,0,"BCNST",0.0,0);
  cpglab("Time [samples]", "Voltage [volts]", "Antenna Measurement Receiver");
  cpgmove(samp, voltarray[0]);
  for (samp=2; samp<read_count; samp++)
	 {
	   cpgdraw(samp, voltarray[samp]);
	 }
  return 0;
}
Beispiel #3
0
static void demo1()
{
  int i;
  static float xs[] = {1.0, 2.0, 3.0, 4.0, 5.0 };
  static float ys[] = {1.0, 4.0, 9.0, 16.0, 25.0 };
  float xr[60], yr[60];
  int n = sizeof(xr) / sizeof(xr[0]);
  /*
   * Call cpgenv to specify the range of the axes and to draw a box, and
   * cpglab to label it. The x-axis runs from 0 to 10, and y from 0 to 20.
   */
  cpgenv(0.0, 10.0, 0.0, 20.0, 0, 1);
  cpglab("(x)", "(y)", "PGPLOT Example 1: y = x\\u2\\d");
  /*
   * Mark five points (coordinates in arrays XS and YS), using symbol
   * number 9.
   */
  cpgpt(5, xs, ys, 9);
  /*
   * Compute the function at 'n=60' points, and use cpgline to draw it.
   */
  for(i=0; i<n; i++) {
    xr[i] = 0.1*i;
    yr[i] = xr[i]*xr[i];
  }
  cpgline(n, xr, yr);
  return;
}
Beispiel #4
0
int main(int argc, char** argv)
{
  if(argc!=2)
    {
      perror("Invalid arguements : SMROStats <file.lba>\n");
      exit(1);
    }

  // Get the filename from the command line
  char* filename = argv[1];

  // Get stats for input file
  struct stat file_stats;
  if(stat(filename,&file_stats))
    {
      perror("Couldn't retrieve file information.\n");
      exit(1);
    }

  // Check length of input file
  int max=1024; // No. of blocks to read. When max=1024;64MB of input used 
  if(file_stats.st_size<(BLK_SIZE*max))
    max=file_stats.st_size/BLK_SIZE;

  // Data loader
  dsp::SMROFile* loader = new dsp::SMROFile;
  loader->open( filename );
  loader->set_output( new dsp::BitSeries );
  loader->set_block_size( BLK_SIZE );

  // Convert to a dsp::TimeSeries
  dsp::SMROTwoBitCorrection* unpacker = new dsp::SMROTwoBitCorrection;
  unpacker->set_input( loader->get_output() );
  unpacker->set_output( new dsp::TimeSeries );

  // Go to work
  int count;
  for(count=0;count<max;count++)  // Load and unpack (BLK_SIZE*max) bytes
    {
      loader->operate();
      unpacker->operate();
    }
  loader->close();

  // Plot Histogram
  cpgopen("?");
  cpglab("","","SMRO Sampler Statistics");
  cpgsvp(0.1,0.9,0.1,0.9);
  dsp::TwoBitStatsPlotter* plot = new dsp::TwoBitStatsPlotter;
  plot->set_data(unpacker);
  plot->plot();
  cpgclos();

  // Free memory
  delete loader,unpacker;
}
Beispiel #5
0
void plot_profile(int proflen, float *profile, const char *title,
                  const char *probtxt, const char *foldtxt,
                  int showerr, float *errors, int showid)
{
    int ii;
    float *x, overy, ymin, ymax;
    float errmin = 0.0, errmax = 0.0, offset, avg = 0.0, av[2];

    find_min_max_arr(proflen, profile, &ymin, &ymax);
    if (showerr)
        find_min_max_arr(proflen, errors, &errmin, &errmax);
    overy = 0.1 * (ymax + errmax - ymin - errmin);
    ymax = ymax + overy + errmax;
    ymin = ymin - overy - errmin;
    x = gen_fvect(proflen);
    for (ii = 0; ii < proflen; ii++)
        x[ii] = (float) ii / (float) proflen;
    cpgenv(0.0, 1.00001, ymin, ymax, 0, 0);
    cpgscf(2);
    cpglab("Pulse Phase", "Counts", "");
    if (showid)
        cpgiden();
    cpgslw(5);
    if (showerr) {
        cpgbin(proflen, x, profile, 0);
    } else {
        cpgline(proflen, x, profile);
    }
    cpgslw(1);
    if (showerr) {
        offset = 0.5 / (float) proflen;
        for (ii = 0; ii < proflen; ii++)
            x[ii] += offset;
        cpgerrb(6, proflen, x, profile, errors, 2);
        cpgpt(proflen, x, profile, 5);
    }
    for (ii = 0; ii < proflen; ii++)
        avg += profile[ii];
    avg /= proflen;
    cpgsls(4);
    x[0] = 0.0;
    x[1] = 1.0;
    av[0] = avg;
    av[1] = avg;
    cpgline(2, x, av);
    cpgsls(1);
    cpgsch(1.3);
    cpgmtxt("T", +2.0, 0.5, 0.5, title);
    cpgsch(1.0);
    cpgmtxt("T", +0.8, 0.5, 0.5, foldtxt);
    cpgmtxt("T", -1.5, 0.5, 0.5, probtxt);
    vect_free(x);
}
/*
 * Class:     pulsarhunter_PgplotInterface
 * Method:    pglab
 * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_pulsarhunter_PgplotInterface_pglab
(JNIEnv *env, jclass cl, jstring x, jstring y, jstring top){

	char *xStr = (char*)(*env)->GetStringUTFChars(env,x,NULL);
	char *yStr = (char*)(*env)->GetStringUTFChars(env,y,NULL);
	char *topStr = (char*)(*env)->GetStringUTFChars(env,top,NULL);
        jint strlen1 =  (*env)->GetStringUTFLength(env,x);
        jint strlen2 =  (*env)->GetStringUTFLength(env,y);
        jint strlen3 =  (*env)->GetStringUTFLength(env,top);


	cpglab(xStr,yStr,topStr);

	(*env)->ReleaseStringUTFChars(env,x,xStr);
	(*env)->ReleaseStringUTFChars(env,y,yStr);
	(*env)->ReleaseStringUTFChars(env,top,topStr);



}
Beispiel #7
0
void powerplot(int npts, float *freqs, float *amp, float norm, int id)
{
   float *pwr, xmin, xmax, ymin, ymax;
   float overy, over = 0.1;
   int i, ptr;

   pwr = (float *) malloc((size_t) npts * sizeof(float));
   if (!pwr) {
      printf("Error allocating 'pwr' in powerplot.  Exiting.\n\n");
      exit(EXIT_FAILURE);
   }
   /* Turn the complex amps into a power series: */
   for (i = 0; i < npts; i++) {
      ptr = i * 2;
      pwr[i] = plot_power(amp[ptr], amp[ptr + 1]) / norm;
   }

   /* Determine min and max values to plot and scaling: */
   find_min_max_arr(npts, freqs, &xmin, &xmax);
   find_min_max_arr(npts, pwr, &ymin, &ymax);
   overy = over * (ymax - ymin);
   ymax += overy;

   /* Setup the plot screen: */
   cpgenv(xmin, xmax, ymin, ymax, 0, 1);

   /* Choose the font: */
   cpgscf(2);

   /* Label the axes: */
   cpglab("Frequency", "Power", "");

   /* Add ID line if required */
   if (id == 1)
      cpgiden();

   /* Plot the points: */
   cpgline(npts, freqs, pwr);

   free(pwr);
}
int plot_freq_data(void)
{
  int bin=0;

  printf("\nPlotting ...");
  cpgask(0);
  cpgpage();
  cpgslct(pg_id);
  cpgsci(1);
  cpgeras();
  cpgsvp(0.15f, 0.95f, 0.2f, 0.8f);
  cpgupdt();
  cpgsch(2.0);
  cpgswin(0, (N/2)+1, 0.0f, 0.005f);
  //  cpgswin(80, 120, 0.0f, 0.01f);
  cpgbox("BC1NST",0.0,0,"BCNST",0.0,0);
  cpglab("Frequency [bins]", "Peak Voltage [volts]", "Antenna Measurement Receiver");
  cpgmove(bin, accumFreqData[0]);
  for (bin=1; bin<(N/2)+1; bin++)
	 {
	   cpgdraw(bin, accumFreqData[bin]);
	 }
  return 0;
}
Beispiel #9
0
int plot_shifts(Secat *shiftcat, int nshift)
{
  int i;                     /* Looping variable */
  int no_error=1;            /* Flag set to 0 on error */
  float x1,x2,y1,y2;         /* Limits on plot */
  float *fdx=NULL;           /* float version of x offsets */
  float *fdy=NULL;           /* float version of y offsets */
  float *fxptr,*fyptr;       /* Navigation pointers */
  double *dx=NULL;           /* x offsets */
  double *dy=NULL;           /* y offsets */
  double *xptr,*yptr;        /* Navigation pointers */
  double xmean, xsig, xmed;  /* Statistics on dx */
  double ymean, ysig, ymed;  /* Statistics on dx */
  Secat *sptr;               /* Pointer to navigate shiftcat */
  FILE *ofp=NULL;            /* Output file pointer */

  /*
   * Allocate memory for dx and dy arrays
   */

  if(!(dx = new_doubarray(nshift))) {
    fprintf(stderr,"ERROR: calc_shift_stats\n");
    return 1;
  }
  if(!(dy = new_doubarray(nshift)))
    no_error = 0;
  if(!(fdx = new_array(nshift,1)))
    no_error = 0;
  if(!(fdy = new_array(nshift,1)))
    no_error = 0;

  if(no_error) {

    /*
     * Transfer info to new arrays
     */

    for(i=0,sptr=shiftcat,xptr=dx,yptr=dy,fxptr=fdx,fyptr=fdy; 
	i<nshift; i++,sptr++,xptr++,yptr++,fxptr++,fyptr++) {
      *xptr = sptr->dx;
      *yptr = sptr->dy;
      *fxptr = (float) sptr->dx;
      *fyptr = (float) sptr->dy;
    }

    /*
     * Calculate statistics on dx and dy
     */

    doubstats(dx,nshift,&xmean,&xsig,&xmed);
    doubstats(dy,nshift,&ymean,&ysig,&ymed);

    /*
     * Give output values
     */

    printf("\nStatistics on x shift:\n");
    printf("  mean = %f\n",xmean);
    printf("  rms = %f\n",xsig);
    printf("  median = %f\n",xmed);
    printf("Statistics on y shift:\n");
    printf("  mean = %f\n",ymean);
    printf("  rms = %f\n",ysig);
    printf("  median = %f\n",ymed);

    /*
     * Set the limits and median
     */


    x1 = xmed - 5.0 * xsig;
    x2 = xmed + 5.0 * xsig;
    y1 = ymed - 5.0 * ysig;
    y2 = ymed + 5.0 * ysig;

    /*
     * Plot distribution
     */

    cpgslct(2);
    cpgenv(x1,x2,y1,y2,0,1);
    cpglab("x shift","y shift","Calculated Shifts");
    cpgpt(nshift,fdx,fdy,9);

    /*
     * Plot median
     */

    cpgsci(2);
    cpgslw(5);
    fdx[0] = fdx[1] = xmed;
    fdy[0] = y1;
    fdy[1] = y2;
    cpgline(2,fdx,fdy);
    fdy[0] = fdy[1] = ymed;
    fdx[0] = x1;
    fdx[1] = x2;
    cpgline(2,fdx,fdy);
    cpgsci(1);
    cpgslw(1);
  }

  /*
   * Write median shifts to output file -- NB: for these to be the
   *  proper shifts for an iraf imcombine offsets file, the value
   *  need to be the negative of what the above calculation gives.
   */

  if(!(ofp = open_writefile("tmp.offsets")))
    no_error = 0;
  else
    fprintf(ofp,"%8.2f %8.2f\n",-xmed,-ymed);

  /*
   * Clean up and exit
   */

  dx = del_doubarray(dx);
  dy = del_doubarray(dy);
  fdx = del_array(fdx);
  fdy = del_array(fdy);
  if(ofp)
    fclose(ofp);
  if(no_error)
    return 0;
  else {
    fprintf(stderr,"ERROR: calc_shift_stats\n");
    return 1;
  }
}
Beispiel #10
0
void nrpoint(float x[],float y[],float azy[],float ely[],float azmod[],float elmod[],float sig[],int ndata,int num_gauss,int flag,int ant_num,int plotflag,char
*header)
{
	FILE *fp1,*fp2,*fp3,*fp4,*fp5;
	float rms(float *,int);
	float arg, guessed_parameters,xmin,xmax,ymin,ymax,tmp,rms_fac;
	float alamda,chisq,ochisq,**covar,**alpha,*a;
	int i,*ia,itst,j,k,l,numplot,i_maxy,i_miny,MA, NPT;
	char ans[200],f_line[200],c;
	char file_n1[160],file_n2[160],file_n3[160],file_n4[160],file_n5[160];
	char xtitle[60],ytitle[60],title[60],plotant[10];
	FILE *fpsummary, *headerfp;
	char fullfilename[250];
	char buffer[2048]; /* must be larger than length of header */
	char *token[MAX_TOKENS];
	int tokens;
	char rxlabelhigh[30];
	char rxlabellow[30];

	float xx[1600],yy[1600],yyy[1600],res[1600];

/* 	following for aperture efficiency 16 Nov 04, TK */
        char etaCommand[130], rawfilename[256];
        FILE *fpi_eta,*fpo_eta, *fph_eta;
        int  use_beam, time_stamp; 
        float tau_zenith,Tcmbr,Tatm,Thot,Tamb,Tcab,eta_l,delVsource,Vhot,Vsky,err,el,SB;
        float Frequency, TBright, VhotL, VhotH, VskyL, VskyH;
        float PlanetDia, WidthFwhm,fwhm_beam, EtaA, EtaB;
        char  object[20], date[30];
/* 	aperture efficiecny additions end */


	sprintf(file_n1,"/usr/PowerPC/common/data/rpoint/ant%d/load.fitted.dat",ant_num);
	sprintf(file_n2,"/usr/PowerPC/common/data/rpoint/ant%d/load.initial.dat",ant_num);
	sprintf(file_n3,"/usr/PowerPC/common/data/rpoint/ant%d/load.temp.dat",ant_num);
	sprintf(file_n4,"/usr/PowerPC/common/data/rpoint/ant%d/load.results.dat",ant_num);
	sprintf(file_n5,"/usr/PowerPC/common/data/rpoint/ant%d/rpoint.ant%1d",ant_num,ant_num);

	if ((fp1=fopen(file_n1,"w"))==NULL){
	  printf("nrpoint: cannot open n1 = %s\n",file_n1);
	  exit(1);
	}
	chmod(file_n1,0666);
	if ((fp3=fopen(file_n3,"w"))==NULL){
	  printf("nrpoint: cannot open n2 (first time) = %s\n",file_n3);
	  exit(1);
	}
	chmod(file_n3,0666);
	if ((fp4=fopen(file_n4,"a"))==NULL){
	  printf("nrpoint: cannot open n4 = %s\n",file_n4);
	  exit(1);
	}
	chmod(file_n4,0666);
	if ((fp5=fopen(file_n5,"a"))==NULL){
	  printf("nrpoint: cannot open n5 = %s\n",file_n5);
	  exit(1);
	}
	chmod(file_n5,0666);

	NPT=ndata;MA=num_gauss;
/*
	printf("number of data = %d number of fitting components = %d flag = %d\n", NPT,MA/5,flag);

*/
	ia=ivector(1,MA);
	a=vector(1,MA);
	covar=matrix(1,MA,1,MA);
	alpha=matrix(1,MA,1,MA);
	
/* read data */
	xmin=1e6;ymin=1e6;
	xmax=-1e6;ymax=-1e6;
	for (i=1;i<=NPT;i++) {
	  xx[i-1]=x[i];
	  yy[i-1]=y[i];
	  if(xmin>=x[i]) xmin=x[i];
	  if(xmax<x[i]) xmax=x[i];
	  if(ymin>=y[i]){ymin=y[i];i_miny=i;}
	  if(ymax<y[i]) {ymax=y[i];i_maxy=i;}
	  /*
	    if(i<10)	printf("%d %f %f %f %f %f %f\n",i,x[i],y[i],ymin,ymax,azy[i],ely[i],sig[i]);
	  */
	  fprintf(fp3,"%f %f\n",x[i],y[i]);
	}

	tmp=ymax-ymin;
	ymax=tmp*0.2+ymax;
	ymin=ymin-tmp*0.2;
	fclose(fp3);

/*    PGPLOT */
	sprintf(plotant,"%d/xs",(ant_num+10));
	if(plotflag){
	  if(cpgbeg(0,plotant,1,1)!=1) exit(1);
	  cpgenv(xmin,xmax,ymin,ymax,0,0); 
	  cpgpt(NPT,xx,yy,2);
	  cpgline(NPT,xx,yy);
	  tokens = tokenize(header,token);
	  strcpy(rxlabelhigh,token[RX_LABEL_HIGH]);
	  strcpy(rxlabellow,token[RX_LABEL_LOW]);
	  if (lowfreqflag == 0) {
	    sprintf(title,"Antenna %1d  High-frequency (%s) Raw data",ant_num,rxlabelhigh);
	  } else {
	    sprintf(title,"Antenna %1d  Low-frequency (%s) Raw data",ant_num,rxlabellow);
	  }
	  if(flag){
	    sprintf(xtitle,"Antenna %ld  Azoff (arcsec)",ant_num);
	  } else {
	    sprintf(xtitle,"Antenna %ld  Eloff (arcsec)",ant_num);
	  }
	  sprintf(ytitle,"Intensity (Volts)");
	  cpglab(xtitle,ytitle,title);
	  cpgend();
	}
	
/*	initial values of parameters::::::	*/

	if ((fp2=fopen(file_n2,"w"))==NULL){
	  printf("nrpoint: cannot open n2 (second time) = %s\n",file_n2);
	  exit(1);
	}
	chmod(file_n2,0666);

	if(fabs(ymax)>=fabs(ymin)) {
		fprintf(fp2,"%f\n",ymax-ymin);
		fprintf(fp2,"%f\n",x[i_maxy]);
	}
	if(fabs(ymin)>fabs(ymax)) {
		fprintf(fp2,"%f\n",ymin-ymax);
		fprintf(fp2,"%f\n",x[i_miny]);
	}
	fprintf(fp2,"%f\n",20.0);
	fprintf(fp2,"%f\n",0.0);
	fprintf(fp2,"%f\n",y[1]);
	fclose(fp2);

	if ((fp2=fopen(file_n2,"r"))==NULL){
	  printf("nrpoint: cannot open n2 for read = %s\n",file_n2);
	  exit(1);
	}

	for(i=1;i<=MA;i++) 
	{
	  fscanf(fp2,"%f\n",&guessed_parameters);
	  a[i]=guessed_parameters;
	  ia[i]=i;
	}

	fclose(fp2);

/*      start fitting	*/ 
	alamda = -1;
	mrqmin(x,y,sig,NPT,a,ia,MA,covar,alpha,&chisq,fgauss2,&alamda);
	k=1;
	itst=0;
	for (;;) {
	  /*
	    printf("\n%s %2d %17s %9.3e %10s %9.3e\n","Iteration #",k, "chi-squared:",chisq,"alamda:",alamda);
	    for (i=1;i<=MA;i++) printf("%5.3e ",a[i]);
	    printf("\n");
	  */
	  k++;
	  
	  ochisq=chisq;
	  mrqmin(x,y,sig,NPT,a,ia,MA,covar,alpha,&chisq,fgauss2,&alamda);
	  if (chisq > ochisq)
	    itst=0;
	  else if ((fabs(ochisq-chisq) < 0.01 &&
		    fabs(chisq) < .1) || (k>10))
	    {itst++;}
	  if (itst < 4) continue;
	  
	  /*
	    if ((fp2=fopen(file_n2,"w"))==NULL){
	    printf("cannot open %s\n",file_n2);
	    exit(1);
	    }
	  */
	  
	  /*
	    for (i=1;i<=MA;i++) fprintf(fp2,"%f\n",a[i]);
	  */
	  for (i=1;i<=MA;i++) fprintf(fp4,"%f ",a[i]);
	  fprintf(fp4,"%f ",chisq);
	  printf("%f\n ",chisq);
	  /*
	    fprintf(fp2,"\n");
	  */
	  fprintf(fp4,"\n\n");
	  /*
	    fclose(fp2);
	  */
	  
	  for(j=1;j<=NPT;j++){
	    yyy[j-1]=0.0;
	    for(k=1;k<=MA;k+=5){
	      arg=(x[j]-a[k+1])/a[k+2];
	      yyy[j-1]+=a[k]*exp(-arg*arg)+a[k+3]*x[j]+a[k+4];
	    }
	    res[j-1]=y[j]-yyy[j-1]+a[5];
	    fprintf (fp1,"%.6f %.6f %.6f %.6f\n",x[j],y[j],yyy[j-1],res[j-1]);
	  }
	  fclose(fp1);
	  
	  alamda=0.0;
	  mrqmin(x,y,sig,NPT,a,ia,MA,covar,alpha,&chisq,fgauss2,&alamda);
	  rms_fac=rms(res,NPT);
	  printf("\nUncertainties:\n");
	  for (i=1;i<=MA;i++) printf("%8.4e ",rms_fac*sqrt(covar[i][i]));
	  printf("\n");
	  
	  fprintf(fp4,"\nUncertainties:\n");
	  for (i=1;i<=MA;i++) fprintf(fp4,"%8.4e ",rms_fac*sqrt(covar[i][i]));
	  fprintf(fp4,"\n");
	  printf("Generating plot....\n");
	  break;
	}
fclose(fp4);

	if(flag){
	  if (lowfreqflag == 0) {
	    sprintf(title,"Antenna %1d  High-frequency (%s) AZ scan  Fitted data",ant_num,rxlabelhigh);
	  } else {
	    sprintf(title,"Antenna %1d  Low-frequency (%s) AZ scan  Fitted data",ant_num,rxlabellow);
	  }
	  sprintf(xtitle,"Antenna %ld  Azoff (arcsec)",ant_num);
	}
	else{
	  if (lowfreqflag == 0) {
	    sprintf(title,"Antenna %1d  High-frequency (%s) El scan  Fitted data",ant_num,rxlabelhigh);
	  } else {
	    sprintf(title,"Antenna %1d  Low-frequency (%s) El scan  Fitted data",ant_num,rxlabellow);
	  }
	  sprintf(xtitle,"Antenna %ld  Eloff (arcsec)",ant_num);
	}
	sprintf(ytitle,"Intensity (Volts)");

/*    PGPLOT */
	sprintf(plotant,"%d/xs",(ant_num+10));
	if(plotflag){
	  if(cpgbeg(0,plotant,1,1)!=1) exit(1);
	  /* These do nothing helpful:
	  cpgeras();
	  cpgupdt();
	  */
	  cpgenv(xmin,xmax,ymin,ymax,0,0); 
	  cpgpt(NPT,xx,yy,2);
	  cpgline(NPT,xx,yyy);
	  cpgpt(NPT,xx,res,-1);
	  cpglab(xtitle,ytitle,title);
	  sprintf(f_line,"az= %10.4f deg",azy[i_maxy]);
	  cpgmtxt("t",-2.5,0.05,0,f_line);
	  sprintf(f_line,"el = %10.4f deg",ely[i_maxy]);
	  cpgmtxt("t",-4.0,0.05,0,f_line);
	  sprintf(f_line,"y= %10.4f",a[1]);
	  cpgmtxt("t",-7.0,0.05,0,f_line);
	  sprintf(f_line,"x = %10.4f arcsec",a[2]);
	  cpgmtxt("t",-5.5,0.05,0,f_line);
	  sprintf(f_line,"width = %10.4f",a[3]*2*0.83255);
	  cpgmtxt("t",-8.5,0.05,0,f_line);
	  sprintf(f_line,"chisq = %10.4e",chisq);
	  cpgmtxt("t",-10.0,0.05,0,f_line);
	  cpgend();
	}
        fpsummary = fopen(summary_file_name,"r");
	if (fpsummary == NULL) {
	  fpsummary = fopen(summary_file_name,"w");
	} else {
	  fclose(fpsummary);
	  fpsummary = fopen(summary_file_name,"a");
	}
	if (fpsummary == NULL) {
	  printf("Could not write to summary file = %s\n",summary_file_name);
	} else {
#if USE_HEADER
	  sprintf(fullfilename,"/data/engineering/rpoint/ant%d/header.dat",ant_num);
	  headerfp = fopen(fullfilename,"r");
	  /* skip the first line */
	  fgets(buffer,sizeof(buffer),headerfp);
	  fgets(buffer,sizeof(buffer),headerfp);
	  fclose(headerfp);
	  /* cut off the final carriage return */
	  buffer[strlen(buffer)-1] = 0;
	  fprintf(fpsummary,"%s,",buffer);
#endif
	  if (flag == 1) {
	    fprintf(fpsummary,"rpoint: azoff %f %f %f %f ",a[1],a[2],
			a[3]*2*0.83255, rms_fac*sqrt(covar[2][2]));
	  } else {
	    fprintf(fpsummary,"rpoint: eloff %f %f %f %f ",a[1],a[2],
			a[3]*2*0.83255, rms_fac*sqrt(covar[2][2]));
	  }
          /* Following lines added 16 Nov 04, for aperture efficiecncy: TK */
          /* create a temporary file eta_tmp and run the aperture efficiency program */
	  /* needed: 
	  /*  4: source - object
	     14: planetdia
	     29: temperature
  	     37: cabin temperature
             40: elcmd
	     91: rest freq
	     92: sidebandA 
	     a[1]=intensity
	     a[2]=offset
	     a[3]*2*0.83255=scanwidth
	  */
	  printf("Computing aperture efficiency....\n");
          fpi_eta=fopen("aperInput.tmp","w");
	  use_beam=USE_BEAM;
	  delVsource=a[1];
	  WidthFwhm=a[3]*2*0.83255;
	  sprintf(etaCommand, "nawk -F, \' (NR>=2) {print $4,$14,$29,$37,$40,$91,$92,$107}\' /data/engineering/rpoint/ant%d/header.dat > picked.tmp",ant_num);
/*	  printf("%s\n", etaCommand); */
	  system(etaCommand);
	  fph_eta=fopen("picked.tmp","r");
	  fscanf(fph_eta,"%s %f %f %f %f %f %f",object,&PlanetDia,&Tamb,&Tcab,&el,&Frequency,&SB);
	  fscanf(fph_eta, "%s %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %f", rawfilename, &VhotL, &time_stamp, &VhotH, &time_stamp, &VskyL, &time_stamp, &VskyH, &time_stamp, &tau_zenith, &time_stamp, &Tatm , &time_stamp, &eta_l, &time_stamp, &Frequency, &SB);
	  if (lowfreqflag == 0) {
		Vhot=VhotL;
		Vsky=VskyL;
	  }
	  else {
		Vhot=VhotH;
		Vsky=VskyH;
	  }
		
/*	  fscanf(fph_eta, "%s %f %f %f %f %f %f %f %f", rawfilename, &Thot, &tau_zenith, &eta_l, &Vhot, &Vsky, &delVsource,
          &WidthFwhm); */
	  printf("raw file name: %s\n", rawfilename);
	  Tamb = (Tamb+Tcab)/2.0;
	  Thot=Tamb;
/*	  Frequency=Frequency-SB*5.0; */
/*	 
	  Thot=
	  Vhot=
	  Vsky=
	  delVsource=
	  fwhm_beam=52.0;
	  WidthFwhm=
	  Tbright=100;
	  TBright=
*/
	  if (object=="jupiter") TBright=TB_JUP;
	  if (object=="saturn")  TBright=TB_SAT;
	  if (strstr(object,"jupiter")!=NULL) TBright=TB_JUP;
	  if (strstr(object,"saturn")!=NULL)  TBright=TB_SAT;
	  err=0.0;
          fprintf(fpi_eta, "%s %d %s %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %d\n", rawfilename, ant_num, object, el, tau_zenith, Thot,Tamb,Tatm,eta_l,Vhot,Vsky,delVsource,fwhm_beam,Frequency, PlanetDia, WidthFwhm,TBright,err,use_beam);
	   sprintf(etaCommand, "aperEff aperInput.tmp");
          system(etaCommand);
          fpo_eta=fopen("aperResults.tmp","w");
/*	  fscanf(fpo_eta, "%f %f %f", &EtaA,&EtaB,&fwhm_beam); */
	  fprintf(fpo_eta,"%3.2f %3.2f %4.1f\n",EtaA,EtaB,fwhm_beam);
	  fprintf(fpsummary,"%3.2f %3.2f %4.1f\n",EtaA,EtaB,fwhm_beam);
	  fclose(fpsummary);
	  fclose(fpi_eta);
	  fclose(fpo_eta);
	  fclose(fph_eta);
/*	  remove("aperResults.tmp");
	  remove("aperInput.tmp"); */
	}
	printf("recorded! \n");
	printf("azfit %s  | %10.5f %10.5f %10.5f %10.4f %10.2f +- %10.2f %8.1f %8.1f\n",header,azy[i_maxy],ely[i_maxy],a[1],a[3]*2*0.83255,a[2],rms_fac*sqrt(covar[2][2]),azmod[i_maxy],elmod[i_maxy]);
	if(flag==1) fprintf(fp5,"azfit %s  | %10.5f %10.5f %10.5f %10.4f %10.2f +- %10.2f %8.1f %8.1f\n",header,azy[i_maxy],ely[i_maxy],a[1],a[3]*2*0.83255,a[2],rms_fac*sqrt(covar[2][2]),azmod[i_maxy],elmod[i_maxy]);
	else fprintf(fp5,"elfit %s | %10.5f %10.5f %10.5f %10.4f %10.2f +- %10.2f %8.1f %8.1f \n",header,azy[i_maxy],ely[i_maxy],a[1],a[3]*2*0.83255,a[2],rms_fac*sqrt(covar[2][2]),azmod[i_maxy],elmod[i_maxy]);

	fclose(fp5);
	free_matrix(alpha,1,MA,1,MA);
	free_matrix(covar,1,MA,1,MA);
	free_ivector(ia,1,MA);
	free_vector(a,1,MA);
}
Beispiel #11
0
int main(int argc,char *argv[])
{
  int i;
  char fname[128];
  dSet *data; 
  float freq,bw,chanbw;
  int nchan,npol;
  float bpass[4096];
  float fx[4096];
  float miny,maxy,minx,maxx;
  float ominy,omaxy,ominx,omaxx;
  float mx,my,mx2,my2;
  float binw;
  char key;
  char grDev[128]="/xs";
  int interactive=1;
  int noc1=0;
  int zapChannels[4096];
  int nzap=0;
  int overlay=-1;
  float overlayVal[MAX_OVERLAY];
  char overlayStr[MAX_OVERLAY][128];
  char overlayFile[128];
  int noverlay=0;
  fitsfile *fp;

  data = initialiseDset();
  

  for (i=0;i<argc;i++)
    {
      if (strcmp(argv[i],"-f")==0)
	strcpy(fname,argv[++i]);
      else if (strcmp(argv[i],"-noc1")==0)
	noc1=1;
      else if (strcmp(argv[i],"-g")==0)
	{
	  strcpy(grDev,argv[++i]);
	  interactive=0;
	}
      else if (strcmp(argv[i],"-h")==0)
	help();
      else if (strcmp(argv[i],"-overlay")==0)
	{
	  strcpy(overlayFile,argv[++i]);
	  overlay=1;
	}
    }
  if (overlay==1)
    {
      FILE *fin;
      char line[1024];
      noverlay=0;

      if (!(fin = fopen(overlayFile,"r")))
	  printf("Unable to open overlay file >%s<\n",overlayFile);
      else
	{
	  while (!feof(fin))
	    {
	      fgets(overlayStr[noverlay],1024,fin);
	      if (fscanf(fin,"%f",&overlayVal[noverlay])==1)
		{
		  if (overlayStr[noverlay][strlen(overlayStr[noverlay])-1] == '\n')
		    overlayStr[noverlay][strlen(overlayStr[noverlay])-1]='\0';
		  noverlay++;
		}
	    }
	  fclose(fin);
	}
    }
  fp   = openFitsFile(fname); 
  loadPrimaryHeader(fp,data);
  displayHeaderInfo(data);
  readBandpass(fp,bpass);
  nchan = data->phead.nchan;
  freq  = data->phead.freq;
  bw    = data->phead.bw;
  chanbw = data->phead.chanbw;

  for (i=0;i<nchan;i++)
    {
      fx[i] = freq-bw/2+(i+0.5)*chanbw;
      if (i==noc1)
	{
	  miny = maxy = bpass[i];
	  minx = maxx = fx[i];
	}
      else if (i!=0)
	{
	  if (bpass[i] > maxy) maxy = bpass[i];
	  if (bpass[i] < miny) miny = bpass[i];
	  if (fx[i] > maxx) maxx = fx[i];
	  if (fx[i] < minx) minx = fx[i];
	}
    }
  ominx = minx;
  omaxx = maxx;
  ominy = miny;
  omaxy = maxy;
  binw = fx[1]-fx[0];
  printf("Complete\n");

  cpgbeg(0,grDev,1,1);
  cpgask(0);
  do {
    cpgenv(minx,maxx,miny,maxy,0,1);
    cpglab("Frequency (MHz)","Amplitude (arbitrary)",fname);
    cpgbin(nchan-noc1,fx+noc1,bpass+noc1,0);
    if (overlay==1)
      {
	float tx[2],ty[2];
	cpgsls(4); cpgsci(2); cpgsch(0.8);
	for (i=0;i<noverlay;i++)
	  {
	    tx[0] = tx[1] = overlayVal[i];
	    ty[0] = miny;
	    ty[1] = maxy;
	    if (tx[1] > minx && tx[1] < maxx)
	      {
		cpgline(2,tx,ty);
		//		cpgtext(tx[1],ty[1]-0.05*(maxy-miny),overlayStr[i]);
		cpgptxt(tx[1]-0.004*(maxx-minx),ty[0]+0.05*(maxy-miny),90,0.0,overlayStr[i]);
	      }
	  }
	cpgsci(1); cpgsls(1); cpgsch(1);
      }
    if (interactive==1)
      {
	cpgcurs(&mx,&my,&key);
	if (key=='A')
	  {
	    int cc=-1;
	    int i;
	    for (i=0;i<nchan-1;i++)
	      {
		//		if ((bw > 0 && (mx > fx[i]-binw/2 && mx < fx[i]+binw/2)) ||
		//		    (bw < 0 && (mx > fx[i]+binw/2 && mx < fx[i]-binw/2)))
		if ((bw > 0 && (mx > fx[i] && mx < fx[i]+binw)) ||
		    (bw < 0 && (mx > fx[i] && mx < fx[i]+binw)))
		  {
		    cc = i;
		    break;
		  }
	      }
	    printf("mouse x = %g MHz, mouse y = %g, channel = %d, channel frequency = %g MHz\n",mx,my,cc,fx[cc]);
	  }
	else if (key=='X')
	  {
	    int cc=-1;
	    int i;
	    printf("Deleting %g %g %g\n",mx,fx[10],binw);
	    for (i=0;i<nchan-1;i++)
	      {
		//		if ((bw > 0 && (mx > fx[i]-binw/2 && mx < fx[i]+binw/2)) ||
		//		    (bw < 0 && (mx > fx[i]+binw/2 && mx < fx[i]-binw/2)))
		if ((bw > 0 && (mx > fx[i] && mx < fx[i]+binw)) ||
		    (bw < 0 && (mx > fx[i] && mx < fx[i]+binw)))
		  {
		    cc = i;
		    break;
		  }
	      }
	    printf("Want to delete = %d\n",cc);
	    if (cc != -1)
	      {
		bpass[cc] = 0;
		omaxy = bpass[noc1];
		zapChannels[nzap++] = cc;
		for (i=noc1;i<nchan;i++)
		  {
		    if (omaxy < bpass[i]) omaxy = bpass[i];
		  }
	      }
	  }
	else if (key=='z')
	  {
	    cpgband(2,0,mx,my,&mx2,&my2,&key);
	    if (mx > mx2) {maxx = mx; minx = mx2;}
	    else {maxx = mx2; minx = mx;}
	    
	    if (my > my2) {maxy = my; miny = my2;}
	    else {maxy = my2; miny = my;}	   
	  }
	else if (key=='u')
	  {
	    minx = ominx;
	    maxx = omaxx;
	    miny = ominy;
	    maxy = omaxy;
	  }
	else if (key=='l') // List the channels and frequencies to zap
	  {
	    int i;
	    sortInt(zapChannels,nzap);
	    printf("-------------------------------------------------------\n");
	    printf("Zap channels with first channel = 0\n\n");
	    for (i=0;i<nzap;i++)
	      printf("%d ",zapChannels[i]);
	    printf("\n\n");
	    printf("Zap channels with first channel = 1\n\n");
	    for (i=0;i<nzap;i++)
	      printf("%d ",zapChannels[i]+1);
	    printf("\n\n");
	    printf("Zap channels frequencies:\n\n");
	    for (i=0;i<nzap;i++)
	      printf("%g ",fx[zapChannels[i]]);
	    printf("\n\n");
	    printf("-------------------------------------------------------\n");
	  }
	else if (key=='%') // Enter percentage of the band edges to zap
	  {
	    float percent;
	    int i;

	    printf("Enter band edge percentage to zap ");
	    scanf("%f",&percent);
	    for (i=0;i<nchan;i++)
	      {
		if (i < nchan*percent/100.0 || i > nchan-(nchan*percent/100.0))
		  {
		    bpass[i] = 0;		    
		    zapChannels[nzap++] = i;

		  }
	      }
	    omaxy = bpass[noc1];
	    for (i=noc1;i<nchan;i++)
	      {
		if (omaxy < bpass[i]) omaxy = bpass[i];
	      }

	    // Unzoom
	    minx = ominx;
	    maxx = omaxx;
	    miny = ominy;
	    maxy = omaxy;
	  }

      }
  } while (key != 'q' && interactive==1);
  cpgend();
}
Beispiel #12
0
int main()
{
	//
	printf("\n====================================================================\n");
	printf("This program is able to simulate a variety of ecological\n");
	printf("situations in a 2D lattice\n");
	printf("====================================================================\n");

	//==========================================================================
	//--------------------------SYSTEM INITIALIZATIONS--------------------------
	//==========================================================================
	
	// initialize random seed
	srand(time(NULL));

	// force print all outputs (remove stdout buffer)
	setbuf(stdout, NULL);

	// initialize pgplot window
	if (!cpgopen("/XWINDOW"))
		errorCase(ERR_PGPLOT);
	cpgpap(20.0, 0.33);						// set window size
	cpgsubp(3,1);							// subdivide window into panels

	// color indexes (R, G, B)
	cpgscr(0, 0.0, 0.0, 0.0);				// empty space, black
	cpgscr(1, 1.0, 1.0, 1.0);
	cpgscr(10, 0.0, 0.0, 0.0);				// empty space, black
	cpgscr(11, 0.5, 0.5, 0.5);				// Trophic 1, gray
	cpgscr(12, 0.5, 1.0, 1.0);				// Trophic 2, cyan
	cpgscr(13, 1.0, 0.5, 0.0);				// Trophic 3, orange
	cpgscr(14, 1.0, 0.0, 0.0);
	cpgscir(10,NUMB_TROPHIC+10);


	//==========================================================================
	//--------------------------VARIABLE INITIALIZATIONS------------------------
	//==========================================================================

	// generic variables
	int i, j, k;						// counters

	// simulation environment
	int** simEnv = allocateArray2DInt(ENV_SIZE_X, ENV_SIZE_Y);
	int** simEnvAge = allocateArray2DInt(ENV_SIZE_X, ENV_SIZE_Y);
	int* simLocal = allocateArray1DInt(5);

	// inputs
	char input;

	// current location and time
	int x,y;
	int tGlobal,t;
	int flagUpdate;

	// rates
	float predationRates[NUMB_TROPHIC-1] = RATE_PRED;
	float deathRates[NUMB_TROPHIC] = RATE_DEATH;

	//float aBirth = 0;			// A+0 -> A+A
//	float abPred = 0;			// B+A -> B+B
//	float bDeath = 0;			//   B ->   0

//	int aFlag; int abFlag; int bFlag;

	// population counts;
	int popCount[NUMB_TROPHIC];
	float popDens[NUMB_TROPHIC];
	float popDensOld[NUMB_TROPHIC];
	for (i=0; i<NUMB_TROPHIC; i++){
		popCount[i] = 0;
		popDens[i] = 0.0;
		popDensOld[i] = 1.0/(float)INIT_DENSITY;
	}
	float* ageStructure = allocateArray1D(ENV_SIZE_TOTAL);


	// pgplot variables
	float* plotImg = allocateArray1D(ENV_SIZE_TOTAL);
	//float TR[6] = {0, 1, 0, 0, 0, 1};
	float TR[6] = {0, 0, 1, ENV_SIZE_Y, -1, 0};
	float plotMinBound = 0.0;
	float plotMaxBound = (float)NUMB_TROPHIC;


	//==========================================================================
	//--------------------------ACTUAL CODE-------------------------------------
	//==========================================================================
	
	// environment initialization
	randomizeArray2DInt(simEnv, ENV_SIZE_X, ENV_SIZE_Y, NUMB_TROPHIC);

	// load initial display
	for (i=0; i<ENV_SIZE_X; i++)
		for (j=0; j<ENV_SIZE_Y; j++)
			plotImg[i*ENV_SIZE_Y+j] = (float)(simEnv[i][j]);
	cpgpanl(1,1);
	cpgswin(0, ENV_SIZE_X-1, 0, ENV_SIZE_Y-1);
	cpgsvp(0.01, 0.99, 0.01, 0.99);
	cpgimag(plotImg, ENV_SIZE_Y, ENV_SIZE_X, 1, ENV_SIZE_Y, 1, ENV_SIZE_X, plotMinBound, plotMaxBound, TR);

	// Load graph labels
	// Population Density vs Time Plot
	cpgpanl(2,1);
	cpgsvp(0.08, 0.92, 0.08, 0.92);
	cpgswin(0, ENV_SIZE_X, 0, 1);
	cpgbox("ABCINTS", 0.0, 0, "ABCINTS", 0.0, 0);
	cpglab("Time", "Population Density", "");

	// Phase Portrait Plot
	cpgpanl(3,1);
	cpgsvp(0.08, 0.92, 0.08, 0.92);
	cpgswin(0, 1, 0, 1);
	cpgbox("ABCINTS", 0.0, 0, "ABCINTS", 0.0, 0);
	cpglab("", "", "Phase Portrait");
	cpgsci(11);
	cpglab("Population Density SpA", "", "");
	cpgsci(12);
	cpglab("", "Population Density SpB", "");
	
	// initial delay to visualize starting matrix
	for (t=0; t<500000000; t++){}

	tGlobal = 1;
	while(1){
		//aFlag = 0; abFlag = 0; bFlag = 0;

		// run simulation for a full Monte Carlo timestep (ENV_SIZE_X*ENV_SIZE_Y)
		for (t=0; t<ENV_SIZE_TOTAL; t++){
			ecoRun(simEnv, simEnvAge, simLocal, predationRates, deathRates);
		}
		incrementAge(simEnvAge);

	

		// plot stuffs
		if ((tGlobal%1) == 0){

			// calculate population densities
			updatePopDens(simEnv, popCount, popDens);

			// PLOT population densities
			cpgpanl(2,1);
			cpgsvp(0.08, 0.92, 0.08, 0.92);
			cpgswin(0, ENV_SIZE_X, 0, 1);
			for (i=0; i<NUMB_TROPHIC; i++){
				cpgsls(1); cpgsci(i+11);				// line style and color
				cpgmove((tGlobal-1), popDensOld[i]);
				cpgdraw(tGlobal, popDens[i]);
			}

			//printArray2DInt(simEnvAge, ENV_SIZE_X, ENV_SIZE_Y);

			// PLOT age structure
			/*updateAgeStructure(simEnv, simEnvAge, ageStructure, 1);
			cpgpanl(3,1);
			cpgsvp(0.08, 0.92, 0.08, 0.92);
			cpgswin(0, 10, 0, (ENV_SIZE_TOTAL/10));
			cpgsls(1); cpgsci(1);						// line style and color
			cpgeras();
			cpgbox("ABCINTS", 0.0, 0, "ABCINTS", 0.0, 0);
			cpglab("Age", "Number of Individuals", "Age Structure");
			cpghist(popCount[1], ageStructure, 0, 10, 10, 1);*/

			
			// PLOT phase portrait
			cpgpanl(3,1);
			cpgsvp(0.08, 0.92, 0.08, 0.92);
			cpgswin(0, 1, 0, 1);
			cpgsls(1); cpgsci(1);						// line style and color
			cpgmove(popDensOld[0], popDensOld[1]);
			cpgdraw(popDens[0], popDens[1]);

			for (i=0; i<NUMB_TROPHIC; i++)
				popDensOld[i] = popDens[i];
		}

		// load array and display on pgplot
		if ((tGlobal%1) == 0){
			cpgpanl(1,1);
			cpgswin(0, ENV_SIZE_X, 0, ENV_SIZE_Y);
			cpgsvp(0.01, 0.99, 0.01, 0.99);
			for (i=0; i<ENV_SIZE_X; i++)
				for (j=0; j<ENV_SIZE_Y; j++)
					plotImg[i*ENV_SIZE_Y+j] = (float)(simEnv[i][j]);
			cpgimag(plotImg, ENV_SIZE_Y, ENV_SIZE_X, 1, ENV_SIZE_Y, 1, ENV_SIZE_X, plotMinBound, plotMaxBound, TR);
		}


		tGlobal++;
		//for (t=0; t<10000000; t++){}
	}
}
Beispiel #13
0
void doPlot(pulsar *psr,int npsr,float *scale,int nScale,char *grDev,int plotUs,float fontSize,float centreMJD,int ptStyle,float ptSize,int error,float minyv,float maxyv,float minxv,float maxxv,int nOverlay,float labelsize,float fracX)
{
  int i,j,fitFlag=2,exitFlag=0,scale1=0,scale2,count[MAX_PSR],p,xautoscale=0,k,graphics=1;
  int yautoscale=0,plotpre=1;
  int ps,pe,pi;
  int time=0;
  char xstr[1000],ystr[1000];
  float px[2],py[2],pye1[2],pye2[2];
  float x[MAX_PSR][MAX_OBSN],y[MAX_PSR][MAX_OBSN],yerr1[MAX_PSR][MAX_OBSN],yerr2[MAX_PSR][MAX_OBSN],tmax,tmin,tmaxy1,tminy1,tmaxy2,tminy2;
  float sminy[MAX_PSR],smaxy[MAX_PSR];
  float minx[MAX_PSR],maxx[MAX_PSR],miny[MAX_PSR],maxy[MAX_PSR],plotx1,plotx2,ploty1,ploty2,mean;
  float fx[2],fy[2];
  float mouseX,mouseY;
  char key;
  //  float widthPap=0.0,aspectPap=0.618;
  float widthPap=0.0,aspectPap=1;
  float xx[MAX_OBSN],yy[MAX_OBSN],yyerr1[MAX_OBSN],yyerr2[MAX_OBSN];
  int num=0,colour;

  /* Obtain a graphical PGPLOT window */
  cpgbeg(0,grDev,1,1);
  //    cpgpap(widthPap,aspectPap);
  cpgsch(fontSize);
  cpgscf(2);
  cpgslw(2);
  cpgask(0);

  for (p=0;p<npsr;p++)
    {
      scale2 = psr[p].nobs;
      
      /*      sprintf(xstr,"MJD-%.1Lf",psr[0].param[param_pepoch].val[0]); */
      if (centreMJD == -1)
	sprintf(xstr,"Year"); 
      else
	sprintf(xstr,"MJD-%.1f",centreMJD); 

      sprintf(ystr,"Residual (\\gmsec)");
      
      count[p]=0;
      printf("points = %d\n",psr[p].nobs);
      for (i=0;i<psr[p].nobs;i++)
	{	  
	  if (psr[p].obsn[i].deleted == 0 &&
	      (psr[p].param[param_start].paramSet[0]!=1 || psr[p].param[param_start].fitFlag[0]!=1 ||
	       psr[p].param[param_start].val[0] < psr[p].obsn[i].bat) &&
	      (psr[p].param[param_finish].paramSet[0]!=1 || psr[p].param[param_finish].fitFlag[0]!=1 ||
	       psr[p].param[param_finish].val[0] > psr[p].obsn[i].bat))
	    {
	      /* x[p][count[p]] = (double)(psr[p].obsn[i].bat-psr[0].param[param_pepoch].val[0]);	     	       */
	      if (centreMJD == -1)
		x[p][count[p]] = calcYr(psr[p].obsn[i].bat);
	      else
		x[p][count[p]] = (double)(psr[p].obsn[i].bat-centreMJD); 
	      y[p][count[p]] = (double)psr[p].obsn[i].residual*1.0e6;
	      if (nScale>0)
		y[p][count[p]] *= scale[p];
	      count[p]++;
	    }
	}
      /* Remove mean from the residuals and calculate error bars */
      mean = findMean(y[p],psr,p,scale1,count[p]);
      count[p]=0;
      for (i=0;i<psr[p].nobs;i++)
	{
	  if (psr[p].obsn[i].deleted==0   &&
	      (psr[p].param[param_start].paramSet[0]!=1 || psr[p].param[param_start].fitFlag[0]!=1 ||
	       psr[p].param[param_start].val[0] < psr[p].obsn[i].bat) &&
	      (psr[p].param[param_finish].paramSet[0]!=1 || psr[p].param[param_finish].fitFlag[0]!=1 ||
	       psr[p].param[param_finish].val[0] > psr[p].obsn[i].bat))
	    {
	      psr[p].obsn[i].residual-=mean/1.0e6;
	      y[p][count[p]]-=mean;
	      yerr1[p][count[p]] = y[p][count[p]]-(float)psr[p].obsn[i].toaErr;
	      yerr2[p][count[p]] = y[p][count[p]]+(float)psr[p].obsn[i].toaErr;
	      count[p]++;
	    }
	}
    	  
      /* Get scaling for graph */
      if (minxv == maxxv) {
	minx[p] = findMin(x[p],psr,p,scale1,count[p]);
	maxx[p] = findMax(x[p],psr,p,scale1,count[p]);
      }
      else {
	minx[p] = minxv;
	maxx[p] = maxxv;
      }
      if (minyv == maxyv){
	miny[p] = findMin(y[p],psr,p,scale1,count[p]);
	maxy[p] = findMax(y[p],psr,p,scale1,count[p]);
      }
      else {
	miny[p] = minyv;
	maxy[p] = maxyv;
      }
      sminy[p] = miny[p]/1e6;
      smaxy[p] = maxy[p]/1e6;
    }
  for (p=0;p<npsr;p++)
    {
      for (i=0;i<count[p];i++)
	{
	  y[p][i] = (y[p][i]-miny[p])/(maxy[p]-miny[p]);
	  yerr1[p][i] = (yerr1[p][i]-miny[p])/(maxy[p]-miny[p]);
	  yerr2[p][i] = (yerr2[p][i]-miny[p])/(maxy[p]-miny[p]);
	}
      //      maxy[p] = 1.0;
      //      miny[p] = 0.0;
    }
  

  tmin = findMinVal(minx,npsr);
  tmax = findMaxVal(maxx,npsr);

  tminy2 = 0.0; //findMinVal(miny,npsr);
  tmaxy2 = 1.0; //findMaxVal(maxy,npsr);

  plotx1 = tmin-(tmax-tmin)*0.1;
  plotx2 = tmax+(tmax-tmin)*0.1;
  
  //  ploty1 = tminy2-(tmaxy2-tminy2)*0.1;
  //  ploty2 = tmaxy2+(tmaxy2-tminy2)*0.1;
	
  ploty1 = 0.1;
  ploty2 = 0.9;

  for (p=0;p<npsr;p++)
    {
      for (i=0;i<count[p];i++)
	{
	  y[p][i]=(p)+ploty1+y[p][i]*(ploty2-ploty1);
	  yerr1[p][i]=(p)+ploty1+yerr1[p][i]*(ploty2-ploty1);
	  yerr2[p][i]=(p)+ploty1+yerr2[p][i]*(ploty2-ploty1);
	}
    } 
  
  printf("ytick = %g\n",ploty2-ploty1);
      /*  cpgenv(plotx1,plotx2,ploty1,ploty2+(ploty2-ploty1)*(npsr-1),0,0); */
  //  cpgenv(plotx1,plotx2,0,npsr+1,0,-1);

  if (labelsize!=-1)
    cpgsch(labelsize);
  cpgsvp(fracX,1.0,0.1,1.0);
  cpgswin(0,1,0,npsr);
  cpgbox("ABC",0.0,0,"C",0.0,0);
  cpgsch(fontSize);
  char str[1000];
  for (p=0;p<npsr;p++)
    {
      cpgsch(fontSize);
      //      cpgtext(tmax+(tmax-tmin)*0.05,p+1.5-0.5,psr[p].name);
      cpgtext(0,p+0.6,psr[p].name);
      //      cpgsch(fontSize);
      if (plotUs==0)
	{
	  sprintf(str,"%.2f",(double)((smaxy[p]-sminy[p])*psr[p].param[param_f].val[0]));
	  cpgtext(0,p+0.4,str);
	  //	  cpgtext(tmax+(tmax-tmin)*0.05,p+1.1-0.5,str);
	}
      else
	{
	  sprintf(str,"%.2f\\gms",(double)((smaxy[p]-sminy[p])/1e-6));
	  //	  cpgtext(tmax+(tmax-tmin)*0.05,p+1.1-0.5,str);
	  cpgtext(0,p+0.1,str);
	}
      cpgsch(1);
      px[0] = 0;
      //      px[1] = tmax; //+(tmax-tmin)*0.03;
	px[1] = 1;
      py[0] = p;
      py[1] = p;
      cpgline(2,px,py);
      
    }
  if (labelsize!=-1)
    cpgsch(labelsize);

  cpgsvp(0.1,fracX,0.1,1.0);
  cpgswin(plotx1,plotx2,0,npsr);
  cpgbox("ATNSBC",0.0,0,"B",0.0,0);
  cpglab(xstr,"","");	    
  cpgsch(fontSize);

  for (p=0;p<npsr;p++)
    {
      cpgsls(1);
      px[0] = plotx1;
      //      px[1] = tmax; //+(tmax-tmin)*0.03;
      px[1] = plotx2;
      py[0] = p;
      py[1] = p;
      cpgline(2,px,py);
      cpgsls(4);
      px[0] = tmin;
      px[1] = tmax+(tmax-tmin)*0.03;

      py[0]=py[1] =(p)+ploty1+(-miny[p]/(maxy[p]-miny[p]))*(ploty2-ploty1);
      //      py[0]=py[1] = (p)+ploty1;
      //      py[0] = py[1] = (0-miny[p])/(maxy[p]-miny[p])/(ploty2-ploty1)+p;
      cpgline(2,px,py);

      px[0] = plotx1+0.005*(plotx2-plotx1);
      py[0] = p;
      pye1[0] = p + 5/(ploty2-ploty1);
      pye2[0] = p - 5/(ploty2-ploty1);
      cpgsls(1);
      cpgsch(3);
      //      cpgerry(1,px,pye1,pye2,1); 
      cpgsch(1);

      for (colour=0;colour<5;colour++)
	{
	  num=0;
	  for (i=0;i<count[p];i++)
	    {
	      if ((colour==0 && psr[p].obsn[i].freq<=500) ||
		  (colour==1 && psr[p].obsn[i].freq>500 && psr[p].obsn[i].freq<=1000) ||
		  (colour==2 && psr[p].obsn[i].freq>1000 && psr[p].obsn[i].freq<=1500) ||
		  (colour==3 && psr[p].obsn[i].freq>1500 && psr[p].obsn[i].freq<=3300) ||
		  (colour==4 && psr[p].obsn[i].freq>3300))
		{
		  xx[num]=x[p][i];
		  yy[num]=y[p][i];
		  yyerr1[num]=yerr1[p][i];
		  yyerr2[num]=yerr2[p][i];
		  //		  printf("plotting: %g\n",yy[num]);

		  num++;
		}
	    }
	  cpgsci(colour+1);
	  cpgsch(ptSize);
	  cpgpt(num,xx,yy,ptStyle);
	  if (error==1)
	    cpgerry(num,xx,yyerr1,yyerr2,1);
	  cpgsch(fontSize);
	  // Plot arrow giving one period
	  fx[0] = fx[1] = tmin-(tmax-tmin)*0.05;
	  //	  fy[0] = (p+1)+0.5-(float)(1.0/psr[p].param[param_f].val[0])/2.0/(ploty2-ploty1);
	  //	  fy[1] = (p+1)+0.5+(float)(1.0/psr[p].param[param_f].val[0])/2.0/(ploty2-ploty1);

	  //	  fy[0] = (-(float)(1.0/psr[p].param[param_f].val[0])/2.0/1.0e6 - miny[p])/(maxy[p]-miny[p])/(ploty2-ploty1) + (p+1)+0.5;
	  //	  fy[1] = ((float)(1.0/psr[p].param[param_f].val[0])/2.0/1.0e6 - miny[p])/(maxy[p]-miny[p])/(ploty2-ploty1) + (p+1)+0.5;
	  fy[0] = (p+1)+0.5+(float)(1.0/psr[p].param[param_f].val[0])/2.0/(maxy[p]-miny[p])*1e6;
	  fy[1] = (p+1)+0.5-(float)(1.0/psr[p].param[param_f].val[0])/2.0/(maxy[p]-miny[p])*1e6;
	  if (fy[0] > (p+1)+1) fy[0] = (p+1)+1;
	  if (fy[1] < (p+1)) fy[1] = (p+1);
	  
	  //	  cpgsls(1); cpgline(2,fx,fy); cpgsls(1);
	}
      cpgsci(1);
    }

  
  cpgend();
}
Beispiel #14
0
/* write labels for x-axis, y-axis, and top of plot */
static void _pglab (char *a, char *b, char *c)
{
   cpglab (a, b, c);
}
int plot_map()
{
  int nx=720;
  int ny=180;
  int deli, delj;
  float value;
  int counter;
  float mapplot[720][180];

  int i=0, j=0, k=0;
  float tr[6]= {0.0, 0.5, 0.0, 0.0, 0.0, 0.5};

  float fmin=1, fmax=0;
  //  float RL[9]={-0.5, 0.004, 0.006, 0.008, 0.02, 0.04, 0.06, 0.08, 0.1};
  float RL[9]={-0.5, 0.0, 0.04, 0.08, 0.2, 0.4, 0.6, 0.8, 1.0};
  float RR[9]={0.0, 0.0, 0.0, 0.0, 0.6, 1.0, 1.0, 1.0, 1.0};
  float RG[9]={0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.6, 1.1, 1.0};
  float RB[9]={0.0, 0.3, 0.8, 1.0, 0.3, 0.0, 0.0, 0.0, 1.0};
  float bright=0.5; //0.53
  float contra=1.0; //1.0

  //map larger array into smaller array

  for (j=1; j<ny; j++)
    {
      for (i=1; i<nx; i++)
	{
	  value=0;
	  counter=0;
	  for (deli=0; deli<=5; deli++)
	    {
	      for (delj=0; delj<=5; delj++)
		{
		  value=value+mapx[sat_choice][(5*i)+deli][(5*j)+delj];		
		  if (mapx[sat_choice][(5*i)+deli][(5*j)+delj]>0)
		  {
		    counter++;
		    //		    printf("%i %f\n", counter, value/counter);
		  }
	      }
	    }
	  if (counter==0) mapplot[i][j]=value;
	  else mapplot[i][j]=value/counter;
	}
    }


 
  for (j=1; j<ny; j++)
    {
      for (i=1; i<nx; i++)
	{
	  k=(j-1)*nx + (i-1);
	  f[k]=mapplot[i][j];
	  if (f[k] <fmin) fmin = f[k];
	  if (f[k] >fmax) fmax = f[k];
	}
    }

  printf("min=%f max=%f\n", fmin, fmax);
  fmax=0.1;
  cpgslct(pg_id);
  cpgeras();
  cpgenv(0.0, 360, 0.0, 90, 1.0, -2); 
    cpglab("Azimuth", "Elevation", "Antenna Power Pattern  [Data: May 7-22, 2006]");
  cpgctab(RL, RR, RG, RB, 9, contra, bright);
    cpgimag(f, (float)nx, (float)ny, 1.0, (float)nx, 1.0, (float)ny,  fmin, fmax, tr);
  cpgbox("BCNST1",0.0,0,"BCNST1",0.0,0);
     return 0;
}
Beispiel #16
0
void doPlot(pulsar *psr,int npsr,int overlay)
{
  int i,j,fitFlag=1,exitFlag=0,scale1=0,scale2,count,p,xautoscale=1,k,graphics=1;
  int yautoscale=1,plotpre=1;
  int time=0;
  char xstr[1000],ystr[1000];
  float x[MAX_OBSN],y[MAX_OBSN],yerr1[MAX_OBSN],yerr2[MAX_OBSN],tmax,tmin,tmaxy1,tminy1,tmaxy2,tminy2;
  float minx,maxx,miny,maxy,plotx1,plotx2,ploty1,ploty2,mean;
  float mouseX,mouseY;
  float fontSize=1.8;
  char key;
  float widthPap=0.0,aspectPap=0.618;

  /* Obtain a graphical PGPLOT window */
  if (overlay==1)
    cpgbeg(0,"?",2,1);
  else
    cpgbeg(0,"?",2,npsr);
  cpgpap(widthPap,aspectPap);
  cpgsch(fontSize);
  cpgask(0);

  do {
    for (p=0;p<npsr;p++)
      {
	scale2 = psr[p].nobs;
	for (j=0;j<2;j++)
	  {
	    if (j==0) fitFlag=1;
	    else if (j==1) fitFlag=2;

	    ld_sprintf(xstr,"MJD-%.1Lf",psr[0].param[param_pepoch].val[0]); 
	    sprintf(ystr,"Residual (\\gmsec)");

	    count=0;
	    for (i=0;i<psr[p].nobs;i++)
	      {
		if (psr[p].obsn[i].deleted == 0  &&
	    (psr[p].param[param_start].paramSet[0]!=1 || psr[p].param[param_start].fitFlag[0]!=1 ||
	      psr[p].param[param_start].val[0] < psr[p].obsn[i].bat) &&
	    (psr[p].param[param_finish].paramSet[0]!=1 || psr[p].param[param_finish].fitFlag[0]!=1 ||
	     psr[p].param[param_finish].val[0] > psr[p].obsn[i].bat))
		  {
		    if (xautoscale==1)
		      x[count] = (double)(psr[p].obsn[i].bat-psr[p].param[param_pepoch].val[0]);
		    else
		      x[count] = (double)(psr[p].obsn[i].bat-psr[0].param[param_pepoch].val[0]);
		    
		    if (fitFlag==1)  /* Get pre-fit residual */
		      y[count] = (double)psr[p].obsn[i].prefitResidual*1.0e6;
		    else if (fitFlag==2) /* Post-fit residual */
		      y[count] = (double)psr[p].obsn[i].residual*1.0e6;
		    count++;
		  }
	      }
	    /* Remove mean from the residuals and calculate error bars */
	    mean = findMean(y,psr,p,scale1,count);
	    count=0;
	    for (i=0;i<psr[p].nobs;i++)
	      {
		if (psr[p].obsn[i].deleted==0   &&
	    (psr[p].param[param_start].paramSet[0]!=1 || psr[p].param[param_start].fitFlag[0]!=1 ||
	      psr[p].param[param_start].val[0] < psr[p].obsn[i].bat) &&
	    (psr[p].param[param_finish].paramSet[0]!=1 || psr[p].param[param_finish].fitFlag[0]!=1 ||
	     psr[p].param[param_finish].val[0] > psr[p].obsn[i].bat))
		  {
		    psr[p].obsn[i].residual-=mean/1.0e6;
		    y[count]-=mean;
		    yerr1[count] = y[count]-(float)psr[p].obsn[i].toaErr;
		    yerr2[count] = y[count]+(float)psr[p].obsn[i].toaErr;
		    count++;
		  }
	      }
	    
	    /* Get scaling for graph */
	    minx = findMin(x,psr,p,scale1,count);
	    maxx = findMax(x,psr,p,scale1,count);
	    if (xautoscale==1)
	      {
		plotx1 = minx-(maxx-minx)*0.1;
		plotx2 = maxx+(maxx-minx)*0.1;
	      }
	    else
	      {
		plotx1 = tmin-(tmax-tmin)*0.1;
		plotx2 = tmax+(tmax-tmin)*0.1;
	      }
	    miny = findMin(y,psr,p,scale1,count);
	    maxy = findMax(y,psr,p,scale1,count);

	    if (yautoscale==1)
	      {
		ploty1 = miny-(maxy-miny)*0.1;
		ploty2 = maxy+(maxy-miny)*0.1;
	      }
	    else
	      {
		if (j==0)
		  {
		    ploty1 = tminy1-(tmaxy1-tminy1)*0.1;
		    ploty2 = tmaxy1+(tmaxy1-tminy1)*0.1;
		  }
		else
		  {
		    ploty1 = tminy2-(tmaxy2-tminy2)*0.1;
		    ploty2 = tmaxy2+(tmaxy2-tminy2)*0.1;
		  }
	      }

	    /* Plot the residuals */	    
	    if (plotpre==1 || j!=0)
	      {
		float xx[MAX_OBSN],yy[MAX_OBSN],yyerr1[MAX_OBSN],yyerr2[MAX_OBSN];
		int num=0,colour;
		if (overlay==0 || (overlay==1 && p==0))
		  {
		    cpgenv(plotx1,plotx2,ploty1,ploty2,0,0);
		    cpglab(xstr,ystr,psr[p].name);	    
		  }

		for (colour=0;colour<5;colour++)
		  {
		    num=0;
		    for (i=0;i<count;i++)
		      {
			if ((colour==0 && psr[p].obsn[i].freq<=500) ||
			    (colour==1 && psr[p].obsn[i].freq>500 && psr[p].obsn[i].freq<=1000) ||
			    (colour==2 && psr[p].obsn[i].freq>1000 && psr[p].obsn[i].freq<=1500) ||
			    (colour==3 && psr[p].obsn[i].freq>1500 && psr[p].obsn[i].freq<=3300) ||
			    (colour==4 && psr[p].obsn[i].freq>3300))
			  {
			    xx[num]=x[i];
			    yy[num]=y[i];
			    yyerr1[num]=yerr1[i];
			    yyerr2[num]=yerr2[i];
			    num++;
			  }
		      }
		    cpgsci(colour+1);
		    if (overlay==1)
		      cpgsci(p+1);
		    cpgpt(num,xx,yy,16);
		    cpgerry(num,xx,yyerr1,yyerr2,1);
		  }
		cpgsci(1);
	      }
	  }
      }
    printf("------------------------------\n");
    printf("`a'     set aspect ratio\n");
    printf("`f'     set font size\n");
    printf("`g'     set graphics device\n");
    printf("`q'     quit\n");
    printf("`x'     toggle autoscale x axis\n");
    printf("`y'     toggle autoscale y axis\n");
    printf("`p'     toggle prefit plotting\n");
    printf("`r'     output residuals to file\n");

    if (graphics==1)
      {
	cpgcurs(&mouseX,&mouseY,&key);
	
	/* Check key press */
	if (key=='q') exitFlag=1;
	if (key=='p') {
	  plotpre*=-1;
	  if (plotpre==-1)
	    {
	      cpgend();
	      if (overlay==1)
		cpgbeg(0,"/xs",1,1);
	      else
		cpgbeg(0,"/xs",1,npsr);
	      cpgpap(widthPap,aspectPap);
	      cpgsch(fontSize);
	      cpgask(0);	      
	    }
	  else
	    {
	      cpgend();
	      if (overlay==1)
		cpgbeg(0,"/xs",2,1);
	      else
		cpgbeg(0,"/xs",2,npsr);
	      cpgpap(widthPap,aspectPap);
	      cpgsch(fontSize);
	      cpgask(0);	      
	    }
	}
	else if (key=='a') /* Change aspect ratio */
	  {
	    printf("Please enter a new aspect ratio ");
	    scanf("%f",&aspectPap);
	    cpgend();
	    cpgbeg(0,"/xs",2,npsr);
	    cpgpap(widthPap,aspectPap);
	    cpgsch(fontSize);
	    cpgask(0);	      
	  }
	else if (key=='f') /* Change font size */
	  {
	    printf("Please enter a new font size ");
	    scanf("%f",&fontSize);
	    cpgend();
	    cpgbeg(0,"/xs",2,npsr);
	    cpgpap(widthPap,aspectPap);
	    cpgsch(fontSize);
	    cpgask(0);	      
	  }
	else if (key=='g')
	  {
	    graphics=0;
	    cpgend();
	    if (plotpre==-1)
	      {
		cpgend();
		if (overlay==1)
		  cpgbeg(0,"?",1,1);
		else
		  cpgbeg(0,"?",1,npsr);
		cpgpap(widthPap,aspectPap);
		cpgsch(fontSize);
		cpgask(0);	      
	      }
	    else
	      {
		cpgend();
		if (overlay==1)
		  cpgbeg(0,"?",1,1);
		else
		  cpgbeg(0,"?",2,npsr);
		cpgpap(widthPap,aspectPap);
		cpgsch(fontSize);
		cpgask(0);	      
	      }
	  }
	else if (key=='r') /* Output residuals to file */
	  {
	    FILE *fout;
	    char fname[1000];
	    int ii,jj;

	    for (ii=0;ii<npsr;ii++)
	      {
		sprintf(fname,"%s.res",psr[ii].name);
		fout = fopen(fname,"w");
		/* Print header */
		fprintf(fout,"#PSR %s\n",psr[ii].name);
		ld_fprintf(fout,"#F0  %.14Lf\n",psr[ii].param[param_f].val[0]);
		fprintf(fout,"#RAJ %s\n",psr[ii].rajStrPre);
		fprintf(fout,"#DECJ %s\n",psr[ii].decjStrPre);
		for (jj=0;jj<psr[ii].nobs;jj++)
		  fprintf(fout,"%.5lf %.5lg %.5lg\n",
			  (double)(psr[ii].obsn[jj].bat-psr[0].param[param_pepoch].val[0]),
			  (double)(psr[ii].obsn[jj].residual),(double)(psr[ii].obsn[jj].toaErr)/1.0e6);
		fclose(fout);
	      }
	  }
	else if (key=='x') 
	  {
	    xautoscale*=-1;
	    if (xautoscale==-1)
	      {
		for (k=0;k<npsr;k++)
		  {
		    count=0;
		    for (i=0;i<psr[k].nobs;i++)
		      {
			if (psr[k].obsn[i].deleted==0   &&
			    (psr[k].param[param_start].paramSet[0]!=1 || psr[k].param[param_start].fitFlag[0]!=1 ||
			     psr[k].param[param_start].val[0] < psr[k].obsn[i].bat) &&
			    (psr[k].param[param_finish].paramSet[0]!=1 || psr[k].param[param_finish].fitFlag[0]!=1 ||
			     psr[k].param[param_finish].val[0] > psr[k].obsn[i].bat))

			  {x[count] = (double)(psr[k].obsn[i].bat-psr[0].param[param_pepoch].val[0]); count++;}
		      }
		    minx = findMin(x,psr,k,scale1,count);
		    maxx = findMax(x,psr,k,scale1,count);
		    if (k==0)
		      {
			tmin = minx;
			tmax = maxx;
			printf("Have1 tmin = %f, tmax = %f\n",tmin,tmax);
		      }
		    else
		      {
			if (tmin > minx) tmin = minx;
			if (tmax < maxx) tmax = maxx;
			printf("Have2 tmin = %f, tmax = %f\n",tmin,tmax);

		      }
		  }
	      }
	  }       
	else if (key=='y') 
	  {
	    yautoscale*=-1;
	    if (yautoscale==-1)
	      {
		for (k=0;k<npsr;k++)
		  {
		    count=0;
		    for (i=0;i<psr[k].nobs;i++)
		      {
			if (psr[k].obsn[i].deleted==0   &&
			    (psr[k].param[param_start].paramSet[0]!=1 || psr[k].param[param_start].fitFlag[0]!=1 ||
			     psr[k].param[param_start].val[0] < psr[k].obsn[i].bat) &&
			    (psr[k].param[param_finish].paramSet[0]!=1 || psr[k].param[param_finish].fitFlag[0]!=1 ||
			     psr[k].param[param_finish].val[0] > psr[k].obsn[i].bat))			  
			  {y[count] = (double)psr[k].obsn[i].prefitResidual*1e6; count++;}
		      }
		    miny = findMin(y,psr,k,scale1,count);
		    maxy = findMax(y,psr,k,scale1,count);
		    if (k==0)
		      {
			tminy1 = miny;
			tmaxy1 = maxy;
		      }
		    else
		      {
			if (tminy1 > miny) tminy1 = miny;
			if (tmaxy1 < maxy) tmaxy1 = maxy;
		      }

		    count=0;
		    for (i=0;i<psr[k].nobs;i++)
		      {
			if (psr[k].obsn[i].deleted==0   &&
			    (psr[k].param[param_start].paramSet[0]!=1 || psr[k].param[param_start].fitFlag[0]!=1 ||
			     psr[k].param[param_start].val[0] < psr[k].obsn[i].bat) &&
			    (psr[k].param[param_finish].paramSet[0]!=1 || psr[k].param[param_finish].fitFlag[0]!=1 ||
			     psr[k].param[param_finish].val[0] > psr[k].obsn[i].bat))
			  {y[count] = (double)psr[k].obsn[i].residual*1e6; count++;}
		      }
		    miny = findMin(y,psr,k,scale1,count);
		    maxy = findMax(y,psr,k,scale1,count);
		    if (k==0)
		      {
			tminy2 = miny;
			tmaxy2 = maxy;
		      }
		    else
		      {
			if (tminy2 > miny) tminy2 = miny;
			if (tmaxy2 < maxy) tmaxy2 = maxy;
		      }
		  }
		printf("Have tminy2 = %g %g\n",tminy2,tmaxy2);
	      }
	  }       
	else printf("Unknown key press %c\n",key);
      }
    else
      {
	graphics=1;

	cpgend();
	if (plotpre==-1)
	  {
	    cpgend();
	    if (overlay==1)
	      cpgbeg(0,"/xs",1,1);
	    else
	      cpgbeg(0,"/xs",1,npsr);
	    cpgpap(widthPap,aspectPap);
	    cpgsch(fontSize);
	    cpgask(0);	      
	  }
	else
	  {
	    cpgend();
	    if (overlay==1)
	      cpgbeg(0,"/xs",2,1);
	    else
	      cpgbeg(0,"/xs",2,npsr);
	    cpgpap(widthPap,aspectPap);
	    cpgsch(fontSize);
	    cpgask(0);	      
	  }
      }
  } while (exitFlag==0);
  
  cpgend();
}
Beispiel #17
0
int closure (
  const char ctypeS[9],
  double restfrq,
  double restwav,
  int    naxisj,
  double crpixj,
  double cdeltX,
  double crvalX)

{
  char ptype, sname[32], title[80], units[8], xtype, ylab[80];
  int  nFail = 0, restreq, stat1[NSPEC], stat2[NSPEC], status;
  register int j;
  float  tmp, x[NSPEC], xmin, xmax, y[NSPEC], ymax, ymin;
  double cdeltS, clos[NSPEC], crvalS, dSdX, resid, residmax, spec1[NSPEC],
         spec2[NSPEC];
  struct spcprm spc;


  /* Get keyvalues for the required spectral axis type. */
  if ((status = spcxps(ctypeS, crvalX, restfrq, restwav, &ptype, &xtype,
                       &restreq, &crvalS, &dSdX))) {
    printf("ERROR %d from spcxps() for %s.\n", status, ctypeS);
    return 1;
  }
  cdeltS = cdeltX * dSdX;

  spcini(&spc);

  if (ctypeS[5] == 'G') {
    /* KPNO MARS spectrograph grism parameters. */
    spc.pv[0] = mars[0];
    spc.pv[1] = mars[1];
    spc.pv[2] = mars[2];
    spc.pv[3] = mars[3];
    spc.pv[4] = mars[4];
    spc.pv[5] = mars[5];
    spc.pv[6] = mars[6];
  }

  /* Construct the axis. */
  for (j = 0; j < naxisj; j++) {
    spec1[j] = (j+1 - crpixj)*cdeltS;
  }

  printf("%4s (CRVALk+w) range: %13.6e to %13.6e, step: %13.6e\n", ctypeS,
    crvalS+spec1[0], crvalS+spec1[naxisj-1], cdeltS);


  /* Initialize. */
  spc.flag = 0;
  spc.crval = crvalS;
  spc.restfrq = restfrq;
  spc.restwav = restwav;
  strncpy(spc.type, ctypeS, 4);
  spc.type[4] = '\0';
  strcpy(spc.code, ctypeS+5);

  /* Convert the first to the second. */
  if ((status = spcx2s(&spc, naxisj, 1, 1, spec1, spec2, stat1))) {
    printf("spcx2s ERROR %d: %s.\n", status, spc_errmsg[status]);
  }

  /* Convert the second back to the first. */
  if ((status = spcs2x(&spc, naxisj, 1, 1, spec2, clos, stat2))) {
    printf("spcs2x ERROR %d: %s.\n", status, spc_errmsg[status]);
  }

  residmax = 0.0;

  /* Test closure. */
  for (j = 0; j < naxisj; j++) {
    if (stat1[j]) {
      printf("%s: w =%20.12e -> %s = ???, stat = %d\n", ctypeS, spec1[j],
             spc.type, stat1[j]);
      continue;
    }

    if (stat2[j]) {
      printf("%s: w =%20.12e -> %s =%20.12e -> w = ???, stat = %d\n",
             ctypeS, spec1[j], spc.type, spec2[j], stat2[j]);
      continue;
    }

    resid = fabs((clos[j] - spec1[j])/cdeltS);
    if (resid > residmax) residmax = resid;

    if (resid > tol) {
      nFail++;
      printf("%s: w =%20.12e -> %s =%20.12e ->\n          w =%20.12e,  "
             "resid =%20.12e\n", ctypeS, spec1[j], spc.type, spec2[j],
             clos[j], resid);
    }
  }

  printf("%s: Maximum closure residual = %.1e pixel.\n", ctypeS, residmax);


  /* Draw graph. */
  cpgbbuf();
  cpgeras();

  xmin = (float)(crvalS + spec1[0]);
  xmax = (float)(crvalS + spec1[naxisj-1]);
  ymin = (float)(spec2[0]) - xmin;
  ymax = ymin;
  for (j = 0; j < naxisj; j++) {
    x[j] = (float)(j+1);
    y[j] = (float)(spec2[j] - (crvalS + spec1[j]));
    if (y[j] > ymax) ymax = y[j];
    if (y[j] < ymin) ymin = y[j];
  }

  j = (int)crpixj + 1;
  if (y[j] < 0.0) {
    tmp  = ymin;
    ymin = ymax;
    ymax = tmp;
  }

  cpgask(0);
  cpgenv(1.0f, (float)naxisj, ymin, ymax, 0, -1);

  cpgsci(1);
  cpgbox("ABNTS", 0.0f, 0, "BNTS", 0.0f, 0);
  spctyp(ctypeS, 0x0, 0x0, sname, units, 0x0, 0x0, 0x0);
  sprintf(ylab, "%s - correction [%s]", sname, units);
  sprintf(title, "%s:  CRVALk + w [%s]", ctypeS, units);
  cpglab("Pixel coordinate", ylab, title);

  cpgaxis("N", 0.0f, ymax, (float)naxisj, ymax, xmin, xmax, 0.0f, 0, -0.5f,
    0.0f, 0.5f, -0.5f, 0.0f);

  cpgaxis("N", (float)naxisj, ymin, (float)naxisj, ymax, (float)(ymin/cdeltS),
    (float)(ymax/cdeltS), 0.0f, 0, 0.5f, 0.0f, 0.5f, 0.1f, 0.0f);
  cpgmtxt("R", 2.2f, 0.5f, 0.5f, "Pixel offset");

  cpgline(naxisj, x, y);
  cpgsci(7);
  cpgpt1((float)crpixj, 0.0f, 24);
  cpgebuf();

  printf("Type <RETURN> for next page: ");
  (void)getchar();

  printf("\n");

  return nFail;
}
Beispiel #18
0
int main(){
	printf("\n====================================================================\n");
	printf("This program is able to simulate the diffusion of heat\n");
	printf("across a metal plate of size %i x %i\n", ENV_SIZE_X, ENV_SIZE_Y);
	printf("====================================================================\n");

	//==========================================================================
	//--------------------------SYSTEM INITIALIZATIONS--------------------------
	//==========================================================================
	
	// initialize random seed
	srand(time(NULL));

	// force print all outputs (remove stdout buffer)
	setbuf(stdout, NULL);

	// initialize pgplot window
	if (!cpgopen("/XWINDOW"))
		errorCase(ERR_PGPLOT);

	cpgpap(0.0, 0.6);						// set window size
	cpgsubp(1,3);						// subdivide window into panels
	// heatmap
	cpgpanl(1,1);
	cpgsvp(0.0, 1.0, 0.0, 1.0);
	cpgswin(0, ENV_SIZE_X, 0, ENV_SIZE_Y);
	// flux plot
	cpgpanl(1,2);
	cpgsvp(0.08, 0.92, 0.08, 0.92);
	cpgswin(LINE_PLOT_X1, LINE_PLOT_X2, FLUX_PLOT_Y1, FLUX_PLOT_Y2);
	cpgbox("ABCINTS", 0.0, 0, "ABCINTS", 0.0, 0);
	cpglab("Time", "Flux", "");
	// heat plot
	cpgpanl(1,3);
	cpgsvp(0.08, 0.92, 0.08, 0.92);
	cpgswin(LINE_PLOT_X1, LINE_PLOT_X2, LINE_PLOT_Y1, LINE_PLOT_Y2);
	cpgbox("ABCINTS", 0.0, 0, "ABCINTS", 0.0, 0);
	cpglab("Time", "Total Heat", "");

	// initialize color table for pgplot display
  	float rl[9] = {-0.5, 0.0, 0.17, 0.33, 0.50, 0.67, 0.83, 1.0, 1.7};
  	float rr[9] = { 0.0, 0.0,  0.0,  0.0,  0.6,  1.0,  1.0, 1.0, 1.0};
  	float rg[9] = { 0.0, 0.0,  0.0,  1.0,  1.0,  1.0,  0.6, 0.0, 1.0};
  	float rb[9] = { 0.0, 0.3,  0.8,  1.0,  0.3,  0.0,  0.0, 0.0, 1.0};
  	cpgctab(rl, rr, rg, rb, 512,  1.0, 0.5);
	cpgscr(10, 0.0, 0.0, 1.0);
	cpgscr(11, 1.0, 0.0, 0.0);
	cpgsfs(3);


	//==========================================================================
	//--------------------------VARIABLE INITIALIZATIONS------------------------
	//==========================================================================

	// generic variables
	int i, j, k;						// counters

	// simulation environment
	float** simEnvEven = allocateArray2D(ENV_SIZE_X, ENV_SIZE_Y);
	float** simEnvOdd = allocateArray2D(ENV_SIZE_X, ENV_SIZE_Y);
	float* simLocal = allocateArray1D(5);

	// mnist handwritten numbers
	float** mnistDatabase = readCSV("mnist_train_100.csv", 100, 785);
	for (i=0; i<100; i++)
		for (j=0; j<785; j++)
			mnistDatabase[i][j] = mnistDatabase[i][j]/255.0;

	// current location and time
	int x,y,z;
	int t, tGlobal;

	// student number
	int studentNumbRaw;
	int studentNumbWorking;
	int studentNumb[7];

	// rates
	float rateDiff = 0.2;
	float delta;

	// flux variables
	float flux;
	float fluxTotal;
	float fluxAverage;
	float fluxHeat;
	float totalHeat;
	int x1, x2, y1, y2;

	// background heat
	float bgHeat;

	// tracking variables
	float totalHeatOld;
	float totalHeatPre;
	float tGlobalOld;
	float fluxOld;

	// pgplot variables
	float* plotImg = allocateArray1D(ENV_SIZE_TOTAL);
	float TR[6] = {0, 0, 1, ENV_SIZE_Y, -1, 0};
	float plotMinBound = 0;
	float plotMaxBound = 1;

	//==========================================================================
	//--------------------------------SETUP-------------------------------------
	//==========================================================================
	
	// ask for student number
	printf("Please enter your student number:\n");
	if (scanf("%i", &studentNumbRaw) == 0)
		errorCase(ERR_INVALID_INPUT);
	studentNumbWorking = studentNumbRaw;
	for (i=0; i<SN_LENGTH; i++){
		studentNumb[6-i] = studentNumbWorking%10;
		studentNumbWorking /= 10;
	}
	printf("\nYour student number is:\n");
	for (i=0; i<SN_LENGTH; i++)
		printf("%i", studentNumb[i]);
	printf("\n\n");

	// set and print diffusion rate based on last digit of student number
	rateDiff = ((((float)(studentNumb[6]))/10.0)*0.19)+0.01;
	printf("Your Diffusion Rate is: \n%f\n\n", rateDiff);

	// set and print background heat added based on last 4 digits of student number
	studentNumbRaw -= 1410000;
	bgHeat = ((float)((studentNumbRaw%97)%10));
	bgHeat += ((float)((studentNumbRaw%101)%8))*10;
	bgHeat /= 100;
	printf("Your Background Heat is: \n%f\n\n", bgHeat*100);

	// set and print domain for calculating flux
	// x1, y1 based on last four digits of student number
	x1 = studentNumbRaw % ENV_SIZE_X;
	y1 = studentNumbRaw % ENV_SIZE_Y;
	// x2, y2 based on last four digits of student number
	x2 = x1 + (studentNumbRaw % (97));
	if (x2 >= ENV_SIZE_X)
		x2 = ENV_SIZE_X - 1;
	y2 = y1 + (studentNumbRaw % (29));
	if (y2 >= ENV_SIZE_Y)
		y2 = ENV_SIZE_Y - 1;
	printf("Your Domain is: \n(%i, %i) X (%i, %i)\n\n", x1, y1, x2, y2);

	// environment initialization:
	// select digits and place into environment
	for (i=0; i<SN_LENGTH; i++){
		if (studentNumb[i] == 0)
			z = 0;
		else if (studentNumb[i] == 1)
			z = 13;
		else if (studentNumb[i] == 2)
			z = 27;
		else if (studentNumb[i] == 3)
			z = 33;
		else if (studentNumb[i] == 4)
			z = 44;
		else if (studentNumb[i] == 5)
			z = 55;
		else if (studentNumb[i] == 6)
			z = 60;
		else if (studentNumb[i] == 7)
			z = 71;
		else if (studentNumb[i] == 8)
			z = 81;
		else
			z = 89;

		for (x=0; x<28; x++)
			for (y=0; y<28; y++) {
				simEnvEven[x+(i*28)+1][y+1] = mnistDatabase[z][y*28+x] + bgHeat;
				if (simEnvEven[x+(i*28)+1][y+1] > 1.0)
					simEnvEven[x+(i*28)+1][y+1] = 1.0;
			}
	}


	//==========================================================================
	//--------------------------ACTUAL CODE-------------------------------------
	//==========================================================================

	// initialize display
	fixBoundaryConditions(simEnvEven);
	copyArray2D(simEnvEven, simEnvOdd, ENV_SIZE_X, ENV_SIZE_Y);
	loadImage(simEnvEven, plotImg);
	cpgpanl(1,1);
	cpgsvp(0.0, 1.0, 0.0, 1.0);
	cpgswin(0, ENV_SIZE_X, 0, ENV_SIZE_Y);
	cpgimag(plotImg, ENV_SIZE_Y, ENV_SIZE_X, 1, ENV_SIZE_Y, 1, ENV_SIZE_X, plotMinBound, plotMaxBound, TR);
	cpgrect(x1, x2, y1, y2);

	// initialize trackers
	tGlobalOld = 0;
	fluxOld = 0;
	totalHeatOld = 0;
	for (x=x1; x<=x2; x++)
		for (y=y1; y<=y2; y++)
			totalHeatOld += simEnvEven[x][y];

	// initial delay to visualize starting matrix
	for (t=0; t<500000000; t++){}
	
	t = 0;
	tGlobal = 0;
	flux = 0;
	fluxAverage = 0;
	fluxTotal = 0;
	while(1){
		flux = 0;
		cpgpanl(1,1);
		cpgsvp(0.0, 1.0, 0.0, 1.0);
		cpgswin(0, ENV_SIZE_X, 0, ENV_SIZE_Y);

		// calculate heat changes using numeric methods
		fixBoundaryConditions(simEnvEven);

		//simEnvEven[50][15] = 100;
		//simEnvEven[60][15] = -10;

		copyArray2D(simEnvEven, simEnvOdd, ENV_SIZE_X, ENV_SIZE_Y);

		for (x=1; x<(ENV_SIZE_X-1); x++)
			for (y=1; y<(ENV_SIZE_Y-1); y++)
				if ((x+y)%2 == 0) {
					delta = rateDiff*(simEnvEven[x][y+1] - 2*simEnvEven[x][y] + simEnvEven[x][y-1]);
					simEnvOdd[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
					delta = rateDiff*(simEnvEven[x+1][y] - 2*simEnvEven[x][y] + simEnvEven[x-1][y]);
					simEnvOdd[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
				}
		for (x=1; x<(ENV_SIZE_X-1); x++)
			for (y=1; y<(ENV_SIZE_Y-1); y++)
				if ((x+y)%2 == 1) {
					delta = rateDiff*(simEnvOdd[x][y+1] - 2*simEnvOdd[x][y] + simEnvOdd[x][y-1]);
					simEnvOdd[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
					delta = rateDiff*(simEnvOdd[x+1][y] - 2*simEnvOdd[x][y] + simEnvOdd[x-1][y]);
					simEnvOdd[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
				}
		loadImage(simEnvOdd, plotImg);
		cpgimag(plotImg, ENV_SIZE_Y, ENV_SIZE_X, 1, ENV_SIZE_Y, 1, ENV_SIZE_X, plotMinBound, plotMaxBound, TR);
		cpgrect(x1, x2, y1, y2);
		fluxTotal += flux;
		tGlobal++;

		flux = 0;

		//simEnvOdd[50][15] = 100;
		//simEnvOdd[60][15] = -10;

		fixBoundaryConditions(simEnvOdd);
		
		for (x=1; x<(ENV_SIZE_X-1); x++)
			for (y=1; y<(ENV_SIZE_Y-1); y++)
				if ((x+y)%2 == 1) {
					delta = rateDiff*(simEnvOdd[x][y+1] - 2*simEnvOdd[x][y] + simEnvOdd[x][y-1]);
					simEnvEven[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
					delta = rateDiff*(simEnvOdd[x+1][y] - 2*simEnvOdd[x][y] + simEnvOdd[x-1][y]);
					simEnvEven[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
				}
		for (x=1; x<(ENV_SIZE_X-1); x++)
			for (y=1; y<(ENV_SIZE_Y-1); y++)
				if ((x+y)%2 == 0) {
					delta = rateDiff*(simEnvEven[x][y+1] - 2*simEnvEven[x][y] + simEnvEven[x][y-1]);
					simEnvEven[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
					delta = rateDiff*(simEnvEven[x+1][y] - 2*simEnvEven[x][y] + simEnvEven[x-1][y]);
					simEnvEven[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
				}
		loadImage(simEnvEven, plotImg);
		cpgimag(plotImg, ENV_SIZE_Y, ENV_SIZE_X, 1, ENV_SIZE_Y, 1, ENV_SIZE_X, plotMinBound, plotMaxBound, TR);
		cpgrect(x1, x2, y1, y2);
		fluxTotal += flux;
		tGlobal++;



		// flux line plot
		cpgpanl(1,2);
		cpgsvp(0.08, 0.92, 0.08, 0.92);
		cpgswin(LINE_PLOT_X1, LINE_PLOT_X2, FLUX_PLOT_Y1, FLUX_PLOT_Y2);
		cpgmove(tGlobalOld, fluxOld);
		cpgdraw(tGlobal, flux);

		// heat line plot
		totalHeat = 0;
		for (x=x1; x<=x2; x++)
			for (y=y1; y<=y2; y++)
				totalHeat += simEnvEven[x][y];
		cpgpanl(1,3);
		cpgsvp(0.08, 0.92, 0.08, 0.92);
		cpgswin(LINE_PLOT_X1, LINE_PLOT_X2, LINE_PLOT_Y1, LINE_PLOT_Y2);
		cpgmove(tGlobalOld, totalHeatOld);
		cpgdraw(tGlobal, totalHeat);

		// set trackers
		tGlobalOld = tGlobal;
		totalHeatOld = totalHeat;
		fluxOld = flux;

		if (tGlobal%100 == 0) {
			totalHeat = 0;
			for (x=x1; x<=x2; x++)
				for (y=y1; y<=y2; y++)
					totalHeat += simEnvEven[x][y];
			fluxAverage = fluxTotal/tGlobal;
			fluxHeat = totalHeat - totalHeatPre;
			printf("Total Heat: %f \n Current Divergence: %f \n Current Flux:       %f\n\n", totalHeat, flux, fluxHeat);
		}

		totalHeatPre = 0;
		for (x=x1; x<=x2; x++)
			for (y=y1; y<=y2; y++)
				totalHeatPre += simEnvEven[x][y];
	}
}
Beispiel #19
0
int main(int argc, char *argv[]) {
    float *x=NULL,*y=NULL,minx,maxx,miny,maxy,cx, *oparams=NULL,*nparams=NULL;
    float *rx=NULL,*ry=NULL,*w=NULL,*wparams=NULL,*wx=NULL,*wy=NULL,*ww=NULL;
    float *y_sault_fit=NULL, *x_fit=NULL, *y_new_fit=NULL, *y_reynolds_fit=NULL;
    float *y_stevens_fit=NULL,*y_whole_fit=NULL,*y_old_fit=NULL;
    int i,j,n=0,n_fit=100,new_fit_order=2,whole_fit_order=5,nr=0,nw=0;
    /* float extra_x[NEXTRA]={ 93, 95 }, extra_y[NEXTRA] = { 0.1223, 0.1168 }; */
    float extra_x[NEXTRA]= { 93, 95 }, extra_y[NEXTRA] = { 0.1116, 0.1056 };
    float extra_u[NEXTRA]= { 0.01356, 0.01399 };
    float fitp_sault[NFIT_SAULT]= { -202.6259, 149.7321, -36.4943, 2.9372 };
    float fitp_reynolds[NFIT_REYNOLDS]= { -30.7667, 26.4908, -7.0977, 0.605334 };
    float fitp_stevens[NFIT_STEVENS]= { -1.237160, 2.005317, -0.400622 };
    float fitp_old[NFIT_OLD]= { -23.839, 19.569, -4.8168, 0.35836 };
    float *ratio_reynolds_fit=NULL,*ratio_stevens_fit=NULL,*ratio_sault_fit=NULL;
    float *ratio_new_fit=NULL;
    float vpx1, vpx2, vpy1, vpy2, vpy3, lx, ly, dly;
    char fitlabel[BUFSIZE];

    /* Generate the cm fit points. */
    for (cx=1.0; cx<10.0; cx+=0.1) {
        nr++;
        rx = realloc(rx, nr * sizeof(float));
        ry = realloc(ry, nr * sizeof(float));
        rx[nr-1] = log10f(cx * 1000);
        ry[nr-1] = 0.0;
        for (i=0; i<NFIT_REYNOLDS; i++) {
            ry[nr-1] += fitp_reynolds[i] * powf(rx[n-1], (float)i);
        }
    }

    /* Generate the 15mm fit points. */
    for (cx=10.0; cx<=24.0; cx+=0.128) {
        n++;
        x = realloc(x, n * sizeof(float));
        y = realloc(y, n * sizeof(float));
        w = realloc(w, n * sizeof(float));
        x[n-1] = log10f(cx * 1000);
        y[n-1] = 0.0;
        for (i=0; i<NFIT_REYNOLDS; i++) {
            y[n-1] += fitp_sault[i] * powf(x[n-1], (float)i);
        }
        w[n-1] = 1.0/0.1;
    }

    /* Do the fit. */
    linfit_order(NFIT_SAULT, n, x, y, w, &oparams);
    for (i=0; i<NFIT_SAULT; i++) {
        printf("i = %d c[i] = %.4f\n", i, oparams[i]);
    }

    /* Add the 3mm flux points. */
    for (i=0; i<NEXTRA; i++) {
        n++;
        x = realloc(x, n * sizeof(float));
        y = realloc(y, n * sizeof(float));
        w = realloc(w, n * sizeof(float));
        x[n-1] = log10f(extra_x[i] * 1000);
        y[n-1] = log10f(extra_y[i]);
        w[n-1] = 1/extra_u[i];
    }

    /* Do another fit. */
    linfit_order(new_fit_order, n, x, y, w, &nparams);
    for (i=0; i<new_fit_order; i++) {
        printf("i = %d nc[i] = %.4f\n", i, nparams[i]);
    }

    /* Generate the whole range fit points. */
    minx=log10f(900);
    maxx=log10f(100000);
    miny=-2;
    maxy=log10f(20);
    x_fit = malloc(n_fit * sizeof(float));
    for (i=0; i<n_fit; i++) {
        x_fit[i] = minx + i * ((maxx - minx)/(float)n_fit);
        nw++;
        wx = realloc(wx, nw * sizeof(float));
        wy = realloc(wy, nw * sizeof(float));
        ww = realloc(ww, nw * sizeof(float));
        wx[nw-1] = x_fit[i];
        wy[nw-1] = 0.0;
        ww[nw-1] = 1;
        if (x_fit[i] < log10f(11143)) {
            /* Use the Reynolds fit. */
            for (j=0; j<NFIT_REYNOLDS; j++) {
                wy[nw-1] += fitp_reynolds[j] * powf(x_fit[i], (float)j);
            }
        } else {
            /* Use the new fit. */
            for (j=0; j<new_fit_order; j++) {
                wy[nw-1] += nparams[j] * powf(x_fit[i], (float)j);
            }
        }
    }

    /* Do a whole-range fit. */
    linfit_order(whole_fit_order, nw, wx, wy, ww, &wparams);
    for (i=0; i<whole_fit_order; i++) {
        printf("i = %d wc[i] = %.4f\n", i, wparams[i]);
    }

    // minmax(n, x, &minx, &maxx);
    // minmax(n, y, &miny, &maxy);

    y_sault_fit = malloc(n_fit * sizeof(float));
    y_reynolds_fit = malloc(n_fit * sizeof(float));
    y_stevens_fit = malloc(n_fit * sizeof(float));
    y_new_fit = malloc(n_fit * sizeof(float));
    y_whole_fit = malloc(n_fit * sizeof(float));
    y_old_fit = malloc(n_fit * sizeof(float));
    ratio_reynolds_fit = malloc(n_fit * sizeof(float));
    ratio_stevens_fit = malloc(n_fit * sizeof(float));
    ratio_sault_fit = malloc(n_fit * sizeof(float));
    ratio_new_fit = malloc(n_fit * sizeof(float));
    /* minx=log10f(50); */
    minx=log10f(1000);
    /* maxx=log10f(500000); */
    maxx=log10f(110000);
    for (i=0; i<n_fit; i++) {
        x_fit[i] = minx + i * ((maxx - minx)/(float)n_fit);
        y_sault_fit[i] = 0.0;
        y_reynolds_fit[i] = 0.0;
        y_new_fit[i] = 0.0;
        y_stevens_fit[i] = 0.0;
        y_whole_fit[i] = 0.0;
        y_old_fit[i] = 0.0;
        for (j=0; j<NFIT_SAULT; j++) {
            y_sault_fit[i] += fitp_sault[j] * powf(x_fit[i], (float)j);
        }
        for (j=0; j<NFIT_REYNOLDS; j++) {
            y_reynolds_fit[i] += fitp_reynolds[j] * powf(x_fit[i], (float)j);
        }
        for (j=0; j<NFIT_STEVENS; j++) {
            y_stevens_fit[i] += fitp_stevens[j] * powf(x_fit[i], (float)j);
        }
        for (j=0; j<new_fit_order; j++) {
            y_new_fit[i] += nparams[j] * powf(x_fit[i], (float)j);
        }
        for (j=0; j<whole_fit_order; j++) {
            y_whole_fit[i] += wparams[j] * powf(x_fit[i], (float)j);
        }
        for (j=0; j<NFIT_OLD; j++) {
            y_old_fit[i] += fitp_old[j] * powf(x_fit[i], (float)j);
        }
        ratio_reynolds_fit[i] = powf(10, (y_reynolds_fit[i] - y_whole_fit[i]));
        ratio_stevens_fit[i] = powf(10, (y_stevens_fit[i] - y_whole_fit[i]));
        ratio_sault_fit[i] = powf(10, (y_sault_fit[i] - y_whole_fit[i]));
        ratio_new_fit[i] = powf(10, (y_new_fit[i] - y_whole_fit[i]));
    }

    /* cpgopen("11/xs"); */
    cpgopen("1934-638_models.ps/cps");
    /* cpgopen("1934-638_models.png/png"); */
    cpgqvp(0, &vpx1, &vpx2, &vpy1, &vpy2);
    vpy3 = vpy1 + (vpy2 - vpy1) / 5.0;
    /* cpgsvp(vpx1, vpx2, vpy3, vpy2); */
    cpgswin(minx, maxx, miny, maxy);
    lx = minx + (maxx - minx) / 9.0;
    ly = miny + (maxy - miny) / 3.0;
    dly = (maxy - miny) / 20.0;
    cpgsch(1.0);
    cpgbox("BCLNTS",0,0,"BCLNTS",0,0);
    cpglab("Frequency (MHz)", "Flux Density (Jy)", "1934-638 Model Comparison");
    cpgsch(0.8);
    cpgpt(n, x, y, 4);
    /* cpgpt(nw, wx, wy, 4); */
    cpgsci(2);
    /* cpgpt(nr, rx, ry, 4); */
    cpgline(n_fit, x_fit, y_sault_fit);
    strcpy(fitlabel, "Sault: ");
    fitstring(fitp_sault, NFIT_SAULT, fitlabel);
    cpgtext(lx, ly, fitlabel);
    cpgsci(3);
    cpgline(n_fit, x_fit, y_new_fit);
    strcpy(fitlabel, "Stevens (linear): ");
    fitstring(nparams, new_fit_order, fitlabel);
    ly -= dly;
    cpgtext(lx, ly, fitlabel);
    cpgsci(4);
    cpgline(n_fit, x_fit, y_reynolds_fit);
    strcpy(fitlabel, "Reynolds: ");
    fitstring(fitp_reynolds, NFIT_REYNOLDS, fitlabel);
    ly -= dly;
    cpgtext(lx, ly, fitlabel);
    cpgsci(5);
    cpgline(n_fit, x_fit, y_stevens_fit);
    strcpy(fitlabel, "Stevens (Miriad): ");
    fitstring(fitp_stevens, NFIT_STEVENS, fitlabel);
    ly -= dly;
    cpgtext(lx, ly, fitlabel);
    cpgsci(6);
    cpgline(n_fit, x_fit, y_old_fit);
    strcpy(fitlabel, "Pre-1994: ");
    fitstring(fitp_old, NFIT_OLD, fitlabel);
    ly -= dly;
    cpgtext(lx, ly, fitlabel);
    /* cpgsci(6); */
    /* cpgline(n_fit, x_fit, y_whole_fit); */
    /* strcpy(fitlabel, "Stevens (New): "); */
    /* fitstring(wparams, whole_fit_order, fitlabel); */
    /* ly -= dly; */
    /* cpgtext(lx, ly, fitlabel); */
    /* cpgsvp(vpx1, vpx2, vpy1, vpy3); */
    /* cpgsci(1); */
    /* cpgswin(minx, maxx, 0.9, 1.1); */
    /* cpgsch(1.0); */
    /* cpgbox("BCLNTS",0,0,"BCMTS",0,0); */
    /* cpglab("Frequency (MHz)", "Model Ratio", ""); */
    /* cpgsci(2); */
    /* cpgline(n_fit, x_fit, ratio_sault_fit); */
    /* cpgsci(3); */
    /* cpgline(n_fit, x_fit, ratio_new_fit); */
    /* cpgsci(4); */
    /* cpgline(n_fit, x_fit, ratio_reynolds_fit); */
    /* cpgsci(5); */
    /* cpgline(n_fit, x_fit, ratio_stevens_fit); */
    cpgclos();

    exit(0);
}
Beispiel #20
0
int makePlot (char *fname, char *dname, int number)
{
	FILE *fpt;
	double *on_energy;
	double *off_energy;
	double ave_on, ave_off;
	double on, off;
	int i, j;

	on_energy = (double *)malloc(sizeof(double)*number);
	off_energy = (double *)malloc(sizeof(double)*number);

	if ((fpt = fopen(fname, "r")) == NULL)
	{
		fprintf (stdout, "Can't open file\n");
		exit(1);
	}

	i = 0;
	while (fscanf(fpt, "%lf %lf", &on, &off) == 2)
	{
		on_energy[i] = on;
		off_energy[i] = off;
		i++;
	}

	if (fclose (fpt) != 0)
		fprintf (stderr, "Error closing\n");

	ave_on = 0.0;
	ave_off = 0.0;

	for (i = 0; i < number; i++)
	{
		ave_on += on_energy[i];
		ave_off += off_energy[i];
	}
	ave_on = ave_on/number;
	ave_off = ave_off/number;

	for (i = 0; i < number; i++)
	{
		on_energy[i] = on_energy[i]/ave_on;
		off_energy[i] = off_energy[i]/ave_on;
	}
	/////////////////////////////////////////////////

	float *xHis_on; // x axis of the histogram
	float *val_on;  // data value of the histogram
	float *xHis_off; // x axis of the histogram
	float *val_off;  // data value of the histogram
	int step = 100; // steps in the histogram

	//char caption[1024];
	//char text[1024];

	float max, max1, max2;

	// make histogram
	xHis_on = (float*)malloc(sizeof(float)*step);
	val_on = (float*)malloc(sizeof(float)*step);
	xHis_off = (float*)malloc(sizeof(float)*step);
	val_off = (float*)malloc(sizeof(float)*step);

	histogram (on_energy, number, xHis_on, val_on, -1.0, 4.0, step);
	histogram (off_energy, number, xHis_off, val_off, -1.0, 4.0, step);

	// plot 
	//cpgbeg(0,"/xs",1,1);
	cpgbeg(0,dname,1,1);

	cpgsch(1); // set character height
	cpgscf(1); // set character font

	// find the max
	max1 = find_max_value(step,val_off);
	max2 = find_max_value(step,val_on);
	max = (max1 >= max2 ? max1 : max2);
	//cpgenv(-5,5,0,4500,0,1); // set window and viewport and draw labeled frame
	cpgenv(-1,4,0,max+0.1*max,0,1); // set window and viewport and draw labeled frame

	//sprintf(caption, "%s", "Flux density histogram");
	cpglab("Flux (mJy)","Number","");
	cpgbin(step,xHis_on,val_on,0);
	cpgsci(2);
	cpgbin(step,xHis_off,val_off,0);
	///////////////////////////////////////////////////////
	cpgend();
	////////////////////

	free(on_energy);
	free(off_energy);
	free(xHis_on);
	free(val_on);
	free(xHis_off);
	free(val_off);

	return 0;
}
Beispiel #21
0
void getTOA_alg1(ptime_observation *obs,pheader *header,tmplStruct *tmpl,toaStruct *toa,FILE *fout_log)
{
  int i,j,k;
  int nbin = header->nbin;
  int nchan = header->nchan;
  int npol = header->npol;
  double chisq;
  double diffVals[nbin];
  double phiRot = 0;
  double step1 = 1.0/nbin/2.0;
  double step = step1;
  double baseline = 0;
  double scale = 1;
  double tmplEval;
  int chan = 0;
  int pol = 0;
  double phi,bestPhi;
  double phi0,phi1,bestChisq;
  int it;
  double chisqVals[nbin*2];
  double phiVals[nbin*2];
  int nChisqVals,ibest;
  int iterateAgain;
  int maxIterations = 10;
  int plotOutput=0;
  double error;
  double *fitX;
  double *fitY;
  double *fitE;
  int    *fitI,*fitJ,*fitK;
  int nfit = npol+1; // Up to 4 baselines per profile + 1 scaling factor
  double outputParams_v[nfit];
  double outputParams_e[nfit];
  double results_v[npol*nchan+nchan];
  double results_e[npol*nchan+nchan];
  int weight = 1;
  double bestParameters[npol*nchan+nchan];
  double chisqTot;

  // Covariance matrix
  double **cvm;
  cvm = (double **)malloc(sizeof(double*)*nfit);
  for (i=0;i<nfit;i++)
    cvm[i] = (double *)malloc(sizeof(double)*nfit);
  if (!(fitX = (double *)malloc(sizeof(double)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitX\n");
    exit(1);
  }
  if (!(fitY = (double *)malloc(sizeof(double)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitY\n");
    exit(1);
  }
  if (!(fitE = (double *)malloc(sizeof(double)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitE\n");
    exit(1);
  }
  if (!(fitI = (int *)malloc(sizeof(int)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitI\n");
    exit(1);
  }
  if (!(fitJ = (int *)malloc(sizeof(int)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitJ\n");
    exit(1);
  }
  if (!(fitK = (int *)malloc(sizeof(int)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitK\n");
    exit(1);
  }

  printf("Baseline sdev = %g, mean = %g\n",obs->chan[0].pol[0].sdev,obs->chan[0].pol[0].baselineVal);
  printf("On the next line\n");
  printf("npol = %d \n",npol);
  printf("Doing fit\n");
  it = 0;
  do {
    printf("Iteration %d\n",it+1);
    if (it == 0) {
      phi0 = -0.5;
      phi1 = 0.5;
    } else {
      phi0 = bestPhi - step;
      phi1 = bestPhi + step;
      step/=(double)10.0;
    }
    nChisqVals = 0;
    for (phiRot = phi0;phiRot < phi1;phiRot += step)
      {
	printf("Complete: %.1f percent\n",(phiRot-phi0)/(phi1-phi0)*100);
	//	phiRot = 0.0;
	// Least squares fit for baseline and amplitude at given phiRot
	//	printf("Doing fit\n");
	chisqTot=0;
	for (j=0;j<nchan;j++){
	  for (i=0;i<npol;i++){
	    for (k=0;k<nbin;k++){
	      //	printf("Setting %d %d %d %d %d\n",i,j,k,npol*nchan*nbin,i*(nchan*nbin)+j*nbin+k);
	      fitI[i*nbin+k] = i;
	      fitJ[i*nbin+k] = j;
	      fitK[i*nbin+k] = k;
	      fitX[i*nbin+k] = (double)k/(double)nbin; 
	      //	printf("This far\n");
	      //	printf("Searching for %g\n",obs->chan[j].pol[i].val[k]);
	      fitY[i*nbin+k] = obs->chan[j].pol[i].val[k];
	      fitE[i*nbin+k] = obs->chan[j].pol[i].sdev; 
	    }
	  }

	  TKleastSquares_svd(fitX,fitY,fitE,fitI,fitJ,fitK,npol*nbin,outputParams_v,outputParams_e,nfit,cvm, &chisq, fitFunc, tmpl, weight,phiRot);
	  chisqTot += chisq;
	  for (i=0;i<npol+1;i++)
	    {
	      results_v[(npol+1)*j + i] = outputParams_v[i];
	      results_e[(npol+1)*j + i] = outputParams_e[i];
	    }
	  //	  for (i=0;i<npol*nbin;i++)
	  //	    {
	  //	      printf("FitVals = %g %g %g\n",fitX[i],fitY[i],fitE[i]);
	  //	    }
	  //	  for (i=0;i<nbin;i++)
	  //	    printf("Best %g %g\n",fitX[i],outputParams_v[4]*evaluateTemplateChannel(tmpl,fitX[i],j,0,phiRot)+outputParams_v[0]);
	  //	  for (i=0;i<nbin;i++)
	  //	    printf("Best %g %g\n",fitX[i],outputParams_v[4]*evaluateTemplateChannel(tmpl,fitX[i],j,1,phiRot)+outputParams_v[1]);
	  //	  for (i=0;i<nbin;i++)
	  //	    printf("Best %g %g\n",fitX[i],outputParams_v[4]*evaluateTemplateChannel(tmpl,fitX[i],j,2,phiRot)+outputParams_v[2]);
	  //	  for (i=0;i<nbin;i++)
	  //	    printf("Best %g %g\n",fitX[i],outputParams_v[4]*evaluateTemplateChannel(tmpl,fitX[i],j,3,phiRot)+outputParams_v[3]);

	  //	for (i=0;i<nfit;i++){
	  //	  printf("%d %g %g\n",i,outputParams_v[i],outputParams_e[i]);


	}

	//	printf("Done fit\n");
	//	baseline = outputParams_v[0];
	//	scale = outputParams_v[1];
	//	for (i=0;i<nfit;i++){
	//	  printf("%d %g %g\n",i,outputParams_v[i],outputParams_e[i]);
	//	}
	//	exit(1);	
	chisqVals[nChisqVals] = chisqTot;
	phiVals[nChisqVals] = phiRot;
	if (nChisqVals==0){
	  bestPhi = phiRot;
	  bestChisq = chisqTot;
	  for (i=0;i<nchan*npol+nchan;i++){
	    bestParameters[i] = outputParams_v[i];
	  }
	  ibest = nChisqVals;
	} else {
	  if (bestChisq > chisqTot){
	    bestChisq = chisqTot;
	    bestPhi = phiRot;
	    ibest = nChisqVals;
	    for (i=0;i<nchan*npol+nchan;i++){
	      bestParameters[i] = outputParams_v[i];
	    }
	  }
	}
	//	printf("Chisq = %g\n",chisq);
	//	exit(1);
	nChisqVals++;
      }
    printf("nvals =%d\n",nChisqVals);
    // Should check if we need to iterate again - do check based on how chisq is changing - i.e, must get a good measure of the chisq increasing by 1
    iterateAgain = 1;
    for (i=ibest+1;i<nChisqVals;i++)
      {
	if (chisqVals[i] < bestChisq + 1){
	  iterateAgain = 0;
	  break;
	}
      }
    it++;
  } while (iterateAgain == 1 && it < maxIterations);
  printf("ibest = %d, nChisqVals = %d, bestPhi = %g\n",ibest,nChisqVals,bestPhi);
  //  exit(1);
  {
    int foundStart = 0;
    double start,end;

    // Should think how to improve this method
    for (i=0;i<nChisqVals;i++)
      {
	fprintf(fout_log,"chisqVals %g %g\n",phiVals[i],chisqVals[i]);
	if (foundStart==0 && chisqVals[i] <= bestChisq + 1) 
	  {
	    foundStart = 1;
	    start = phiVals[i]; 
	  }
	else if (foundStart == 1 && chisqVals[i] >= bestChisq + 1)
	  {
	    end = phiVals[i];
	    break;
	  }
      }
    error = (end-start)/2.0;
  }
    
  printf("Number of iterations = %d\n",it);
  printf("bestPhi = %g\n",bestPhi);
  printf("bestChisq = %g\n",bestChisq);
  for (i=0;i<nchan*npol+nchan;i++){
    printf("Best parameter: %d %g\n",i,bestParameters[i]);
  }

  fprintf(fout_log,"Number of iterations = %d\n",it);
  fprintf(fout_log,"bestPhi = %g\n",bestPhi);
  fprintf(fout_log,"bestChisq = %g\n",bestChisq);
  for (i=0;i<nchan*npol+nchan;i++){
    fprintf(fout_log,"Best parameter: %d %g\n",i,bestParameters[i]);
  }

  if (plotOutput == 1){
    float fx[nbin*2],fy[nbin*2],ft[nbin*2],dy[nbin*2];
    float miny,maxy;
    float miny2,maxy2;

    for (i=0;i<nbin;i++)
      {
	fx[i] = (float)i/(float)nbin;
	fx[i+nbin] = fx[i]+1;
	//	tmplEval = bestScale*evaluateTemplateChannel(tmpl,fx[i],chan,pol,bestPhi)+bestBaseline;
	
	fy[i] = obs->chan[chan].pol[pol].val[i];
	fy[i+nbin] = fy[i];
	ft[i] = tmplEval;
	ft[i+nbin] = ft[i];
	dy[i] = fy[i]-ft[i];
	dy[i+nbin] = dy[i];
      }
    findMinMax(nbin,fy,&miny,&maxy);
    findMinMax(nbin,dy,&miny2,&maxy2);

    cpgbeg(0,"/xs",1,1);
    cpgsvp(0.1,0.9,0.5,0.9);
    cpgeras();
    cpgswin(0,2,miny,maxy);
    cpgbox("BCTS",0.0,0,"BCTSN",0.0,0);


    cpgbin(nbin*2,fx,fy,1);
    cpgsci(2); cpgline(nbin*2,fx,ft); cpgsci(1);

    cpgsvp(0.1,0.9,0.15,0.5);
    cpgswin(0,2,miny2,maxy2);
    cpgbox("BCTSN",0.0,0,"BCTSN",0.0,0);
    cpglab("Phase","prof-tmpl","");
    cpgbin(nbin*2,fx,dy,1);



    cpgend();
  }
  toa->dphi = bestPhi;
  toa->dphiErr = error;

  for (i=0;i<nfit;i++)
    free(cvm[i]);
  free(cvm);
  free(fitX); free(fitY); free(fitE); free(fitI); free(fitJ); free(fitK);
  return;
}