main(
	int		argc,			// Number of Arguments
	char	**argv )		// Pointer to Arguments
{
	int		shrd_param_id;				// Shared Memory ID
	struct	SHM_PARAM	*param_ptr;		// Pointer to the Shared Param
	struct	sembuf		sops;			// Semaphore for data area
	int		IFindex;
	int		index;
	float	bitPower[MAX_NIF][POWER_TIME_NUM];	// Power Monitor Data
	float	tempPower[POWER_TIME_NUM];			// Buffer
	char	pg_text[256];				// Text to plot
	char	xlabel[64];					// X-axis label
//------------------------------------------ Access to the SHARED MEMORY
    //------- SHARED PARAMETERS --------
    if(shm_access(
        SHM_PARAM_KEY,					// ACCESS KEY
        sizeof(struct SHM_PARAM),		// SIZE OF SHM
        &shrd_param_id,					// SHM ID
        &param_ptr) != -1){				// Pointer to the SHM
		printf("PowerView: Succeeded to access the shared parameter [%d]!\n",  param_ptr->shrd_param_id);
	}
	memset(bitPower, 0, param_ptr->num_st* POWER_TIME_NUM* sizeof(float));
//------------------------------------------ K5 Header and Data
	setvbuf(stdout, (char *)NULL, _IONBF, 0);	// Disable stdout cache
	cpgbeg(1, argv[1], 1, 1);

	while(param_ptr->validity & ACTIVE){
		cpgbbuf();
		sprintf(xlabel, "Elapsed Time [sec]\0"); cpg_setup(xlabel);
		if( param_ptr->validity & (FINISH + ABSFIN) ){  break; }

		//-------- Wait for Semaphore
		sops.sem_num = (ushort)SEM_POWER;	sops.sem_op = (short)-1;	sops.sem_flg = (short)0;
		semop( param_ptr->sem_data_id, &sops, 1);

		//-------- Plot Power Monitor
		for(IFindex=0; IFindex<param_ptr->num_st; IFindex++){
			memcpy(tempPower, bitPower[IFindex], POWER_TIME_NUM*sizeof(float));
			bitPower[IFindex][0] = 10.0* log10(param_ptr->power[IFindex]);
			memcpy(&bitPower[IFindex][1], tempPower, (POWER_TIME_NUM-1)*sizeof(float));
		}
		cpg_power(param_ptr, bitPower);
	}
	cpgend();
//------------------------------------------ RELEASE the SHM
    return(0);
}
Example #2
0
int main()
{
  /*
   * Call ppgbeg to initiate PGPLOT and open the output device; cpgbeg
   * will prompt the user to supply the device name and type.
   */
  if(cpgbeg(0, "?", 1, 1) != 1)
    exit(EXIT_FAILURE);
  cpgask(1);
  /*
   * Call each demo.
   */
  demo1();
  demo2();
  demo3();
  /*
   * Finally, call cpgend to terminate things properly.
   */
  cpgend();
  return EXIT_SUCCESS;
}
Example #3
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);
}
Example #4
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();
}
Example #5
0
int main()

{
  char   text[80];
  register int status;


  printf("Testing WCSLIB wcsmix() routine (twcsmix.c)\n"
         "-------------------------------------------\n");

  /* List status return messages. */
  printf("\nList of wcs status return values:\n");
  for (status = 1; status <= 13; status++) {
    printf("%4d: %s.\n", status, wcs_errmsg[status]);
  }


  /* PGPLOT initialization. */
  strcpy(text, "/xwindow");
  cpgbeg(0, text, 1, 1);

  /* Define pen colours. */
  cpgscr(0, 0.00f, 0.00f, 0.00f);
  cpgscr(1, 1.00f, 1.00f, 0.00f);
  cpgscr(2, 1.00f, 1.00f, 1.00f);
  cpgscr(3, 0.50f, 0.50f, 0.80f);
  cpgscr(4, 0.80f, 0.50f, 0.50f);
  cpgscr(5, 0.80f, 0.80f, 0.80f);
  cpgscr(6, 0.50f, 0.50f, 0.80f);
  cpgscr(7, 0.80f, 0.50f, 0.50f);
  cpgscr(8, 0.30f, 0.50f, 0.30f);
  cpgscr(9, 1.00f, 0.75f, 0.00f);


  /*----------------------------------------------------------*/
  /* Set the PVi_m keyvalues for the longitude axis so that   */
  /* the fiducial native coordinates are at the native pole,  */
  /* i.e. (phi0,theta0) = (0,90), but without any fiducial    */
  /* offset.  We do this as a test, and also so that all      */
  /* projections will be exercised with the same obliquity    */
  /* parameters.                                              */
  /*----------------------------------------------------------*/
  PV[0].i = 4;			/* Longitude is on axis 4.     */
  PV[0].m = 1;			/* Parameter number 1.         */
  PV[0].value =  0.0;		/* Fiducial native longitude.  */

  PV[1].i = 4;			/* Longitude is on axis 4.     */
  PV[1].m = 2;			/* Parameter number 2.         */
  PV[1].value = 90.0;		/* Fiducial native latitude.   */

  /* Set the PVi_m keyvalues for the latitude axis.           */
  PV[2].i = 2;			/* Latitude is on axis 2.      */
  PV[2].m = 1;			/* Parameter number 1.         */
  PV[2].value = 0.0;		/* PVi_1 (set below).          */

  PV[3].i = 2;			/* Latitude is on axis 2.      */
  PV[3].m = 2;			/* Parameter number 2.         */
  PV[3].value = 0.0;		/* PVi_2 (set below).          */

  /* ARC: zenithal/azimuthal equidistant. */
  strncpy(&CTYPE[1][5], "ARC", 3);
  strncpy(&CTYPE[3][5], "ARC", 3);
  NPV = 2;
  mixex(-190.0, 190.0, -190.0, 190.0);

  /* ZEA: zenithal/azimuthal equal area. */
  strncpy(&CTYPE[1][5], "ZEA", 3);
  strncpy(&CTYPE[3][5], "ZEA", 3);
  NPV = 2;
  mixex(-120.0, 120.0, -120.0, 120.0);

  /* CYP: cylindrical perspective. */
  strncpy(&CTYPE[1][5], "CYP", 3);
  strncpy(&CTYPE[3][5], "CYP", 3);
  NPV = 4;
  PV[2].value = 3.0;
  PV[3].value = 0.8;
  mixex(-170.0, 170.0, -170.0, 170.0);

  /* CEA: cylindrical equal area. */
  strncpy(&CTYPE[1][5], "CEA", 3);
  strncpy(&CTYPE[3][5], "CEA", 3);
  NPV = 3;
  PV[2].value = 0.75;
  mixex(-200.0, 200.0, -200.0, 200.0);

  /* CAR: plate carree. */
  strncpy(&CTYPE[1][5], "CAR", 3);
  strncpy(&CTYPE[3][5], "CAR", 3);
  NPV = 2;
  mixex(-210.0, 210.0, -210.0, 210.0);

  /* SFL: Sanson-Flamsteed. */
  strncpy(&CTYPE[1][5], "SFL", 3);
  strncpy(&CTYPE[3][5], "SFL", 3);
  NPV = 2;
  mixex(-190.0, 190.0, -190.0, 190.0);

  /* PAR: parabolic. */
  strncpy(&CTYPE[1][5], "PAR", 3);
  strncpy(&CTYPE[3][5], "PAR", 3);
  NPV = 2;
  mixex(-190.0, 190.0, -190.0, 190.0);

  /* MOL: Mollweide's projection. */
  strncpy(&CTYPE[1][5], "MOL", 3);
  strncpy(&CTYPE[3][5], "MOL", 3);
  NPV = 2;
  mixex(-170.0, 170.0, -170.0, 170.0);

  /* AIT: Hammer-Aitoff. */
  strncpy(&CTYPE[1][5], "AIT", 3);
  strncpy(&CTYPE[3][5], "AIT", 3);
  NPV = 2;
  mixex(-170.0, 170.0, -170.0, 170.0);

  /* COE: conic equal area. */
  strncpy(&CTYPE[1][5], "COE", 3);
  strncpy(&CTYPE[3][5], "COE", 3);
  NPV = 4;
  PV[2].value = 60.0;
  PV[3].value = 15.0;
  mixex(-140.0, 140.0, -120.0, 160.0);

  /* COD: conic equidistant. */
  strncpy(&CTYPE[1][5], "COD", 3);
  strncpy(&CTYPE[3][5], "COD", 3);
  NPV = 4;
  PV[2].value = 60.0;
  PV[3].value = 15.0;
  mixex(-200.0, 200.0, -180.0, 220.0);

  /* BON: Bonne's projection. */
  strncpy(&CTYPE[1][5], "BON", 3);
  strncpy(&CTYPE[3][5], "BON", 3);
  NPV = 3;
  PV[2].value = 30.0;
  mixex(-160.0, 160.0, -160.0, 160.0);

  /* PCO: polyconic. */
  strncpy(&CTYPE[1][5], "PCO", 3);
  strncpy(&CTYPE[3][5], "PCO", 3);
  NPV = 2;
  mixex(-190.0, 190.0, -190.0, 190.0);

  /* TSC: tangential spherical cube. */
  strncpy(&CTYPE[1][5], "TSC", 3);
  strncpy(&CTYPE[3][5], "TSC", 3);
  NPV = 2;
  mixex(-340.0, 80.0, -210.0, 210.0);

  /* QSC: quadrilateralized spherical cube. */
  strncpy(&CTYPE[1][5], "QSC", 3);
  strncpy(&CTYPE[3][5], "QSC", 3);
  NPV = 2;
  mixex(-340.0, 80.0, -210.0, 210.0);

  cpgend();

  return 0;
}
Example #6
0
void main()
{
   
   float RES = (XMAX - XMIN)/N;                          //resolution
   
   int i,j,p;
   
    
   
   //************************* PGPLOT CODE ***************************
  
  cpgbeg(0,"?",1,1);
  cpgpage();
  
  cpgsci(1);                                           // axis color
  
  cpgpap(0,1);
  
                                                      //axis limits
  cpgswin(XMIN,XMAX,YMIN,YMAX);
  
  cpgbox("BCN",1, 0, "BCN", 1, 0);                  // draw the axes
  
  cpgsci(1);                                          //data color

  cpgsch(0.00000000000001);                        //data point size
  
  
  
  //******************* GRID ALGORITHM AND PLOTTING ********************
  
  
  struct cnum z;                          // z = (0,0) = initial number 
  struct cnum c;                          // c is a complex variable
  z.cx = 0;
  z.cy = 0;
   
   
  for(i=0;i<N;i++)                     //look at every point on grid
  {
    for(j=0;j<N;j++)                       
    {
      
       c.cx = XMIN + i*RES;            //assign c = current point
       c.cy = YMIN + j*RES;            
       
       CPRINT(c);
       
       for(p=0;p<MNI;p++)                  //apply MNI iterations to z
       {                                   //using c = current point
	 z = FMANDEL(z,c);
	 
	 if ( z.cx*z.cx + z.cy*z.cy > R)    // if iteration "blows up"... 
	 {
	   z.cx = 0;
	   z.cy = 0;                       //stay at z=c=0
	   c.cx = 0;
	   c.cy = 0;	   
	 }
	   
       }                                  //end of interation. z = final number
           
           
       if (z.cx*z.cx + z.cy*z.cy < R)      //if iteration hasn't blown up...
       {
	 float X[1], Y[1];
	 X[0] = c.cx;
	 Y[0] = c.cy;
	 cpgpt(1,X,Y,17);                  // plot point c
       }
       
       
       
    }
    
   }
   
  printf("\n\n");                             
 
  cpgend();                       
  
  
 
}
// Process dedispersion output
void* process_output(void* output_params)
{
    OUTPUT_PARAMS* params = (OUTPUT_PARAMS *) output_params;
    OBSERVATION *obs = params -> obs;
    int i, iters = 0, ret, loop_counter = 0, pnsamp = params -> obs -> nsamp;
    int ppnsamp = params -> obs-> nsamp;
    time_t start = params -> start, beg_read;
    double pptimestamp = 0, ptimestamp = 0;
    double ppblockRate = 0, pblockRate = 0;

    // Initialise pg plotter
    #if PLOT
        if(cpgbeg(0, "/xwin", 1, 1) != 1)
            printf("Couldn't initialise PGPLOT\n");
        cpgask(false);
    #endif

    printf("%d: Started output thread\n", (int) (time(NULL) - start));

    FILE *fp = fopen("chanOutput.dat", "wb");

    // Processing loop
    while (1) {

        // Wait input barrier
        ret = pthread_barrier_wait(params -> input_barrier);
        if (!(ret == 0 || ret == PTHREAD_BARRIER_SERIAL_THREAD)) 
            { fprintf(stderr, "Error during input barrier synchronisation [output]\n"); exit(0); }

        // Process output
        if (loop_counter >= params -> iterations) 
        {
            unsigned nsamp = ppnsamp, nchans = obs -> nchans;
            double timestamp = pptimestamp, blockRate = ppblockRate;
            beg_read = time(NULL);

            #if PLOT
            if (!obs -> folding)
            {
                // Process and plot output
                unsigned startChan = 0, endChan = startChan + 32, decFactor = 512;
//                unsigned startChan = 0, endChan = startChan + 32, decFactor = 4;
                float xr[nsamp / decFactor], yr[endChan - startChan][nsamp / decFactor];
                float ymin = 9e12, ymax=9e-12;

                for (unsigned c = 0; c < endChan - startChan; c++)
                {
                    // Decimate before plotting
                    for (unsigned i = 0; i < nsamp / decFactor; i++)
                    {        
                        unsigned index = (startChan + c) * nsamp + i * decFactor;
                        xr[i] = i;
                        yr[c][i] = 0;

                        for (unsigned j = 0; j < decFactor; j++)
                            yr[c][i] += params -> host_odata[index+j].x * 
                                        params -> host_odata[index+j].x + 
                                        params -> host_odata[index+j].y * 
                                        params -> host_odata[index+j].y;

//                            yr[c][i] = (yr[c][i] / decFactor) + c * 1e5;
                        yr[c][i] = (yr[c][i] / decFactor) + c * 4;
                        if (ymax < yr[c][i]) ymax = yr[c][i];
                        if (ymin > yr[c][i]) ymin = yr[c][i];
                    }
                }

                unsigned plotChan = 1;
                float *chan = (float *) malloc(nsamp * sizeof(float));
                for (unsigned i = 0; i < nsamp; i++)
                  chan[i] = params -> host_odata[plotChan * nsamp + i].x * 
                            params -> host_odata[plotChan * nsamp + i].x + 
                            params -> host_odata[plotChan * nsamp + i].y * 
                            params -> host_odata[plotChan * nsamp + i].y;

                fwrite(chan, sizeof(float), nsamp, fp);
                fflush(fp);
                free(chan);

                cpgenv(0.0, pnsamp / decFactor, ymin, ymax, 0, 1);
                cpgsci(7);
                for (unsigned i = 0; i < endChan - startChan; i++)
                    cpgline(nsamp / decFactor, xr, yr[i]);

                cpgmtxt("T", 2.0, 0.0, 0.0, "Dedispersed Channel Plot");
            }
            else
            {
                unsigned plotChannel = 15;
                unsigned decFactor = 256; 
                float *xr = (float *) malloc(obs -> profile_bins / decFactor * sizeof(float));
                float *yr = (float *) malloc(obs -> profile_bins / decFactor * sizeof(float));
                float ymin = 9e12, ymax = 9e-12;           
    
                unsigned fullProfiles = obs -> nsamp * (loop_counter - 1) / 
                                        obs -> profile_bins;
                unsigned leftover = (obs -> nsamp * (loop_counter - 1)) % obs -> profile_bins;

                if (fullProfiles > 0)
                {
                    // Decimate before plotting
                    for (unsigned i = 0; i < obs -> profile_bins / decFactor; i++)
                    {        
                        unsigned index = plotChannel * obs -> profile_bins + i * decFactor;
                        xr[i] = i;
                        yr[i] = 0;

                        for (unsigned j = 0; j < decFactor; j++)
                            yr[i] += params -> host_profile[index + j];

                        yr[i] = (yr[i] / decFactor);
                        yr[i] = (i < leftover / decFactor) 
                              ? yr[i] / (fullProfiles + 1) 
                              : yr[i] / fullProfiles;

                        if (ymax < yr[i]) ymax = yr[i];
                        if (ymin > yr[i]) ymin = yr[i];
                    }

                    cpgenv(0.0, obs -> profile_bins / decFactor, ymin, ymax, 0, 1);
                    cpgsci(7);
                    cpgline(obs -> profile_bins / decFactor, xr, yr);
                    cpgmtxt("T", 2.0, 0.0, 0.0, "Pulsar Profile");
                    
                    free(xr);
                    free(yr);
                }
            }
            #endif

            printf("%d: Processed output %d [output]: %d\n", (int) (time(NULL) - start), loop_counter,
                   (int) (time(NULL) - beg_read));
        }

    sleep(2);

        // Wait output barrier
        ret = pthread_barrier_wait(params -> output_barrier);
        if (!(ret == 0 || ret == PTHREAD_BARRIER_SERIAL_THREAD))
            { fprintf(stderr, "Error during output barrier synchronisation [output]\n"); exit(0); }

        // Acquire rw lock
        if (pthread_rwlock_rdlock(params -> rw_lock))
            { fprintf(stderr, "Unable to acquire rw_lock [output]\n"); exit(0); } 

        // Update params
        ppnsamp = pnsamp;
        pnsamp = params -> obs -> nsamp;     
        pptimestamp = ptimestamp;
        ptimestamp = params -> obs -> timestamp;
        ppblockRate = pblockRate;
        pblockRate = params -> obs -> blockRate;    

        // Stopping clause
        if (((OUTPUT_PARAMS *) output_params) -> stop) {
            
            if (iters >= params -> iterations - 1) {
               
                // Release rw_lock
                if (pthread_rwlock_unlock(params -> rw_lock))
                    { fprintf(stderr, "Error releasing rw_lock [output]\n"); exit(0); }

                for(i = 0; i < params -> maxiters - params -> iterations; i++) {
                    pthread_barrier_wait(params -> input_barrier);
                    pthread_barrier_wait(params -> output_barrier);
                }
                break;
            }
            else
                iters++;
        }

        // Release rw_lock
        if (pthread_rwlock_unlock(params -> rw_lock))
            { fprintf(stderr, "Error releasing rw_lock [output]\n"); exit(0); }

        loop_counter++;
    }   

    printf("%d: Exited gracefully [output]\n", (int) (time(NULL) - start));
    pthread_exit((void*) output_params);
}
Example #8
0
int main (int argc, char *argv[]) 
{
  int ntimglobal=0;  // number of time samples in original
  int ngulp_original=0;       // number of time samples to look at at once
  int nskipstart=0;       // number skipped at start
  int nrejects; //ZAPPER
  int zapswitch = 0; //ZAPPER  
  double tsamp_orig=0;

  //gsearch setup & defaults
  float Gsigmacut=6.0;
  float delta, tstart;
  vector<Gpulse> * Giant = new vector<Gpulse>[MAXFILES];
  bool Gsearched=false;

  int i,ntim,headersize[MAXFILES],noff=0,gulp;
  float *time_series[MAXFILES],sum=0.0,sumsq=0.0,mean,meansq,sigma;
  int MAXMARKERS = 1024;
  int nfiles = 0;
  FILE *inputfile[MAXFILES];
  char filename[MAXFILES][256];
  int spectra=0;
  int powerspectra=0;
  double dmoffirstfile;
  char *killfile;
  bool dokill=false;
  bool ssigned=true;
  bool fsigned=false;
  int topfold=-1;
  int topgiant=-1;
  int toppeak=-1; //?!? sarah added this 
  bool askdevice=false;
  char devicename[200];

  if (argc<2 || help_required(argv[1])) {
      helpmenu();
//    fprintf(stderr,"Usage: giant filenames\n\t(e.g.>>  giant *.tim)\n\n\t-s  N\tskip N samples\n\t-n  N\tread N samples\n\t-S read spectra instead of amplitudes\n-i interpret signed chars as unsigned\n\t-z make a zap list of bad time samples\n");
      exit(0);
  }
  print_version(argv[0],argv[1]);
  i=1;
  while (i<argc) {
    if (file_exists(argv[i]))          {
      inputfile[nfiles]=open_file(argv[i],"r");
      strcpy(filename[nfiles],argv[i]);
      nfiles++;
    }
    if (strings_equal(argv[i],"-s"))       sscanf(argv[++i],"%d",&nskipstart);
    if (strings_equal(argv[i],"-S"))       spectra=1;
    if (strings_equal(argv[i],"-i"))       ssigned=false;
    if (strings_equal(argv[i],"-f"))      fsigned=true;
    if (strings_equal(argv[i],"-n"))       sscanf(argv[++i],"%d",&ngulp_original);
    if (strings_equal(argv[i],"-c"))       sscanf(argv[++i],"%f",&Gsigmacut);
    if (strings_equal(argv[i],"-z"))       zapswitch=1;
    if (strings_equal(argv[i],"-g"))       {askdevice=true;sscanf(argv[++i],"%s",&devicename);}
    if (strings_equal(argv[i],"-k"))       {killfile=(char*)malloc(strlen(argv[++i])+1); strcpy(killfile,argv[i]);dokill=true;}
    if (nfiles>MAXFILES) error_message("too many open files");
    i++;
  }


  int ntimglobal_smallest=0, nsamp;
  for (i=0; i<nfiles; i++) {

    if (spectra){
      int npf; 
      double rate;
      time_series[i]=Creadspec(filename[i],&npf,&rate);
      tsamp = 1.0/(rate);
      //normalise(npf,time_series[i]);
      nsamp = ntimglobal = ntimglobal_smallest = npf;
    }
    else
    {
    if ((headersize[i]=read_header(inputfile[i]))) {
	    if (! fsigned){
		    if (isign > 0) {
			    ssigned=false;
			    fprintf(stderr,"using signed header variable to set UNSIGNED\n");
		    }
		    if (isign < 0) {
			    ssigned=true;
			    fprintf(stderr,"using signed header variable to set SIGNED\n");
		    }
	    }
      if (i==0) dmoffirstfile = refdm;
      if (nbits!=8 && nbits!=32)
	    error_message("giant currently only works for 8- or 32-bit data");

      nsamp = nsamples(filename[i],headersize[i],nbits,nifs,nchans);
      if (i == 0) {
	ntimglobal_smallest=nsamp;
      } else {
	ntimglobal= nsamp;
	if (ntimglobal < ntimglobal_smallest) ntimglobal_smallest = ntimglobal;
      }
      
      // Space for data (time_series)
      time_series[i]=(float *) malloc((nsamp+2)*sizeof(float));
      if (time_series[i]==NULL){
	fprintf(stderr,"Error mallocing %d floats of %d size\n",nsamp,
		sizeof(float));
	exit(-1);
      }
      tsamp_orig = tsamp;
      
      // Skip data
      fprintf(stderr,"Skipping %d bytes\n",nskipstart*nbits/8);
      fseek(inputfile[i],nskipstart*nbits/8,SEEK_CUR);
      
    } // each file
    } // spectra or not
  }  // for (i...)
  puti(ntimglobal_smallest);
  if (ngulp_original==0) ngulp_original=ntimglobal_smallest;


// ****** SAM'S ZAP SWITCH ******
// Sam Bates 2009
// Integrated into new giant by SBS
// Switch to make a .killtchan file for time samples > 3.5 sigma
// SARAHZAP tag means addition was added later by Sarah
// ******************************
  int ngulp=ngulp_original;
//  int nrejects_max=ngulp_original/100;
  int * mown = new int[ngulp_original];
  int nstart=0;
  if (zapswitch){
    float dummy;
    int NActuallyRead;
    char *buffer;
    buffer = new char[ngulp*nbits/8];
    for (i=0; i<nfiles; i++){
      NActuallyRead = fread(buffer,nbits/8,ngulp,inputfile[i]);
      if (nbits==32){
	memcpy(time_series[i],buffer,sizeof(float)*ngulp);
      } else {
	for (int j=0;j<NActuallyRead;j++){
	  if (ssigned) time_series[i][j]=(float)buffer[j];
	  if (!ssigned) time_series[i][j]=(float)((unsigned char)buffer[j]);
	}
      }
      puti(ngulp);
      find_baseline(ngulp,time_series[i],10.0/tsamp,5.0);
      mowlawn(ngulp,time_series[i],5,256);
    }
    printf("%f\n",dummy);
    printf("Bad time samples found...\n");
    exit(0);
  }


  int pgpID;
  if (askdevice){
      pgpID = cpgbeg(0,devicename,1,1);
  } else {
      pgpID = cpgbeg(0,"/xs",1,1);
  }
  cpgsch(0.5);
  cpgtext(0.6,0.0,"Press 'h' over the main window for help and full options list.");
  cpgsch(1.0);
  /* create the dialog */
  dialog * d = new dialog();

  /* add the "action" buttons */
  int QUIT         = d->addbutton(0.02,0.95,"Quit");
  int POWER        = d->addbutton(0.07,0.85,"POWER");
  int SMHRM        = d->addbutton(0.075,0.80,"SMHRM");
  int FFT          = d->addbutton(0.02,0.85,"FFT");
  int PLOT         = d->addbutton(0.02,0.80,"Plot");
  int NEXT         = d->addbutton(0.02,0.75,"Next");
  int ZAPPEAK      = d->addbutton(0.075,0.75,"ZapPeak");
  int RESET        = d->addbutton(0.02,0.70,"Reset");
  int GLOBALRESET  = d->addbutton(0.02,0.65,"Global Reset");
  int HALVEPLOT    = d->addbutton(0.02,0.60,"Halve Plot");
  int BASELINE     = d->addbutton(0.02,0.50,"Baseline");
  int ZAPCOMMON    = d->addbutton(0.02,0.45,"Zap Common");
  int SUBTRACTMEAN = d->addbutton(0.02,0.40,"ZAP Mean");
  int BSCRUNCH     = d->addbutton(0.02,0.35,"Bscrunch");
  int NORMALISE    = d->addbutton(0.02,0.30,"Normalise"); 
  int HISTOGRAM    = d->addbutton(0.02,0.25,"Histogram"); 
  int GSEARCH      = d->addbutton(0.02,0.20,"Find Giants");
  int MOWLAWN      = d->addbutton(0.08,0.70,"LAWN");
  int SEEFIL       = d->addbutton(0.02,0.15,"View Band");
  int FWRITE       = d->addbutton(0.02,0.05,"Write File");
 

  /* add the plot regions */
  d->addplotregion(0.2,0.99,0.98,0.99);
  float deltay = 0.9/(float)nfiles;
  for (i=0; i<nfiles; i++) 
      d->addplotregion(0.2,0.99,0.95-deltay*(float)(i+1),0.95-deltay*(float)i);

  d->draw();

  float x,y;
  char ans;
  int button=-1; int plotno=-1;
  int NPIXELS = 1024;
  float * xaxis = new float[NPIXELS];
  float * ymaxes = new float[NPIXELS];
  float * ymins = new float[NPIXELS];

  int scrunch=1;
  int nmarkers=0;
  int * markers= new int[MAXMARKERS];
  int nfileptr=nskipstart;
  int nplot=ngulp_original;
  nstart=0;  //COMMENTED IN ZAPPER VERSION: MAY CAUSE CONFLICTS IN THIS VER.
  ngulp=ngulp_original;  //COMMENTED IN ZAPPER VERSION: MAY CAUSE CONFLICTS IN THIS VER.
  double trialperiod;
  int doperiod=-1;
  double xperiod;

  bool zoneplot=false;
  int ngates=0;
  float xgate=0.0;



  button=NEXT;
  if (spectra) button = PLOT;
  while (button!=QUIT){
    // Plot the zone
    // Entire file is white
    if (button!=NEXT)button=d->manage(&x,&y,&ans,&plotno);
    if (ans=='h'){
	buttonexplain();
	continue;
    }
//    printf("manage x %f y %f plotno %d\n",x,y,plotno);
    if (button==BASELINE) {
	for (i=0; i<nfiles; i++){
	    find_baseline(ngulp,time_series[i],10.0/tsamp,5.0);
	}
	button = PLOT;
	zoneplot=false;
        plotno = -1;
    }
    if (button==FWRITE) {
      // reread first header and close it. Sets globals.
      fclose(inputfile[0]);
      inputfile[0]=open_file(argv[1],"r");
      headersize[0]=read_header(inputfile[0]);
      output = open_file("giant.tim","w");
      nobits=32;
      nbands=1;
      dedisperse_header();
      fprintf(stderr,"Opened file, writing data\n");
      fwrite(time_series[0],sizeof(float),ngulp,output);
      fclose(output);
      button = -1;
      zoneplot=false;
      plotno =-1;
    }
    if (button==BSCRUNCH) {
	for (i=0; i<nfiles; i++){
	    bscrunch(ngulp,time_series[i]);
	}
	tsamp*=2;
	scrunch*=2;
      	ngulp/=2;
	nplot/=2;
	button = PLOT;
	zoneplot=false;
	Gsearched=false;
        plotno = -1;
    }
    if (button==FFT) {
	for (i=0; i<nfiles; i++){
	  ngulp = ngulp_original;
	  find_fft(&ngulp,time_series[i]);
	// Zap DC spike
	  time_series[i][0]=0.0;
	  time_series[i][1]=0.0;
	}
	spectra = 1;
	nplot = ngulp;
	button = PLOT;
	Gsearched=false;
        plotno = -1;
    }
    if (button==POWER) {
	for (i=0; i<nfiles; i++){
	  find_formspec(ngulp,time_series[i]);
	}
	ngulp/=2;
	powerspectra = 1;
	nplot = ngulp;
	button = PLOT;
        plotno = -1;
    }
    if (button==SMHRM) {
        nfiles = 6;
	for (i=1; i<nfiles; i++){
	  time_series[i]=(float *) malloc((ngulp+2)*sizeof(float));
	  if (time_series[i]==NULL){
	    fprintf(stderr,"Error allocating memory\n");
	    exit(-1);
	  }
	}
	for (i=1;i<nfiles;i++) memcpy(time_series[i],time_series[0],
				      (ngulp+2)*sizeof(float));
	d->nplotregion=1;
        float deltay = 0.9/(float)nfiles;
        for (i=0; i<nfiles; i++) 
          d->addplotregion(0.2,0.99,0.95-deltay*(float)(i+1),
			   0.95-deltay*(float)i);
	cpgeras();
	d->draw();

	float * workspace = new float[ngulp];

	// Set up space for data, now actually sumhrm
	int one=1;
			newoldsumhrm_(&time_series[0][1],workspace,&ngulp,&one,
	//		newoldsumhrm_(&time_series[0][0],workspace,&ngulp,&one,
		   time_series[1],time_series[2],time_series[3],
		   time_series[4],time_series[5]);
		/*	newnewsumhrm_(time_series[0],&ngulp,&one,
		   time_series[1],time_series[2],time_series[3],
		   time_series[4],time_series[5]);*/
		for (int iff=2;iff<6;iff++){
		  for (int i=0;i<ngulp;i++){
		    time_series[iff][i]/=sqrt(pow(2.0,(float)(iff-1)));
		  }
		}
	delete [] workspace;
	button = PLOT;
        plotno = -1;
    }
    if (button==NORMALISE) {
	for (i=0; i<nfiles; i++){
	  normalise(ngulp,time_series[i],5.0);
	}
	button = PLOT;
	Gsearched=false;
        plotno = -1;
    }
    if (button==HISTOGRAM) {
      float pdfs[nfiles][MAXSIGMA];
      //  create pdfs for each beam
      for (int i=0;i<nfiles;i++)
	formpdf(pdfs[i],MAXSIGMA,ngulp,time_series[i]);

      for (int i=0;i<nfiles;i++){
	for (int j=0;j<MAXSIGMA; j++){
	  fprintf(stderr, "pdfs[%d][%2d]=%8.0f %f \%\n", i, j+1, pdfs[i][j], 100*pdfs[i][j]/ngulp);
	}
      }
        button = PLOT;
        plotno = -1;
    }
    if (button==HALVEPLOT) {
	nplot/=2;
	button = PLOT;
	zoneplot=true;
	Gsearched=false;
        plotno = -1;
    }
    if (button==GLOBALRESET) {
      plotno = -1;
      nstart = 0;
      scrunch=1;
      tsamp = tsamp_orig;
      nplot=ngulp_original;
      ngulp=ngulp_original;
      button=PLOT;
      // Skip to end of skipped data
      for (i=0; i<nfiles; i++){
	fseek(inputfile[i],-(nfileptr-nskipstart)*nbits/8,SEEK_CUR);
	Giant[i].clear();
      }
      nfileptr=nskipstart;
      zoneplot=false;
      Gsearched=false;
      doperiod=-1;
      button=NEXT;
    }
    if (button==SUBTRACTMEAN && nfiles>1) {
      plotno = -1;
      nstart = 0;
      nplot=ngulp_original;
      ngulp=ngulp_original;
      button=PLOT;
      // Skip to end of skipped data
	for (int jj=0;jj<ngulp;jj++){
	  float sum;
	  sum=0.0;
	  for (i=1;i<nfiles;i++){
	    sum+=time_series[i][jj];
	  }
	  time_series[0][jj]-=sum/(float(nfiles-1));
	}
	Gsearched=false;
    }
    if (button==ZAPCOMMON && nfiles>1) {
      plotno = -1;
      nstart = 0;
      nplot=ngulp_original;
      ngulp=ngulp_original;
      button=PLOT;
      float pdfs[nfiles][MAXSIGMA];
      //  create pdfs for each beam
      for (int i=0;i<nfiles;i++)
	formpdf(pdfs[i],MAXSIGMA,ngulp,time_series[i]);
      //  for each point in each beam, mask if improbable
      float thresh = 3.0;
      int nbeammax = 5;
      zap_improbables(pdfs,time_series,nfiles,ngulp,MAXSIGMA,thresh,nbeammax);
      // Skip to end of skipped data
      //for (int jj=0;jj<ngulp;jj++){
      //  float sum;
      //  sum=0.0;
      //  for (i=1;i<nfiles;i++){
      //    sum+=time_series[i][jj];
      //  }
      //  time_series[0][jj]-=sum/(float(nfiles-1));
      //}
      //Gsearched=false;
    }
    if (button==NEXT) {
      ngulp=ngulp_original;
      nstart=0;
      nplot=ngulp_original;
      // Read the data
      int NActuallyRead;
      //      unsigned char *buffer;
      char *buffer;
      buffer = new char[ngulp*nbits/8];
      //buffer = new char[ngulp*nbits/8];
      for (i=0; i<nfiles; i++) {
//	NActuallyRead = fread(time_series[i],sizeof(float),ngulp,inputfile[i]);
	NActuallyRead = fread(buffer,nbits/8,ngulp,inputfile[i]);
	if (nbits==32){
	  memcpy(time_series[i],buffer,sizeof(float)*ngulp);
	} else {
	    for (int j=0;j<NActuallyRead;j++){
	      if (ssigned) time_series[i][j]=(float)buffer[j];
	      if (!ssigned) time_series[i][j]=(float)((unsigned char)buffer[j]);
	    }
	}
	
	puti(ngulp);
	if (NActuallyRead!=ngulp){
	  fprintf(stderr,"Could not read %d floats from file\n",ngulp);
	  ngulp = NActuallyRead;
	}
	if(nfiles==1){
	  // Add fake pulsar here....
	  //	  for (int ii=0;ii<ngulp;ii++) time_series[i][ii]+= 10.0*pow(sin(float(ii*2.0*M_PI/60.0)),250.0);
	}
	//normalise(ngulp,time_series[i]);
      }
      nfileptr+=ngulp;
      button = PLOT;
      plotno= -1;
      zoneplot=true;
    }
    if (button==RESET) {
      button = plotno = -1;
      nstart=0;
      nplot=ngulp;
      button=PLOT;
      zoneplot=true;
      Gsearched=false;
      if (ans=='p'){
	doperiod=-1;
      }
    }
    if (plotno>0){
/*      if (ans=='p'){  // hit p on a plot to type in a period
	d->plotregions[plotno].reset();
	//plot the thing;
	fprintf(stderr,"Please enter a period in seconds: ");
	cin>>trialperiod;
	xperiod = x;
	doperiod=plotno;
	button=PLOT;
	}*/
      if (ans=='p'){  // hit p on a plot to type in a period
	d->plotregions[plotno].reset();
	//plot the thing;
	fprintf(stderr,"Please enter a period in seconds: ");
	cin>>trialperiod;
	xperiod = (double)x;
	doperiod=plotno;
	button=PLOT;
      }
      if (ans=='m'){  // subtract 0.0000005 seconds from period
	d->plotregions[plotno].reset();
	trialperiod-=0.0000005;
	fprintf(stderr,"Trial period is now %lf\n",trialperiod);
	doperiod=plotno;
	button=PLOT;
      }
      if (ans=='/'){  // add 0.0000005 seconds to period
	d->plotregions[plotno].reset();
	trialperiod+=0.0000005;
	fprintf(stderr,"Trial period is now %lf\n",trialperiod);
	doperiod=plotno;
	button=PLOT;
      }
      if (ans==','){  // subtract 0.000005 seconds from period
	d->plotregions[plotno].reset();
	trialperiod-=0.000005;
	fprintf(stderr,"Trial period is now %lf\n",trialperiod);
	doperiod=plotno;
	button=PLOT;
      }
      if (ans=='.'){  // add 0.000005 seconds to period
	d->plotregions[plotno].reset();
	trialperiod+=0.000005;
	fprintf(stderr,"Trial period is now %lf\n",trialperiod);
	doperiod=plotno;
	button=PLOT;
      }
      if (ans=='<'){  // subtract 0.001 seconds from period
	d->plotregions[plotno].reset();
	trialperiod-=0.001;
	fprintf(stderr,"Trial period is now %lf\n",trialperiod);
	doperiod=plotno;
	button=PLOT;
      }
      if (ans=='>'){  // add 0.001 seconds to period
	d->plotregions[plotno].reset();
	trialperiod+=0.001;
	fprintf(stderr,"Trial period is now %lf\n",trialperiod);
	doperiod=plotno;
	button=PLOT;
      }
      if (ans=='X'){  // right click two points on a plot to calculate and plot a period
	d->plotregions[plotno].reset();
	cpgsci(3);
	cpgmove(x,-1000);
	cpgdraw(x,1000);
	if (ngates==0){
	  xgate=x;
	  ngates++;
	} else {
	  min_means_min(&x,&xgate);
	  printf("Period from %f to %f is %f\n",x,xgate,xgate-x);  
	  doperiod=plotno;
	  xperiod = (double)x;
	  trialperiod=(double)(xgate-x);
	  ngates=0;
	  button=PLOT;
	}
      }
      if (ans=='D'){
	markers[nmarkers]=(int)(x/NPIXELS)*nplot+nstart+nfileptr-ngulp;
	nmarkers++;
	zoneplot=true;
      }
      if (ans=='A'){
	d->plotregions[plotno].reset();
	cpgsci(2);
	cpgmove(x,-1000);
	cpgdraw(x,1000);
	if (ngates==0){
	  xgate=x;
	  ngates++;
	} else {
	  min_means_min(&x,&xgate);
//	  printf("x %f xgate %f tstart %f\n",x,xgate,tstart);
	  nstart=(int)((x-tstart)/delta)+nstart;
	  nplot=(int)((xgate-x)/delta);
	  //if (nplot<NPIXELS) nplot=NPIXELS;
	  ngates=0;
	  button=PLOT;
	  zoneplot=true;
//	  printf("nplot %d nstart %d\n",nplot,nstart);
	}
      }
      if (ans=='z'){
	if (NPIXELS>nplot) {
	  nstart+=(int)x;
	}else
	nstart=(int)(x/(float)NPIXELS*nplot)+nstart;
	printf("nstart %d\n",nstart);
	nplot/=4;
	printf("nplot %d\n",nplot);
	nstart-=nplot/2;
	printf("nstart %d\n",nstart);
	//if (nplot<NPIXELS){nplot=NPIXELS;}
	button=PLOT;
	zoneplot=true;
      }
    }
Example #9
0
int main()

{
  char   text[80];
  int    ci, crval1, crval2, ilat, ilng, j, k, latpole, lonpole, stat[361],
         status;
  float  xr[512], yr[512];
  double lat[181], lng[361], phi[361], theta[361], x[361], y[361];
  struct celprm native, celestial;


  printf(
  "Testing WCSLIB celestial coordinate transformation routines (tcel1.c)\n"
  "---------------------------------------------------------------------\n");

  /* List status return messages. */
  printf("\nList of cel status return values:\n");
  for (status = 1; status <= 6; status++) {
    printf("%4d: %s.\n", status, cel_errmsg[status]);
  }

  printf("\n");


  /* Initialize. */
  celini(&native);

  /* Reference angles for the native graticule (in fact, the defaults). */
  native.ref[0] = 0.0;
  native.ref[1] = 0.0;

  /* Set up Bonne's projection with conformal latitude at +35. */
  strcpy(native.prj.code, "BON");
  native.prj.pv[1] = 35.0;


  /* Celestial graticule. */
  celini(&celestial);
  celestial.prj = native.prj;


  /* PGPLOT initialization. */
  strcpy(text, "/xwindow");
  cpgbeg(0, text, 1, 1);

  /* Define pen colours. */
  cpgscr(0, 0.0f, 0.0f, 0.0f);
  cpgscr(1, 1.0f, 1.0f, 0.0f);
  cpgscr(2, 1.0f, 1.0f, 1.0f);
  cpgscr(3, 0.5f, 0.5f, 0.8f);
  cpgscr(4, 0.8f, 0.5f, 0.5f);
  cpgscr(5, 0.8f, 0.8f, 0.8f);
  cpgscr(6, 0.5f, 0.5f, 0.8f);
  cpgscr(7, 0.8f, 0.5f, 0.5f);
  cpgscr(8, 0.3f, 0.5f, 0.3f);

  /* Define PGPLOT viewport. */
  cpgenv(-180.0f, 180.0f, -90.0f, 140.0f, 1, -2);

  /* Loop over CRVAL2, LONPOLE, and LATPOLE with CRVAL1 incrementing by */
  /* 15 degrees each time (it has an uninteresting effect).             */
  crval1 = -180;
  for (crval2 = -90; crval2 <=  90; crval2 += 30) {
    for (lonpole = -180; lonpole <= 180; lonpole += 30) {
      for (latpole = -1; latpole <= 1; latpole += 2) {
        /* For the celestial graticule, set the celestial coordinates of
         * the reference point of the projection (which for Bonne's
         * projection is at the intersection of the native equator and
         * prime meridian), the native longitude of the celestial pole,
         * and extra information needed to determine the celestial
         * latitude of the native pole.  These correspond to FITS keywords
         * CRVAL1, CRVAL2, LONPOLE, and LATPOLE.
         */
        celestial.ref[0] = (double)crval1;
        celestial.ref[1] = (double)crval2;
        celestial.ref[2] = (double)lonpole;
        celestial.ref[3] = (double)latpole;

        /* Skip invalid values of LONPOLE. */
        if (celset(&celestial)) {
          continue;
        }

        /* Skip redundant values of LATPOLE. */
        if (latpole == 1 && fabs(celestial.ref[3]) < 0.1) {
          continue;
        }

        /* Buffer PGPLOT output. */
        cpgbbuf();
        cpgeras();

        /* Write a descriptive title. */
        sprintf(text, "Bonne's projection (BON) - 15 degree graticule");
        printf("\n%s\n", text);
        cpgtext(-180.0f, -100.0f, text);

        sprintf(text, "centred on celestial coordinates (%7.2f,%6.2f)",
          celestial.ref[0], celestial.ref[1]);
        printf("%s\n", text);
        cpgtext (-180.0f, -110.0f, text);

        sprintf(text, "with north celestial pole at native coordinates "
          "(%7.2f,%7.2f)", celestial.ref[2], celestial.ref[3]);
        printf("%s\n", text);
        cpgtext(-180.0f, -120.0f, text);


        /* Draw the native graticule faintly in the background. */
        cpgsci(8);

        /* Draw native meridians of longitude. */
        for (j = 0, ilat = -90; ilat <= 90; ilat++, j++) {
          lat[j] = (double)ilat;
        }

        for (ilng = -180; ilng <= 180; ilng += 15) {
          lng[0] = (double)ilng;
          if (ilng == -180) lng[0] = -179.99;
          if (ilng ==  180) lng[0] =  179.99;

          /* Dash the longitude of the celestial pole. */
          if ((ilng-lonpole)%360 == 0) {
            cpgsls(2);
            cpgslw(5);
          }

          cels2x(&native, 1, 181, 1, 1, lng, lat, phi, theta, x, y, stat);

          k = 0;
          for (j = 0; j < 181; j++) {
            if (stat[j]) {
              if (k > 1) cpgline(k, xr, yr);
              k = 0;
              continue;
            }

            xr[k] = -x[j];
            yr[k] =  y[j];
            k++;
          }

          cpgline(k, xr, yr);
          cpgsls(1);
          cpgslw(1);
        }

        /* Draw native parallels of latitude. */
        lng[0]   = -179.99;
        lng[360] =  179.99;
        for (j = 1, ilng = -179; ilng < 180; ilng++, j++) {
          lng[j] = (double)ilng;
        }

        for (ilat = -90; ilat <= 90; ilat += 15) {
          lat[0] = (double)ilat;

          cels2x(&native, 361, 1, 1, 1, lng, lat, phi, theta, x, y, stat);

          k = 0;
          for (j = 0; j < 361; j++) {
            if (stat[j]) {
              if (k > 1) cpgline(k, xr, yr);
              k = 0;
              continue;
            }

            xr[k] = -x[j];
            yr[k] =  y[j];
            k++;
          }

          cpgline(k, xr, yr);
        }


        /* Draw a colour-coded celestial coordinate graticule. */
        ci = 1;

        /* Draw celestial meridians of longitude. */
        for (j = 0, ilat = -90; ilat <= 90; ilat++, j++) {
          lat[j] = (double)ilat;
        }

        for (ilng = -180; ilng <= 180; ilng += 15) {
          lng[0] = (double)ilng;

          if (++ci > 7) ci = 2;
          cpgsci(ilng?ci:1);

          /* Dash the reference longitude. */
          if ((ilng-crval1)%360 == 0) {
            cpgsls(2);
            cpgslw(5);
          }

          cels2x(&celestial, 1, 181, 1, 1, lng, lat, phi, theta, x, y, stat);

          k = 0;
          for (j = 0; j < 181; j++) {
            if (stat[j]) {
              if (k > 1) cpgline(k, xr, yr);
              k = 0;
              continue;
            }

            /* Test for discontinuities. */
            if (j > 0) {
              if (fabs(x[j]-x[j-1]) > 4.0 || fabs(y[j]-y[j-1]) > 4.0) {
                if (k > 1) cpgline(k, xr, yr);
                k = 0;
              }
            }

            xr[k] = -x[j];
            yr[k] =  y[j];
            k++;
          }

          cpgline(k, xr, yr);
          cpgsls(1);
          cpgslw(1);
        }

        /* Draw celestial parallels of latitude. */
        for (j = 0, ilng = -180; ilng <= 180; ilng++, j++) {
          lng[j] = (double)ilng;
        }

        ci = 1;
        for (ilat = -90; ilat <= 90; ilat += 15) {
          lat[0] = (double)ilat;

          if (++ci > 7) ci = 2;
          cpgsci(ilat?ci:1);

          /* Dash the reference latitude. */
          if (ilat == crval2) {
            cpgsls(2);
            cpgslw(5);
          }

          cels2x(&celestial, 361, 1, 1, 1, lng, lat, phi, theta, x, y, stat);

          k = 0;
          for (j = 0; j < 361; j++) {
            if (stat[j]) {
              if (k > 1) cpgline(k, xr, yr);
              k = 0;
              continue;
            }

            /* Test for discontinuities. */
            if (j > 0) {
              if (fabs(x[j]-x[j-1]) > 4.0 || fabs(y[j]-y[j-1]) > 4.0) {
                if (k > 1) cpgline(k, xr, yr);
                k = 0;
              }
            }

            xr[k] = -x[j];
            yr[k] =  y[j];
            k++;
          }

          cpgline(k, xr, yr);
          cpgsls(1);
          cpgslw(1);
        }

        /* Flush PGPLOT buffer. */
        cpgebuf();
        printf(" Type <RETURN> for next page: ");
        getc(stdin);

        /* Cycle through celestial longitudes. */
        if ((crval1 += 15) > 180) crval1 = -180;

        /* Skip boring celestial latitudes. */
        if (crval2 == 0) break;
      }

      if (crval2 == 0) break;
    }
  }

  cpgask(0);
  cpgend();

  return 0;
}
Example #10
0
int main()

{
  char text[80];
  int  naxisj, nFail = 0, status;
  double cdeltX, crpixj, crvalX, restfrq, restwav, x1, x2;


  printf(
    "Testing closure of WCSLIB spectral transformation routines (tspc.c)\n"
    "-------------------------------------------------------------------\n");

  /* List status return messages. */
  printf("\nList of spc status return values:\n");
  for (status = 1; status <= 4; status++) {
    printf("%4d: %s.\n", status, spc_errmsg[status]);
  }


  /* PGPLOT initialization. */
  strcpy(text, "/xwindow");
  cpgbeg(0, text, 1, 1);

  naxisj = NSPEC;
  crpixj = naxisj/2 + 1;

  restfrq = 1420.40595e6;
  restwav = C/restfrq;
  x1 = 1.0e9;
  x2 = 2.0e9;
  cdeltX = (x2 - x1)/(naxisj - 1);
  crvalX = x1 + (crpixj - 1.0)*cdeltX;
  printf("\nLinear frequency axis, span: %.1f to %.1f (GHz), step: %.3f "
         "(kHz)\n---------------------------------------------------------"
         "-----------------\n", x1*1e-9, x2*1e-9, cdeltX*1e-3);
  nFail += closure("WAVE-F2W",     0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VOPT-F2W",     0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("ZOPT-F2W",     0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("AWAV-F2A",     0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VELO-F2V", restfrq,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("BETA-F2V", restfrq,     0.0, naxisj, crpixj, cdeltX, crvalX);

  restwav = 700.0e-9;
  restfrq = C/restwav;
  x1 = 300.0e-9;
  x2 = 900.0e-9;
  cdeltX = (x2 - x1)/(naxisj - 1);
  crvalX = x1 + (crpixj - 1.0)*cdeltX;
  printf("\nLinear vacuum wavelength axis, span: %.0f to %.0f (nm), "
         "step: %f (nm)\n---------------------------------------------"
         "-----------------------------\n", x1*1e9, x2*1e9, cdeltX*1e9);
  nFail += closure("FREQ-W2F",     0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("AFRQ-W2F",     0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("ENER-W2F",     0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("WAVN-W2F",     0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VRAD-W2F", restfrq,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("AWAV-W2A",     0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VELO-W2V",     0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("BETA-W2V",     0.0, restwav, naxisj, crpixj, cdeltX, crvalX);


  printf("\nLinear air wavelength axis, span: %.0f to %.0f (nm), "
         "step: %f (nm)\n------------------------------------------"
         "--------------------------------\n", x1*1e9, x2*1e9, cdeltX*1e9);
  nFail += closure("FREQ-A2F", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("AFRQ-A2F", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("ENER-A2F", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("WAVN-A2F", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VRAD-A2F", restfrq, 0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("WAVE-A2W", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VOPT-A2W", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("ZOPT-A2W", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VELO-A2V", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("BETA-A2V", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);


  restfrq = 1420.40595e6;
  restwav = C/restfrq;
  x1 = -0.96*C;
  x2 =  0.96*C;
  cdeltX = (x2 - x1)/(naxisj - 1);
  crvalX = x1 + (crpixj - 1.0)*cdeltX;
  printf("\nLinear velocity axis, span: %.0f to %.0f m/s, step: %.0f "
         "(m/s)\n------------------------------------------------------"
         "--------------------\n", x1, x2, cdeltX);
  nFail += closure("FREQ-V2F", restfrq, 0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("AFRQ-V2F", restfrq, 0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("ENER-V2F", restfrq, 0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("WAVN-V2F", restfrq, 0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VRAD-V2F", restfrq, 0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("WAVE-V2W", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VOPT-V2W", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("ZOPT-V2W", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("AWAV-V2A", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);


  restwav = 650.0e-9;
  restfrq = C/restwav;
  x1 =  300e-9;
  x2 = 1000e-9;
  cdeltX = (x2 - x1)/(naxisj - 1);
  crvalX = x1 + (crpixj - 1.0)*cdeltX;
  printf("\nVacuum wavelength grism axis, span: %.0f to %.0f (nm), "
         "step: %f (nm)\n--------------------------------------------"
         "------------------------------\n", x1*1e9, x2*1e9, cdeltX*1e9);
  nFail += closure("FREQ-GRI", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("AFRQ-GRI", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("ENER-GRI", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("WAVN-GRI", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VRAD-GRI", restfrq, 0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("WAVE-GRI", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VOPT-GRI", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("ZOPT-GRI", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("AWAV-GRI", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VELO-GRI", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("BETA-GRI", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);


  /* Reproduce Fig. 5 of Paper III. */
  naxisj = 1700;
  crpixj = 719.8;
  crvalX = 7245.2e-10;
  cdeltX = 2.956e-10;
  restwav = 8500.0e-10;
  restfrq = C/restwav;
  x1 = crvalX + (1 - crpixj)*cdeltX;
  x2 = crvalX + (naxisj - crpixj)*cdeltX;
  mars[5] = 0.0;
  mars[6] = 0.0;
  printf("\nAir wavelength grism axis, span: %.0f to %.0f (nm), "
         "step: %f (nm)\n--------------------------------------------"
         "------------------------------\n", x1*1e9, x2*1e9, cdeltX*1e9);
  nFail += closure("AWAV-GRA", 0.0,     0.0, naxisj, crpixj, cdeltX, crvalX);
  nFail += closure("VELO-GRA", 0.0, restwav, naxisj, crpixj, cdeltX, crvalX);

  cpgask(0);
  cpgend();

  if (nFail) {
    printf("\nFAIL: %d closure residuals exceed reporting tolerance.\n",
      nFail);
  } else {
    printf("\nPASS: All closure residuals are within reporting tolerance.\n");
  }

  return nFail;
}
Example #11
0
main(int argc, char *argv[])
{
  FILE *output;
  int numerate,i,j,k,l,nsperdmp,nsamps,indexing,plot,indexnow;
  int ifchan[16],frchan[4096],ifnum,chnum,ns,sample,ntotal;
  float time_of_pulse, width_of_pulse, time, time_start, time_end;
  float series_amp[100000],series_time[100000],ampmin,ampmax;
  char message[80],outfile[80],filename[80],timestring[80],pgdev[80];
  unsigned char c;
  unsigned short s;
  float f[8];

    if (argc<2) {
    puts("");
    puts("getpulse - make and/or plot a time series from dedispersed file\n"); 
    puts("usage: getpulse {filename} -{options}\n");
    puts("filename is the dedispersed data file\n");
    puts("options:\n");
    puts("-t time - time (in seconds) on which to center time series (REQUIRED)\n");
    puts("-w width - width (in seconds) of time series to plot (def=1)\n");
    puts("-c fchan - to only output frequency channel fchan (def=all)\n");
    puts("-i ifchan - to only output IF channel ifchan (def=all)\n");
    puts("-p pgdev - pgplot device (def=/xs)\n");
    puts("-numerate - to precede each dump with sample number (def=time)\n");
    puts("-noindex - do not precede each dump with time/number\n");
    puts("-plot - PGPLOT the results\n");
    puts("");
    exit(0);
   }

  /* zero IF and frequency channel arrays */
  for (i=0;i<16;i++)   ifchan[i]=0;
  for (i=0;i<4096;i++) frchan[i]=0;

  /* default case is to read from standard input */
  input=stdin;
  numerate=0;
  ampmin = 1.e6;
  ampmax = -1.e6;
  plot=0;
  indexnow=0;
  indexing=1;
  strcpy(pgdev,"/xs");

  /* parse command line if arguments were given */
  if (argc>1) {
    i=1;
    while (i<argc) {
        if (strings_equal(argv[i],"-i")) {
	i++;
	ifchan[atoi(argv[i])-1]=1;
      } else if (strings_equal(argv[i],"-c")) {
	i++;
	frchan[atoi(argv[i])-1]=1;
      } else if (strings_equal(argv[i],"-t")) {
        i++;
	time_of_pulse = atof(argv[i]);
        strcpy(timestring,argv[i]);
	fprintf(stderr,"centering on time %f s\n",time_of_pulse); 
      } else if (strings_equal(argv[i],"-w")) {
        i++;
        width_of_pulse = atof(argv[i]);
        fprintf(stderr,"with width %f s\n",width_of_pulse);
      } else if (strings_equal(argv[i],"-p")) {
        i++;
        strcpy(pgdev,argv[i]); 
      } else if (strings_equal(argv[i],"-numerate")) {
	numerate=1;
      } else if (strings_equal(argv[i],"-noindex")) {
	indexing=0;
      } else if (strings_equal(argv[i],"-plot")) {
	plot=1;
      } else if (file_exists(argv[i])) {
	input=open_file(argv[i],"rb");
        strcpy(filename,argv[i]);
      } else {
	sprintf(message,"unknown argument (%s) passed to getpulse",argv[i]);
	error_message(message);
      }
      i++;
    }
  }

  strcat(filename,".pulse.");
  strcat(filename,timestring);
  strcpy(outfile,filename);
  output=fopen(outfile,"w");
  time_start = time_of_pulse - width_of_pulse/2.;
  time_end = time_of_pulse + width_of_pulse/2.;
  sample = 0;
  /* try to read the header */
  if (!read_header(input)) error_message("error reading header\n");

  /* check what IF and frequency channels (if any the user has selected) */
  j=0;
  for (i=0; i<nifs; i++) if (ifchan[i]) j++;
  if (j==0) for (i=0; i<nifs; i++) ifchan[i]=1;
  j=0;
  for (i=0; i<nchans; i++) if (frchan[i]) j++;
  if (j==0) for (i=0; i<nchans; i++) frchan[i]=1;

  /* number of samples to read per dump */
  nsperdmp=nifs*nchans;
  /* initialize loop counters and flags */
  ifnum=chnum=nsamps=l=0;

  while (!feof(input)) {

    /* unpack the sample(s) if necessary */
    switch (nbits) {
    case 1:
      fread(&c,1,1,input);
      for (i=0;i<8;i++) {
	f[i]=c&1;
	c>>=1;
      }
      ns=8;
      break;
    case 4:
      fread(&c,1,1,input);
      char2ints(c,&j,&k);
      f[0]=(float) j;
      f[1]=(float) k;
      ns=2;
      break;
    case 8:
      fread(&c,nbits/8,1,input);
      f[0]=(float) c;
      ns=1;
      break;
    case 16:
      fread(&s,nbits/8,1,input);
      f[0]=(float) s;
      ns=1;
      break;
    case 32:
      fread(&f[0],nbits/8,1,input);
      ns=1;
      break;
    default:
      sprintf(message,"cannot read %d bits per sample...\n",nbits);
      error_message(message);
      break;
    }

    if (plot) {
       ntotal = (time_end-time_start)/tsamp;
       if (ntotal > 100000) {
	  fprintf(stderr,"Too many samples to plot!\n");
	  plot=0;
	}
    }
    for (i=0; i<ns; i++) {
      /* time stamp or index the data */
      time = (double) tsamp * (double) l;
      if (time > time_end) {
         if (plot) {
	       indexnow=indexnow-1;
	       cpgbeg(0,pgdev,1,1);
               cpgsvp(0.1,0.9,0.1,0.9);
               cpgswin(series_time[0],series_time[indexnow],ampmin-0.1*ampmax,ampmax+0.1*ampmax);
               cpgbox("bcnst",0.0,0,"bcnst",0,0.0);
               cpgline(indexnow,series_time,series_amp);
               cpgscf(2);
	       cpgmtxt("B",2.5,0.5,0.5,"Time (s)");
	       cpgmtxt("L",1.8,0.5,0.5,"Amplitude");
               cpgend();}
	    exit(0);
      }
      /* print sample if it is one of the ones selected */
      if (ifchan[ifnum] && frchan[chnum] && time >= time_start && time <= time_end) {
	if (indexing) {
           if (numerate) fprintf(output,"%d %f\n",l,f[i]);
           else fprintf(output,"%f %f\n",time,f[i]);
        }	
	else {
	   fprintf(output,"%f\n",f[i]);
	}
	if (plot) {
	   series_amp[indexnow]=f[i];
	   series_time[indexnow]=time;
           if (f[i] < ampmin) ampmin = f[i];
           if (f[i] > ampmax) ampmax = f[i];
           indexnow++;
	}
      } 
      nsamps++;
      chnum++;
      if (chnum==nchans) {
	chnum=0;
	ifnum++;
	if (ifnum==nifs) ifnum=0;
      }
      if ((nsamps%nsperdmp)==0) {
	nsamps=0;
	l++;
      }
      }
	}
    fclose(output);

}
Example #12
0
void main()
{
   
   float RES = (XMAX - XMIN)/N;                          //resolution
   
   int i,j,p;
   
    
   
   //************************* PGPLOT CODE ***************************
  
  cpgbeg(0,"?",1,1);
  cpgpage();
  
  cpgsci(1);                                           // axis color
  
  cpgpap(0,1);
  
                                                      //axis limits
  cpgswin(XMIN,XMAX,YMIN,YMAX);
  
  cpgbox("BCN",1, 0, "BCN", 1, 0);                  // draw the axes
  
  cpgsci(1);                                          //data color

  cpgsch(0.00000000000001);                        //data point size
  
  
  
  //******************* GRID ALGORITHM AND PLOTTING *******************
  
  
  struct cnum z;                      //complex variables z and c introduced
  struct cnum c;
  
  for(i=0;i<N;i++)                    //look at every point on grid
  {
    for(j=0;j<N;j++)                       
    {
       z.cx = XMIN + i*RES;           // z = current point
       z.cy = YMIN + j*RES;         
       
       CPRINT(z);                     
       
       c.cx = z.cx;                   // keep z, feed c=z in to iteration
       c.cy = z.cy;
          
       for(p=0;p<MNI;p++)                  //apply MNI iterations to c
       {                                     
	 c = FJULIA(c);
	 
	 if ( c.cx*c.cx + c.cy*c.cy > R)    // if iteration "blows up"... 
	 {
	   z.cx = 0;
	   z.cy = 0;
	   c.cx = 0;
	   c.cy = 0;
	 }
	   
       }                                  
           
           
       if (c.cx*c.cx + c.cy*c.cy < R)      //if iteration hasn't blown up...
       {
	 float X[1], Y[1];
	 X[0] = z.cx;
	 Y[0] = z.cy;
	 cpgpt(1,X,Y,17);                  // plot point z
       }
       
       
    }
    
  }
   
  printf("\n\n");                             
 
  cpgend();                       
  
  
   
}
Example #13
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();
}
Example #14
0
int main()

{
  void prjplt();
  int  status;
  char text[80], text1[80], text2[80];
  struct prjprm prj;


  printf("Testing WCSLIB spherical projection routines (tprj2.c)\n"
         "------------------------------------------------------\n");

  /* List status return messages. */
  printf("\nList of prj status return values:\n");
  for (status = 1; status <= 4; status++) {
    printf("%4d: %s.\n", status, prj_errmsg[status]);
  }

  printf("\n");


  /* PGPLOT initialization. */
  strcpy(text, "/xwindow");
  cpgbeg(0, text, 1, 1);

  /* Define pen colours. */
  cpgscr(0, 0.00f, 0.00f, 0.00f);
  cpgscr(1, 1.00f, 1.00f, 0.00f);
  cpgscr(2, 1.00f, 1.00f, 1.00f);
  cpgscr(3, 0.50f, 0.50f, 0.80f);
  cpgscr(4, 0.80f, 0.50f, 0.50f);
  cpgscr(5, 0.80f, 0.80f, 0.80f);
  cpgscr(6, 0.50f, 0.50f, 0.80f);
  cpgscr(7, 0.80f, 0.50f, 0.50f);
  cpgscr(8, 0.30f, 0.50f, 0.30f);

  strcpy(text1, "\n%s projection\n");
  strcpy(text2, "\n%s projection\nParameters:");

  prjini(&prj);

  /* AZP: zenithal/azimuthal perspective. */
  prj.pv[1] =   2.0;
  prj.pv[2] =  30.0;
  printf(text2, "Zenithal/azimuthal perspective");
  printf("%12.5f%12.5f\n", prj.pv[1], prj.pv[2]);
  prjplt("AZP", 90, -90, &prj);

  /* SZP: slant zenithal perspective. */
  prj.pv[1] =   2.0;
  prj.pv[2] = 210.0;
  prj.pv[3] =  60.0;
  printf(text2, "Slant zenithal perspective");
  printf("%12.5f%12.5f%12.5f\n", prj.pv[1], prj.pv[2], prj.pv[3]);
  prjplt("SZP", 90, -90, &prj);

  /* TAN: gnomonic. */
  printf(text1, "Gnomonic");
  prjplt("TAN", 90,   5, &prj);

  /* STG: stereographic. */
  printf(text1, "Stereographic");
  prjplt("STG", 90, -85, &prj);

  /* SIN: orthographic. */
  prj.pv[1] = -0.3;
  prj.pv[2] =  0.5;
  printf(text2, "Orthographic/synthesis");
  printf("%12.5f%12.5f\n", prj.pv[1], prj.pv[2]);
  prjplt("SIN", 90, -90, &prj);

  /* ARC: zenithal/azimuthal equidistant. */
  printf(text1, "Zenithal/azimuthal equidistant");
  prjplt("ARC", 90, -90, &prj);

  /* ZPN: zenithal/azimuthal polynomial. */
  prj.pv[0] =  0.05000;
  prj.pv[1] =  0.95000;
  prj.pv[2] = -0.02500;
  prj.pv[3] = -0.15833;
  prj.pv[4] =  0.00208;
  prj.pv[5] =  0.00792;
  prj.pv[6] = -0.00007;
  prj.pv[7] = -0.00019;
  prj.pv[8] =  0.00000;
  prj.pv[9] =  0.00000;
  printf(text2, "Zenithal/azimuthal polynomial");
  printf("%12.5f%12.5f%12.5f%12.5f%12.5f\n",
    prj.pv[0], prj.pv[1], prj.pv[2], prj.pv[3], prj.pv[4]);
  printf("           %12.5f%12.5f%12.5f%12.5f%12.5f\n",
    prj.pv[5], prj.pv[6], prj.pv[7], prj.pv[8], prj.pv[9]);
  prjplt("ZPN", 90,  10, &prj);

  /* ZEA: zenithal/azimuthal equal area. */
  printf(text1, "Zenithal/azimuthal equal area");
  prjplt("ZEA", 90, -90, &prj);

  /* AIR: Airy's zenithal projection. */
  prj.pv[1] = 45.0;
  printf(text2, "Airy's zenithal");
  printf("%12.5f\n", prj.pv[1]);
  prjplt("AIR", 90, -85, &prj);

  /* CYP: cylindrical perspective. */
  prj.pv[1] = 3.0;
  prj.pv[2] = 0.8;
  printf(text2, "Cylindrical perspective");
  printf("%12.5f%12.5f\n", prj.pv[1], prj.pv[2]);
  prjplt("CYP", 90, -90, &prj);

  /* CEA: cylindrical equal area. */
  prj.pv[1] = 0.75;
  printf(text2, "Cylindrical equal area");
  printf("%12.5f\n", prj.pv[1]);
  prjplt("CEA", 90, -90, &prj);

  /* CAR: plate carree. */
  printf(text1, "Plate carree");
  prjplt("CAR", 90, -90, &prj);

  /* MER: Mercator's. */
  printf(text1, "Mercator's");
  prjplt("MER", 85, -85, &prj);

  /* SFL: Sanson-Flamsteed. */
  printf(text1, "Sanson-Flamsteed (global sinusoid)");
  prjplt("SFL", 90, -90, &prj);

  /* PAR: parabolic. */
  printf(text1, "Parabolic");
  prjplt("PAR", 90, -90, &prj);

  /* MOL: Mollweide's projection. */
  printf(text1, "Mollweide's");
  prjplt("MOL", 90, -90, &prj);

  /* AIT: Hammer-Aitoff. */
  printf(text1, "Hammer-Aitoff");
  prjplt("AIT", 90, -90, &prj);

  /* COP: conic perspective. */
  prj.pv[1] =  60.0;
  prj.pv[2] =  15.0;
  printf(text2, "Conic perspective");
  printf("%12.5f%12.5f\n", prj.pv[1], prj.pv[2]);
  prjplt("COP", 90, -25, &prj);

  /* COE: conic equal area. */
  prj.pv[1] =  60.0;
  prj.pv[2] = -15.0;
  printf(text2, "Conic equal area");
  printf("%12.5f%12.5f\n", prj.pv[1], prj.pv[2]);
  prjplt("COE", 90, -90, &prj);

  /* COD: conic equidistant. */
  prj.pv[1] = -60.0;
  prj.pv[2] =  15.0;
  printf(text2, "Conic equidistant");
  printf("%12.5f%12.5f\n", prj.pv[1], prj.pv[2]);
  prjplt("COD", 90, -90, &prj);

  /* COO: conic orthomorphic. */
  prj.pv[1] = -60.0;
  prj.pv[2] = -15.0;
  printf(text2, "Conic orthomorphic");
  printf("%12.5f%12.5f\n", prj.pv[1], prj.pv[2]);
  prjplt("COO", 85, -90, &prj);

  /* BON: Bonne's projection. */
  prj.pv[1] = 30.0;
  printf(text2, "Bonne's");
  printf("%12.5f\n", prj.pv[1]);
  prjplt("BON", 90, -90, &prj);

  /* PCO: polyconic. */
  printf(text1, "Polyconic");
  prjplt("PCO", 90, -90, &prj);

  /* TSC: tangential spherical cube. */
  printf(text1, "Tangential spherical cube");
  prjplt("TSC", 90, -90, &prj);

  /* CSC: COBE quadrilateralized spherical cube. */
  printf(text1, "COBE quadrilateralized spherical cube");
  prjplt("CSC", 90, -90, &prj);

  /* QSC: quadrilateralized spherical cube. */
  printf(text1, "Quadrilateralized spherical cube");
  prjplt("QSC", 90, -90, &prj);

  /* HPX: HEALPix projection. */
  prj.pv[1] = 4.0;
  prj.pv[2] = 3.0;
  printf(text1, "HEALPix");
  prjplt("HPX", 90, -90, &prj);

  /* XPH: HEALPix polar, aka "butterfly" projection. */
  printf(text1, "Butterfly");
  prjplt("XPH", 90, -90, &prj);

  cpgask(0);
  cpgend();

  return 0;
}
Example #15
0
int main()

{
  /* Set up a 2 x 2 lookup table. */
  const int M = 2;
  const int K[] = {K1, K2};
  const int map[] = {0, 1};
  const double crval[] = {0.0, 0.0};

  char text[80];
  int i, j, k, l, l1, l2, l3, lstep, m, stat[NP*NP], status;
  float array[NP][NP], clev[31], v0, v1, w;
  const float scl = 2.0f/(NP-1);
  float ltm[6];
  double x[NP][NP][2], world[NP][NP][2];
  struct tabprm tab;

  printf("Testing WCSLIB coordinate lookup table routines (ttab2.c)\n"
         "---------------------------------------------------------\n");

  /* List status return messages. */
  printf("\nList of tab status return values:\n");
  for (status = 1; status <= 5; status++) {
    printf("%4d: %s.\n", status, tab_errmsg[status]);
  }

  printf("\n");


  /* PGPLOT initialization. */
  strcpy(text, "/xwindow");
  cpgbeg(0, text, 1, 1);
  cpgvstd();
  cpgsch(0.7f);

  /* The viewport is slightly oversized. */
  cpgwnad(-0.65f, 1.65f, -0.65f, 1.65f);

  for (l = 0; l <= 30; l++) {
    clev[l] = 0.2f*(l-10);
  }

  ltm[0] = -scl*(1.0f + (NP-1)/4.0f);
  ltm[1] =  scl;
  ltm[2] =  0.0f;
  ltm[3] = -scl*(1.0f + (NP-1)/4.0f);
  ltm[4] =  0.0f;
  ltm[5] =  scl;


  /* Set up the lookup table. */
  tab.flag = -1;
  if ((status = tabini(1, M, K, &tab))) {
    printf("tabini ERROR %d: %s.\n", status, tab_errmsg[status]);
    return 1;
  }

  tab.M = M;
  for (m = 0; m < tab.M; m++) {
    tab.K[m] = K[m];
    tab.map[m] = map[m];
    tab.crval[m] = crval[m];

    for (k = 0; k < tab.K[m]; k++) {
      tab.index[m][k] = (double)k;
    }
  }

  /* Subdivide the interpolation element. */
  for (i = 0; i < NP; i++) {
    for (j = 0; j < NP; j++) {
      x[i][j][0] = j*(K1-1.0)*scl - 0.5 - crval[0];
      x[i][j][1] = i*(K2-1.0)*scl - 0.5 - crval[1];
    }
  }

  /* The first coordinate element is static. */
  tab.coord[0] = 0.0;
  tab.coord[2] = 0.0;
  tab.coord[4] = 0.0;
  tab.coord[6] = 0.0;

  /* (k1,k2) = (0,0). */
  tab.coord[1] = 0.0;

  /* The second coordinate element varies in three of the corners. */
  for (l3 = 0; l3 <= 100; l3 += 20) {
    /* (k1,k2) = (1,1). */
    tab.coord[7] = 0.01 * l3;

    for (l2 = 0; l2 <= 100; l2 += 20) {
      /* (k1,k2) = (0,1). */
      tab.coord[5] = 0.01 * l2;

      cpgpage();
      for (l1 = 0; l1 <= 100; l1 += 2) {
        /* (k1,k2) = (1,0). */
        tab.coord[3] = 0.01 * l1;

        /* Compute coordinates within the interpolation element. */
        tab.flag = 0;
        if ((status = tabx2s(&tab, NP*NP, 2, (double *)x, (double *)world,
                             stat))) {
          printf("tabx2s ERROR %d: %s.\n", status, tab_errmsg[status]);
        }

        /* Start a new plot. */
        cpgbbuf();
        cpgeras();
        cpgsci(1);
        cpgslw(3);
        cpgbox("BCNST", 0.0f, 0, "BCNSTV", 0.0f, 0);
        cpgmtxt("T", 0.7f, 0.5f, 0.5f, "-TAB coordinates:  "
          "linear interpolation / extrapolation in 2-D");

        /* Draw the boundary of the interpolation element in red. */
        cpgsci(2);
        cpgmove(-0.5f,  0.0f);
        cpgdraw( 1.5f,  0.0f);

        cpgmove( 1.0f, -0.5f);
        cpgdraw( 1.0f,  1.5f);

        cpgmove( 1.5f,  1.0f);
        cpgdraw(-0.5f,  1.0f);

        cpgmove( 0.0f,  1.5f);
        cpgdraw( 0.0f, -0.5f);

        /* Label the value of the coordinate element in each corner. */
        sprintf(text, "%.1f", tab.coord[1]);
        cpgtext(-0.09f, -0.05f, text);
        sprintf(text, "%.2f", tab.coord[3]);
        cpgtext( 1.02f, -0.05f, text);
        sprintf(text, "%.1f", tab.coord[5]);
        cpgtext(-0.13f,  1.02f, text);
        sprintf(text, "%.1f", tab.coord[7]);
        cpgtext( 1.02f,  1.02f, text);

        cpgsci(1);
        /* Contour labelling: bottom. */
        v0 = world[0][0][1];
        v1 = world[0][NP-1][1];
        if (v0 != v1) {
          lstep = (abs((int)((v1-v0)/0.2f)) < 10) ? 20 : 40;
          for (l = -200; l <= 300; l += lstep) {
            w = -0.5f + 2.0f * (l*0.01f - v0) / (v1 - v0);
            if (w < -0.5 || w > 1.5) continue;

            sprintf(text, "%4.1f", l*0.01f);
            cpgptxt(w+0.04f, -0.56f, 0.0f, 1.0f, text);
          }
        }

        /* Contour labelling: left. */
        v0 = world[0][0][1];
        v1 = world[NP-1][0][1];
        if (v0 != v1) {
          lstep = (abs((int)((v1-v0)/0.2f)) < 10) ? 20 : 40;
          for (l = -200; l <= 300; l += lstep) {
            w = -0.5f + 2.0f * (l*0.01f - v0) / (v1 - v0);
            if (w < -0.5 || w > 1.5) continue;

            sprintf(text, "%4.1f", l*0.01f);
            cpgptxt(-0.52f, w-0.02f, 0.0f, 1.0f, text);
          }
        }

        /* Contour labelling: right. */
        v0 = world[0][NP-1][1];
        v1 = world[NP-1][NP-1][1];
        if (v0 != v1) {
          lstep = (abs((int)((v1-v0)/0.2f)) < 10) ? 20 : 40;
          for (l = -200; l <= 300; l += lstep) {
            w = -0.5f + 2.0f * (l*0.01f - v0) / (v1 - v0);
            if (w < -0.5 || w > 1.5) continue;

            sprintf(text, "%.1f", l*0.01f);
            cpgptxt(1.52f, w-0.02f, 0.0f, 0.0f, text);
          }
        }

        /* Contour labelling: top. */
        v0 = world[NP-1][0][1];
        v1 = world[NP-1][NP-1][1];
        if (v0 != v1) {
          lstep = (abs((int)((v1-v0)/0.2f)) < 10) ? 20 : 40;
          for (l = -200; l <= 300; l += lstep) {
            w = -0.5f + 2.0f * (l*0.01f - v0) / (v1 - v0);
            if (w < -0.5 || w > 1.5) continue;

            sprintf(text, "%4.1f", l*0.01f);
            cpgptxt(w+0.04f, 1.52f, 0.0f, 1.0f, text);
          }
        }

        /* Draw contours for the second coordinate element. */
        for (i = 0; i < NP; i++) {
          for (j = 0; j < NP; j++) {
            array[i][j] = world[i][j][1];
          }
        }

        cpgsci(4);
        cpgslw(2);
        cpgcont(array[0], NP, NP, 1, NP, 1, NP, clev, 10, ltm);

        cpgsci(7);
        cpgcont(array[0], NP, NP, 1, NP, 1, NP, clev+10, 1, ltm);

        cpgsci(5);
        cpgcont(array[0], NP, NP, 1, NP, 1, NP, clev+11, 20, ltm);

        cpgebuf();
      }
    }
  }

  cpgend();

  tabfree(&tab);

  return 0;
}
Example #16
0
// Main code
int main()
{
  /**** Count to 10 in integers ****/

  // Declare integer for loop counting
  int i;

  // Loop from 0 to 10, printing at each step
  for(i=0; i<10; i++)
  {
    printf("i= %d\n", i);
  }

  /**** Plot a function y=f(x) ****/

  // Declare arrays of N real numbers
  float ax[N]; // x
  float ay[N]; // y

  float aylow[N];  // lower error in y
  float ayhigh[N]; // upper error in y

  // Set minimum and maximum for x
  float xmin = 0.0;
  float xmax = 10.0;

  // Assigning ax with N values for x between xmin and xmax
  for(i=0;i<N;i++)
  {
    ax[i] = xmin + (xmax-xmin)*(float)i/(float)(N-1);
  }

  // Fill ay using function fy
  for(i=0;i<N;i++)
  {
    ay[i] = fy(ax[i]);
  }

  // Fill aylow and ayhigh using sqrt(y) as the error
  for(i=0;i<N;i++)
  {
    aylow[i]  = ay[i] - sqrt(ay[i]);
    ayhigh[i] = ay[i] + sqrt(ay[i]);
  }

  /**** Use pgplot to plot this function ****/

  // cpgbeg starts a plotting page, in this case with 2x1 panels
  cpgbeg(0,"?",2,1);

  // sets colour: 1-black, 2-red, 3-green, 4-blue
  cpgsci(1);

  // sets line style: 1-solid, 2-dashed, 3-dot-dashed, 4-dotted
  cpgsls(1);

  // sets charachter height, larger number = bigger
  cpgsch(2.);

  // cpgpage() moves to the next panel
  cpgpage();

  // sets the axes limits in the panel
  cpgswin(xmin,xmax,0.,100.);

  // draw the axes
  cpgbox("BCNST", 0.0, 0, "BCNST", 0.0, 0);

  // label the bottom axis
  cpgmtxt("B",2.,.5,.5,"x");
  // label the left axis
  cpgmtxt("L",2.5,.5,.5,"f");

  // connect N points in ax and ay with a line
  cpgline(N,ax,ay);

  // cpgpage() moves to the next panel
  cpgpage();

  // sets the axes limits in the panel
  cpgswin(xmin,xmax,0.,100.);

  // draw the axes
  cpgbox("BCNST", 0.0, 0, "BCNST", 0.0, 0);

  // label the bottom axis
  cpgmtxt("B",2.,.5,.5,"x");
  // label the left axis
  cpgmtxt("L",2.5,.5,.5,"f");

  // draw N points in ax and ay
  //   17 - filled circles, 16 - filled squares, 13 - filled triangles
  cpgpt(N,ax,ay,17);

  // draw y error bars on the points
  cpgerry(N,ax,aylow,ayhigh,1.0);

  // close all pgplot applications
  cpgend();

  // end program
  return 0;
}
Example #17
0
int main(int argc, char **argv)

{
  char alt = '\0', *header, idents[3][80], *infile, keyword[16], nlcprm[1],
       opt[2], pgdev[16];
  int  c0[] = {-1, -1, -1, -1, -1, -1, -1};
  int  alts[27], gcode[2], hdunum = 1, hdutype, i, ic, naxes, naxis[2],
       nkeyrec, nreject, nwcs, stat[NWCSFIX], status;
  float  blc[2], trc[2];
  double cache[257][4], grid1[3], grid2[3], nldprm[1];
  struct wcsprm *wcs;
  nlfunc_t pgwcsl_;
  fitsfile *fptr;


  /* Parse options. */
  strcpy(pgdev, "/XWINDOW");
  for (i = 1; i < argc && argv[i][0] == '-'; i++) {
    if (!argv[i][1]) break;

    switch (argv[i][1]) {
    case 'a':
      alt = toupper(argv[i][2]);
      break;

    case 'd':
      if (argv[i][2] == '?') {
        cpgldev();
        return 0;
      }

      if (argv[i][2] == '/') {
        strncpy(pgdev+1, argv[i]+3, 15);
      } else {
        strncpy(pgdev+1, argv[i]+2, 15);
      }
      break;

    case 'h':
      hdunum = atoi(argv[i]+2);
      break;

    default:
      fprintf(stderr, "%s", usage);
      return 1;
    }
  }

  if (i < argc) {
    infile = argv[i++];

    if (i < argc) {
      fprintf(stderr, "%s", usage);
      return 1;
    }
  } else {
    infile = "-";
  }

  /* Check accessibility of the input file. */
  if (strcmp(infile, "-") && access(infile, R_OK) == -1) {
    printf("wcsgrid: Cannot access %s.\n", infile);
    return 1;
  }


  /* Open the FITS file and move to the required HDU. */
  status = 0;
  if (fits_open_file(&fptr, infile, READONLY, &status)) goto fitserr;
  if (fits_movabs_hdu(fptr, hdunum, &hdutype, &status)) goto fitserr;
  if (hdutype != IMAGE_HDU) {
    fprintf(stderr, "ERROR, HDU number %d does not contain an image array.\n",
      hdunum);
    return 1;
  }

  /* Check that we have at least two image axes. */
  if (fits_read_key(fptr, TINT, "NAXIS",  &naxes, NULL, &status)) {
    goto fitserr;
  }

  if (naxes < 2) {
    fprintf(stderr, "ERROR, HDU number %d does not contain a 2-D image.\n",
      hdunum);
    return 1;
  } else if (naxes > 2) {
    printf("HDU number %d contains a %d-D image array.\n", hdunum, naxes);
  }

  /* Read in the FITS header, excluding COMMENT and HISTORY keyrecords. */
  if (fits_hdr2str(fptr, 1, NULL, 0, &header, &nkeyrec, &status)) {
    goto fitserr;
  }


  /* Interpret the WCS keywords. */
  if ((status = wcspih(header, nkeyrec, WCSHDR_all, -3, &nreject, &nwcs,
                       &wcs))) {
    fprintf(stderr, "wcspih ERROR %d: %s.\n", status, wcshdr_errmsg[status]);
    return 1;
  }
  free(header);

  /* Read -TAB arrays from the binary table extension (if necessary). */
  if (fits_read_wcstab(fptr, wcs->nwtb, (wtbarr *)wcs->wtb, &status)) {
    goto fitserr;
  }

  /* Translate non-standard WCS keyvalues. */
  if ((status = wcsfix(7, 0, wcs, stat))) {
    status = 0;
    for (i = 0; i < NWCSFIX; i++) {
      if (stat[i] > 0) {
         fprintf(stderr, "wcsfix ERROR %d: %s.\n", stat[i],
                 wcsfix_errmsg[stat[i]]);

        /* Ignore problems with CDi_ja and DATE-OBS. */
        if (!(i == CDFIX || i == DATFIX)) status = 1;
      }
    }

    if (status) return 1;
  }

  /* Sort out alternates. */
  if (alt) {
    wcsidx(nwcs, &wcs, alts);

    if (alt == ' ') {
      if (alts[0] == -1) {
        fprintf(stderr, "WARNING, no primary coordinate representation, "
                        "doing all.\n");
        alt = '\0';
      }

    } else if (alt < 'A' || alt > 'Z') {
      fprintf(stderr, "WARNING, alternate specifier \"%c\" is invalid, "
                      "doing all.\n", alt);
      alt = '\0';

    } else {
      if (alts[alt - 'A' + 1] == -1) {
        fprintf(stderr, "WARNING, no alternate coordinate representation "
                        "\"%c\", doing all.\n", alt);
        alt = '\0';
      }
    }
  }

  /* Get image dimensions from the header. */
  sprintf(keyword, "NAXIS%d", wcs->lng + 1);
  fits_read_key(fptr, TINT, "NAXIS1", naxis,   NULL, &status);
  sprintf(keyword, "NAXIS%d", wcs->lat + 1);
  fits_read_key(fptr, TINT, "NAXIS2", naxis+1, NULL, &status);

  if ((naxis[0] < 2) || (naxis[1] < 2)) {
    fprintf(stderr, "ERROR, HDU number %d contains degenerate image axes.\n",
      hdunum);
    return 1;
  }

  fits_close_file(fptr, &status);


  /* Plot setup. */
  blc[0] = 0.5f;
  blc[1] = 0.5f;
  trc[0] = naxis[0] + 0.5f;
  trc[1] = naxis[1] + 0.5f;

  if (cpgbeg(0, pgdev, 1, 1) != 1) {
    fprintf(stderr, "ERROR, failed to open PGPLOT device %s.\n", pgdev);
    return 1;
  }
  cpgvstd();

  cpgwnad(blc[0], trc[0], blc[0], trc[1]);
  cpgask(1);
  cpgpage();

  /* Compact lettering. */
  cpgsch(0.8f);

  /* Draw full grid lines. */
  gcode[0] = 2;
  gcode[1] = 2;
  grid1[0] =    0.0;
  grid2[0] =    0.0;

  /* These are for the projection boundary. */
  grid1[1] = -180.0;
  grid1[2] =  180.0;
  grid2[1] =  -90.0;
  grid2[2] =   90.0;

  cpgsci(1);

  for (i = 0; i < nwcs; i++) {
    if (alt && (wcs+i)->alt[0] != alt) {
      continue;
    }

    if ((status = wcsset(wcs+i))) {
      fprintf(stderr, "wcsset ERROR %d: %s.\n", status, wcs_errmsg[status]);
      continue;
    }

    /* Draw the frame. */
    cpgbox("BC", 0.0f, 0, "BC", 0.0f, 0);

    /* Axis labels; use CNAMEia in preference to CTYPEia. */
    if ((wcs+i)->cname[0][0]) {
      strcpy(idents[0], (wcs+i)->cname[0]);
    } else {
      strcpy(idents[0], (wcs+i)->ctype[0]);
    }

    if ((wcs+i)->cname[1][0]) {
      strcpy(idents[1], (wcs+i)->cname[1]);
    } else {
      strcpy(idents[1], (wcs+i)->ctype[1]);
    }

    /* Title; use WCSNAME. */
    strcpy(idents[2], (wcs+i)->wcsname);
    if (strlen(idents[2])) {
      printf("\n%s\n", idents[2]);
    }

    /* Formatting control for celestial coordinates. */
    if (strncmp((wcs+i)->ctype[0], "RA", 2) == 0) {
      /* Right ascension in HMS, declination in DMS. */
      opt[0] = 'G';
      opt[1] = 'E';
    } else {
      /* Other angles in decimal degrees. */
      opt[0] = 'A';
      opt[1] = 'B';
    }

    /* Draw the celestial grid.  The grid density is set for each world */
    /* coordinate by specifying LABDEN = 1224. */
    ic = -1;
    cpgsbox(blc, trc, idents, opt, 0, 1224, c0, gcode, 0.0, 0, grid1, 0,
      grid2, 0, pgwcsl_, 1, WCSLEN, 1, nlcprm, (int *)(wcs+i), nldprm, 256,
      &ic, cache, &status);

    /* Delimit the projection boundary. */
    if ((wcs+i)->cel.prj.category != ZENITHAL) {
      /* Reset to the native coordinate graticule. */
      (wcs+i)->crval[0] = (wcs+i)->cel.prj.phi0;
      (wcs+i)->crval[1] = (wcs+i)->cel.prj.theta0;
      (wcs+i)->lonpole  = 999.0;
      (wcs+i)->latpole  = 999.0;
      status = wcsset(wcs+i);

      ic = -1;
      cpgsbox(blc, trc, idents, opt, -1, 0, c0, gcode, 0.0, 2, grid1, 2,
        grid2, 0, pgwcsl_, 1, WCSLEN, 1, nlcprm, (int *)(wcs+i), nldprm, 256,
        &ic, cache, &status);
    }

    cpgpage();
  }

  status = wcsvfree(&nwcs, &wcs);

  return 0;

fitserr:
  fits_report_error(stderr, status);
  fits_close_file(fptr, &status);
  return 1;
}
Example #18
0
int main(int argc, char *argv[])
{
	fitsfile* fptr;
	//char filename[] = "guppi_56590_B1133+16_0003_0001.fits";
	char filename[] = "~/pulsar_data/B0329.fits";
	int status = 0;
	float realDm = 26.8;
	double psrFreq = 1.399541539;
	int i,j; //for loop
	int sampNum;


	fits_open_file(&fptr,filename,READONLY,&status);
	
	//初始化fits文件信息
	struct Fitsinfo* fi = (struct Fitsinfo*)malloc(sizeof(struct Fitsinfo));
	initFitsInfo(fptr,fi,realDm,&status);
	sampNum = fi->nSBLK*fi->nROW;
	//初始化保存所有流量数据的二维数组
	/*
	unsigned char** ptr = (unsigned char**)malloc(fi->nROW*fi->nSBLK*sizeof(unsigned char*));
	for (i=0; i<fi->nROW*fi->nSBLK; i++) {
		ptr[i] = (unsigned char*)malloc(fi->nCHAN*sizeof(unsigned char));
	}
	initTotalData(fptr,fi,ptr,&status);
	*/

	//初始化合适的频道
	unsigned char** ptr = (unsigned char**)malloc(fi->nROW*fi->nSBLK*sizeof(unsigned char*));
	for (i=0; i<fi->nROW*fi->nSBLK; i++) {
		ptr[i] = (unsigned char*)malloc((fi->highF-fi->lowF+1)*sizeof(unsigned char));
	}
	initSuitData(fptr,fi,ptr,&status);
	//给需要处理的某两个通道分配空间	
    	struct FreqData* fdm = (struct FreqData*)malloc(sizeof(struct FreqData));
	fdm->data = (int*)malloc(sizeof(int)*fi->nSBLK*fi->nROW);
	struct FreqData** fd = (struct FreqData**)malloc(DMNUM*sizeof(struct FreqData*));	
	for (i=0; i<DMNUM; i++) {
		fd[i] = (struct FreqData*)malloc(sizeof(struct FreqData));
		fd[i]->data = (int*)malloc(sizeof(int)*fi->nSBLK*fi->nROW);
		//addSuitFreqData(fptr,fd[i],fdm,ptr,fi->dmArr[i],fi,&status);
		addSuitFreqDataWithZeroDm(fptr,fd[i],fdm,ptr,fi->dmArr[i],fi,&status);
	}
	for (i=0; i<fi->nROW*fi->nSBLK; i++) {
		free(ptr[i]);
	}
	free(ptr);

	/* draw fd[DMNUM/2]->data */
	/* draw fd[DMNUM/2]->data */
	if (cpgbeg(0, "/xs", 1, 1) != 1) {
		return EXIT_FAILURE;
	}
	float ns = fi->nROW * fi->nSBLK;
	float *x_coor, *data_adm;
	x_coor = (float *)malloc(sizeof(float) * fi->nROW * fi->nSBLK);
	data_adm = (float *)malloc(sizeof(float) * ns);
	for (i = 0; i < fi->nROW * fi->nSBLK; i++) {
		*(x_coor + i) = i;
		*(data_adm  + i) = (float)fd[DMNUM/2]->data[i];
	}
	
	cpgpage();
	cpgenv(0.0, fi->nROW * fi->nSBLK, -5000.0f, 5000.0f, 0, 1);
	
	cpgline(ns, x_coor, data_adm);
	cpgbbuf();
	cpgend();
	return EXIT_SUCCESS;
	
	float aveData[20000] = {0};
	writeIntData("26.8.dat",26.8,fd[DMNUM/2]->data,fi->nSBLK*fi->nROW);
	calcAveArr(aveData,fd[DMNUM/2]->data,2000000,100);
	writeFloatData("ave26.8.dat",26.8,aveData,20000);
	int foldData[20000] = {0};
	fold(foldData,fd[DMNUM/2]->data,fi->tBIN,psrFreq,fi->nSBLK*fi->nROW);

	writeHistogramData(fd,fi);
	
	

	fits_close_file(fptr,&status);

}
Example #19
0
int main()

{
  /* Set up the lookup table. */
  const int M  = 2;
  const int K[] = {K1, K2};
  const int map[] = {0, 1};
  const double crval[] = {135.0, 95.0};

  char text[80];
  int ci, i, ilat, ilng, j, k, m, stat[K2][K1], status;
  float xr[361], yr[361];
  double *dp, world[361][2], x[K1], xy[361][2], y[K2];
  struct tabprm tab;
  struct prjprm prj;

  printf(
    "Testing WCSLIB inverse coordinate lookup table routines (ttab3.c)\n"
    "-----------------------------------------------------------------\n");

  /* List status return messages. */
  printf("\nList of tab status return values:\n");
  for (status = 1; status <= 5; status++) {
    printf("%4d: %s.\n", status, tab_errmsg[status]);
  }

  printf("\n");


  /* PGPLOT initialization. */
  strcpy(text, "/xwindow");
  cpgbeg(0, text, 1, 1);
  cpgvstd();
  cpgsch(0.7f);
  cpgwnad(-135.0f, 135.0f, -95.0f, 140.0f);
  cpgbox("BC", 0.0f, 0, "BC", 0.0f, 0);

  cpgscr(0, 0.00f, 0.00f, 0.00f);
  cpgscr(1, 1.00f, 1.00f, 0.00f);
  cpgscr(2, 1.00f, 1.00f, 1.00f);
  cpgscr(3, 0.50f, 0.50f, 0.80f);
  cpgscr(4, 0.80f, 0.50f, 0.50f);
  cpgscr(5, 0.80f, 0.80f, 0.80f);
  cpgscr(6, 0.50f, 0.50f, 0.80f);
  cpgscr(7, 0.80f, 0.50f, 0.50f);
  cpgscr(8, 0.30f, 0.50f, 0.30f);


  /* Set up the lookup table. */
  tab.flag = -1;
  if ((status = tabini(1, M, K, &tab))) {
    printf("tabini ERROR %d: %s.\n", status, tab_errmsg[status]);
    return 1;
  }

  tab.M = M;
  for (m = 0; m < tab.M; m++) {
    tab.K[m] = K[m];
    tab.map[m] = map[m];
    tab.crval[m] = crval[m];

    for (k = 0; k < tab.K[m]; k++) {
      tab.index[m][k] = (double)k;
    }
  }

  /* Set up the lookup table to approximate Bonne's projection. */
  for (i = 0; i < K1; i++) {
    x[i] = 135 - i;
  }
  for (j = 0; j < K2; j++) {
    y[j] = j - 95;
  }

  prjini(&prj);
  prj.pv[1] = 35.0;
  status = bonx2s(&prj, K1, K2, 1, 2, x, y, tab.coord, tab.coord+1,
                  (int *)stat);

  dp = tab.coord;
  for (j = 0; j < K2; j++) {
    for (i = 0; i < K1; i++) {
      if (stat[j][i]) {
        *dp = 999.0;
        *(dp+1) = 999.0;
      }
      dp += 2;
    }
  }


  /* Draw meridians. */
  ci = 1;
  for (ilng = -180; ilng <= 180; ilng += 15) {
    if (++ci > 7) ci = 2;
    cpgsci(ilng?ci:1);

    for (j = 0, ilat = -90; ilat <= 90; ilat++, j++) {
      world[j][0] = (double)ilng;
      world[j][1] = (double)ilat;
    }

    /* A fudge to account for the singularity at the poles. */
    world[0][0] = 0.0;
    world[180][0] = 0.0;

    status = tabs2x(&tab, 181, 2, (double *)world, (double *)xy,
                    (int *)stat);

    k = 0;
    for (j = 0; j < 181; j++) {
      if (stat[0][j]) {
        if (k > 1) cpgline(k, xr, yr);
        k = 0;
        continue;
      }

      xr[k] = xy[j][0];
      yr[k] = xy[j][1];
      k++;
    }

    cpgline(k, xr, yr);
  }


  /* Draw parallels. */
  ci = 1;
  for (ilat = -75; ilat <= 75; ilat += 15) {
    if (++ci > 7) ci = 2;
    cpgsci(ilat?ci:1);

    for (j = 0, ilng = -180; ilng <= 180; ilng++, j++) {
      world[j][0] = (double)ilng;
      world[j][1] = (double)ilat;
    }

    status = tabs2x(&tab, 361, 2, (double *)world, (double *)xy,
                    (int *)stat);

    k = 0;
    for (j = 0; j < 361; j++) {
      if (stat[0][j]) {
        if (k > 1) cpgline(k, xr, yr);
        k = 0;
        continue;
      }

      xr[k] = xy[j][0];
      yr[k] = xy[j][1];
      k++;
    }

    cpgline(k, xr, yr);
  }

  cpgend();

  return 0;
}
Example #20
0
void main()	//main code

{	
	printf("\nRUNGE-KUTTA METHOD\n\nR		M		Rho\n");	//printing titles for values displayed
	
	double c = 10.0;	//the parameter rho(c)
	int n;			//the integer steps, n
	
	//declare arrays
	float x[N];
	float y[N];
	float z[N];
	
	//r,m,p as the radius, mass and density
	double r,m,p;
	
	//declare initial conditons for arrays
	x[0] = h;				//first array is for r=h
	y[0] = (h*h*h/3)*c;			//initial conditon for scaled mass (m)
	z[0] = c*(1-((h*h*c)/(6*gamma(c))));	//initial conditon for rho
	
	//for loop for n=0,1,...,200
	for(n=0;n<N;n++)
	{
		//declared how x(n+1) relates to x(n), y(n+1) relates to y(n), z(n+1) relates to z(n)
		x[n+1] = x[n]+h;
		y[n+1] = y[n]+(h/6)*(M(x[n],y[n],z[n])+2*M2(x[n],y[n],z[n])+2*M3(x[n],y[n],z[n])+M4(x[n],y[n],z[n]));
		z[n+1] = z[n]+(h/6)*(rho(x[n],y[n],z[n])+2*rho2(x[n],y[n],z[n])+2*rho3(x[n],y[n],z[n])+rho4(x[n],y[n],z[n]));

		if(isnan(z[n+1]))
		{
			break;
		}
		
		//r,m,p will be declared in pg-plot
		r = x[n+1];
		m = y[n+1];
		p = z[n+1];
		
		printf("%.2e	%.2e	%.2e\n",x[n+1],y[n+1],z[n+1]);	//printed values for x and y respectively
	}
	
	//Use pg-plot to plot mass and density

  // cpgbeg starts a plotting page, in this case with 2x1 panels
  cpgbeg(0,"?",2,1);

  // sets colour: 1-black, 2-red, 3-green, 4-blue
  cpgsci(1);

  // sets line style: 1-solid, 2-dashed, 3-dot-dashed, 4-dotted
  cpgsls(1);

  // sets charachter height, larger number = bigger
  cpgsch(1.);

  // cpgpage() moves to the next panel
  cpgpage();

  // sets the axes limits in the panel
  cpgswin(0,r,0,m);

  // draw the axes
  cpgbox("BCNST", 0.0, 0, "BCNST", 0.0, 0);

  // label the bottom axis
  cpgmtxt("B",2.,.5,.5,"radius");
  // label the left axis
  cpgmtxt("L",2.5,.5,.5,"saclaed mass");

  // connect N points in ax and ay with a line
  cpgline(n,x,y);

  // cpgpage() moves to the next panel
  cpgpage();

  // sets the axes limits in the panel
  cpgswin(0,r,0,c);

  // draw the axes
  cpgbox("BCNST", 0.0, 0, "BCNST", 0.0, 0);

  // label the bottom axis
  cpgmtxt("B",2.,.5,.5,"radius");
  // label the left axis
  cpgmtxt("L",2.5,.5,.5,"density");

  // connect N points in ax and ay with a line
  cpgline(n,x,z);
  
  // close all pgplot applications
  cpgend();

  // end program
  return;
}
Example #21
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;
}
Example #22
0
int plot(float ***u, const int nx, const int ny) {

#ifdef PGPLOT
	const int ng=2;
	double xl, xr, yl, yr, dx, dy;
	float  denscontours[NCONTOURS], prescontours[NCONTOURS];
	float *dens, *pres;
	double maxd=-1e19, mind=+1e-19;
	double maxp=-1e19, minp=+1e-19;
	static int called = 0;
	int i, j, count;	
	float tr[6] = {0.,0.,0.,0.,0.,0.};
	
	xl = 0.; xr = nx-2*ng-1;
	yl = 0.; yr = ny-2*ng-1;
    dx = 1.; dy = 1.;

	dens = (float *)malloc((nx-2*ng)*(ny-2*ng)*sizeof(float));
	pres = (float *)malloc((nx-2*ng)*(ny-2*ng)*sizeof(float));
	count = 0;
	for (j=ny-ng; j>ng; j--) {
		for (i=ng; i<nx-ng; i++) {
			dens[count] = u[j][i][IDENS];
            float vx = u[j][i][IMOMX]/dens[count];
            float vy = u[j][i][IMOMY]/dens[count];
			pres[count] = (u[j][i][IENER] - 0.5*(vx*vx+vy*vy)*dens[count]);
			if (dens[count] > maxd) maxd = dens[count];
			if (dens[count] < mind) mind = dens[count];
			if (pres[count] > maxp) maxp = pres[count];
			if (pres[count] < minp) minp = pres[count];
			count++;
		}
	}
	
	tr[0] = xl; tr[3] = yl;
	tr[1] = dx; tr[5] = dy;

	for (i=0; i<NCONTOURS; i++) {
		denscontours[i] = mind + (i+1)*(maxd-mind)/(NCONTOURS+1);
		prescontours[i] = minp + (i+1)*(maxp-minp)/(NCONTOURS+1);
	}


	if (!called) {
		cpgbeg(0, "/XWINDOW", 1, 1);
		called = 1;
		cpgask(0);
	}
	cpgenv(xl, xr, yl, yr, 1, 1);

	cpgsci(2);
	cpgcont(dens, nx-2*ng, ny-2*ng, 1, nx-2*ng, 1, ny-2*ng, denscontours, NCONTOURS, tr);
	if (minp != maxp) {
		cpgsci(3);
	    cpgcont(pres, nx-2*ng, ny-2*ng, 1, nx-2*ng, 1, ny-2*ng, prescontours, NCONTOURS, tr);
	}
	cpgsci(1);
	
	free(dens); free(pres);
#endif
	return 0;
}
Example #23
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();
}
Example #24
0
int main()

{
  char infile[] = "pih.fits";
  char devtyp[16], idents[3][80], nlcprm[1], opt[2];
  int  c0[] = {-1, -1, -1, -1, -1, -1, -1};
  int  i, ic, gcode[2], naxis[2], nkeyrec, nreject, nwcs, relax, status;
  float  blc[2], trc[2];
  double cache[257][4], grid1[1], grid2[1], nldprm[1];
  struct wcsprm *wcs;
  nlfunc_t pgwcsl_;
#if defined HAVE_CFITSIO && defined DO_CFITSIO
  char *header;
  fitsfile *fptr;
#else
  char keyrec[81], header[28801];
  int  gotend, j, k;
  FILE *fptr;
#endif


  /* Set line buffering in case stdout is redirected to a file, otherwise
   * stdout and stderr messages will be jumbled (stderr is unbuffered). */
  setvbuf(stdout, NULL, _IOLBF, 0);

  printf("Testing WCSLIB parser for FITS image headers (tpih2.c)\n"
         "------------------------------------------------------\n\n");

  /* Read in the FITS header, excluding COMMENT and HISTORY keyrecords. */
#if defined HAVE_CFITSIO && defined DO_CFITSIO
  status = 0;

  if (fits_open_file(&fptr, infile, READONLY, &status)) {
    fits_report_error(stderr, status);
    return 1;
  }

  if (fits_hdr2str(fptr, 1, NULL, 0, &header, &nkeyrec, &status)) {
    fits_report_error(stderr, status);
    return 1;
  }

  fits_close_file(fptr, &status);
#else
  if ((fptr = fopen(infile, "r")) == 0x0) {
    printf("ERROR opening %s\n", infile);
    return 1;
  }

  k = 0;
  nkeyrec = 0;
  gotend = 0;
  for (j = 0; j < 10; j++) {
    for (i = 0; i < 36; i++) {
      if (fgets(keyrec, 81, fptr) == 0) {
        break;
      }

      if (strncmp(keyrec, "        ", 8) == 0) continue;
      if (strncmp(keyrec, "COMMENT ", 8) == 0) continue;
      if (strncmp(keyrec, "HISTORY ", 8) == 0) continue;

      strncpy(header+k, keyrec, 80);
      k += 80;
      nkeyrec++;

      if (strncmp(keyrec, "END     ", 8) == 0) {
        /* An END keyrecord was read, but read the rest of the block. */
        gotend = 1;
      }
    }

    if (gotend) break;
  }
  fclose(fptr);
#endif

  fprintf(stderr, "Found %d non-comment header keyrecords.\n", nkeyrec);

  relax = WCSHDR_all;
  if ((status = wcspih(header, nkeyrec, relax, 2, &nreject, &nwcs, &wcs))) {
    fprintf(stderr, "wcspih ERROR %d: %s.\n", status, wcs_errmsg[status]);
  }
#if defined HAVE_CFITSIO && defined DO_CFITSIO
  free(header);
#endif

  /* Plot setup. */
  naxis[0] = 1024;
  naxis[1] = 1024;

  blc[0] = 0.5f;
  blc[1] = 0.5f;
  trc[0] = naxis[0] + 0.5f;
  trc[1] = naxis[1] + 0.5f;

  strcpy(devtyp, "/XWINDOW");
  cpgbeg(0, devtyp, 1, 1);
  cpgvstd();

  cpgwnad(0.0f, 1.0f, 0.0f, 1.0f);
  cpgask(1);
  cpgpage();

  /* Annotation. */
  strcpy(idents[0], "Right ascension");
  strcpy(idents[1], "Declination");

  opt[0] = 'G';
  opt[1] = 'E';

  /* Compact lettering. */
  cpgsch(0.8f);

  /* Draw full grid lines. */
  cpgsci(1);
  gcode[0] = 2;
  gcode[1] = 2;
  grid1[0] = 0.0;
  grid2[0] = 0.0;

  for (i = 0; i < nwcs; i++) {
    if ((status = wcsset(wcs+i))) {
      fprintf(stderr, "wcsset ERROR %d: %s.\n", status, wcs_errmsg[status]);
      continue;
    }

    /* Get WCSNAME out of the wcsprm struct. */
    strcpy(idents[2], (wcs+i)->wcsname);
    printf("\n%s\n", idents[2]);

    /* Draw the celestial grid.  The grid density is set for each world */
    /* coordinate by specifying LABDEN = 1224. */
    ic = -1;
    cpgsbox(blc, trc, idents, opt, 0, 1224, c0, gcode, 0.0, 0, grid1, 0,
      grid2, 0, pgwcsl_, 1, WCSLEN, 1, nlcprm, (int *)(wcs+i), nldprm, 256,
      &ic, cache, &status);

    /* Draw the frame. */
    cpgbox("BC", 0.0f, 0, "BC", 0.0f, 0);

    cpgpage();
  }

  status = wcsvfree(&nwcs, &wcs);

  return 0;
}
Example #25
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;
}