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

  pg_id = cpgopen("/XSERVE");
  cpgpap(8.0, 0.8);
  cpgask(0);
  cpgpage();
  cpgslct(pg_id);
  cpgsci(3);
  cpgeras();
  cpgsvp(0.15f, 0.95f, 0.2f, 0.8f);
  cpgupdt();
  cpgsch(2.0);
  cpgswin(0, read_count, -0.1f, 0.1f);
  cpgbox("BC1NST",0.0,0,"BCNST",0.0,0);
  cpglab("Time [samples]", "Voltage [volts]", "Antenna Measurement Receiver");
  cpgmove(samp, voltarray[0]);
  for (samp=2; samp<read_count; samp++)
	 {
	   cpgdraw(samp, voltarray[samp]);
	 }
  return 0;
}
Example #2
0
void wipmove(float x, float y)
{
      cpgmove(x, y);
      (void)wipsetvar("cx", (double)x);
      (void)wipsetvar("cy", (double)y);
      return;
}
Example #3
0
int plot_fit_curve(float *a, int ncoeff, float tmin, float tmax)
{
  int i,j;            /* Looping variables */
  int nstep=500;      /* Number of steps used to compute curve */
  float xtmp,ytmp;    /* Values of x,y used in constructing the curve */
  float *polyx=NULL;  /* Polynomial in x */

  cpgsci(2);
  cpgslw(5);

  /*
   * Allocate memory for container for polynomial values
   */

  if(!(polyx = new_array(ncoeff,1))) {
    fprintf(stderr,"ERROR: plot_fit_curve\n");
    return 1;
  }

  /*
   * Loop through range of x values in step sizes determined by nstep.
   * At each value of x, compute the value of y by first calling poly
   *  to compute the values of the various powers of x at that step, and
   *  then multiplying by the coefficients contained in a.
   */

  for(i=0; i<nstep; i++) {

    /*
     * Compute the values of x and y at this step
     */

    xtmp = tmin + i*(tmax - tmin)/(1.0 * nstep);
    sinpoly(xtmp,polyx-1,ncoeff);
    ytmp = 0;
    for(j=0; j<ncoeff; j++)
      ytmp += a[j] * polyx[j];

    /*
     * Now connect this point to the previous one with a cpgdraw call
     */

    if(i == 0)
      cpgmove(xtmp,ytmp);
    else
      cpgdraw(xtmp,ytmp);
  }

  /*
   * Clean up and exit
   */

  cpgslw(1);
  cpgsci(1);
  polyx = del_array(polyx);

  return 0;
}
void aitoffGrid(void) {

  int i,j;
  double phi[MM], lam[MM], x[MM], y[MM];
  double rr, dd;

  cpgsci(DARKGRAY);
  cpgslw(1);

  for(i=0; i<MM; i++) phi[i] = i*M_PI/(double)(MM-1) - M_PI/2.0;

  // make meridians for each ra in (-180,180)
  for(i=0; i<NM; i++) {
    rr = i*2.0*M_PI/(double)(NM-1) - M_PI;

    // steps in dec on (-90,90)
    for(j=0; j<MM; j++) {
      project(rr,phi[j],&x[j],&y[j]);
    }
    for(j=1; j<MM; j++) {
      cpgmove(x[j-1],y[j-1]);
      cpgdraw(x[j],y[j]);
    }
  }

  // make parallels
  // steps in dec on (-90,90)
  for(i=0; i<MM; i++) phi[i] *= 2.0;
  for(i=0; i<NP; i++) {
    dd = i*M_PI/(double)(NP-1) - M_PI/2.0;

    // steps in RA from (-180,180)
    for(j=0; j<MM; j++) {
      project(phi[j],dd,&x[j],&y[j]);
    }
    for(j=1; j<MM; j++) {
      cpgmove(x[j-1],y[j-1]);
      cpgdraw(x[j],y[j]);
    }
  }

  cpgsci(1);
  cpgslw(1);

}
Example #5
0
void mark(g_ctl * ctl, float x, char *c, int color)
{
	int oldcolor;
	cpgqci(&oldcolor);

	cpgsci(color);
	cpgmove(x, ctl->ymin + ctl->h * 0.05);
	cpgdraw(x, ctl->ymax - ctl->h * 0.05);
	
	
	cpgptxt(x, ctl->ymin + ctl->h * 0.1, 0.0, -0.05, c);
	cpgsci(oldcolor);
}
Example #6
0
static void plot_harmonics(double rr, int zoomlevel, fftpart * fp)
{
   int ii, hh;
   double offsetf;
   char label[20];
   fftview *harmview;

   cpgsubp(4, 4);
   for (ii = 0, hh = 2; ii < 8; ii++, hh++) {
      cpgpanl(ii % 4 + 1, ii / 4 + 1);
      harmview = get_harmonic(hh * rr, zoomlevel, fp);
      if (harmview != NULL) {
         offsetf = plot_fftview(harmview, 0.0, 2.0, hh * rr, 2);
         snprintf(label, 20, "Harmonic %d", hh);
         cpgsave();
         cpgsch(2.0);
         cpgmtxt("T", -1.8, 0.05, 0.0, label);
         cpgunsa();
         free(harmview);
      }
   }
   for (ii = 8, hh = 2; ii < 16; ii++, hh++) {
      cpgpanl(ii % 4 + 1, ii / 4 + 1);
      harmview = get_harmonic(rr / (double) hh, zoomlevel, fp);
      if (harmview != NULL) {
         offsetf = plot_fftview(harmview, 0.0, 2.0, rr / (double) hh, 2);
         snprintf(label, 20, "Harmonic 1/%d", hh);
         cpgsave();
         cpgsch(2.0);
         cpgmtxt("T", -1.8, 0.05, 0.0, label);
         cpgunsa();
         free(harmview);
      }
   }
   cpgsubp(1, 1);
   cpgpanl(1, 1);
   cpgsvp(0.0, 1.0, 0.0, 1.0);
   cpgswin(2.0, 6.0, -2.0, 2.0);
   cpgmove(2.0, 0.0);
   cpgslw(3);
   cpgdraw(6.0, 0.0);
   cpgslw(1);
}
int plot_freq_data(void)
{
  int bin=0;

  printf("\nPlotting ...");
  cpgask(0);
  cpgpage();
  cpgslct(pg_id);
  cpgsci(1);
  cpgeras();
  cpgsvp(0.15f, 0.95f, 0.2f, 0.8f);
  cpgupdt();
  cpgsch(2.0);
  cpgswin(0, (N/2)+1, 0.0f, 0.005f);
  //  cpgswin(80, 120, 0.0f, 0.01f);
  cpgbox("BC1NST",0.0,0,"BCNST",0.0,0);
  cpglab("Frequency [bins]", "Peak Voltage [volts]", "Antenna Measurement Receiver");
  cpgmove(bin, accumFreqData[0]);
  for (bin=1; bin<(N/2)+1; bin++)
	 {
	   cpgdraw(bin, accumFreqData[bin]);
	 }
  return 0;
}
Example #8
0
int main()
{
	//
	printf("\n====================================================================\n");
	printf("This program is able to simulate a variety of ecological\n");
	printf("situations in a 2D lattice\n");
	printf("====================================================================\n");

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

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

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

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


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

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

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

	// inputs
	char input;

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

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

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

//	int aFlag; int abFlag; int bFlag;

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


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


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

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

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

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

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

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

	

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

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

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

			//printArray2DInt(simEnvAge, ENV_SIZE_X, ENV_SIZE_Y);

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

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

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

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


		tGlobal++;
		//for (t=0; t<10000000; t++){}
	}
}
Example #9
0
int plot_resid(Fluxrec *flux, int npoints, float *a, int ncoeff,
	       float *meanrms)
{
  int i,j;              /* Looping variables */
  int no_error=1;       /* Flag set to 0 on error */
  float ytmp;           /* Value of fitted function at a given day */
  float mean;           /* Mean of residual curve */
  float *polyx=NULL;    /* Polynomial in x */
  Fluxrec *resid=NULL;  /* Residual curve */
  Fluxrec *rptr;        /* Pointer to navigate resid */
  Fluxrec *fptr;        /* Pointer to navigate flux */

  /*
   * Allocate memory
   */

  if(!(polyx = new_array(ncoeff,1))) {
    fprintf(stderr,"ERROR: plot_resid\n");
    return 1;
  }

  if(!(resid = new_fluxrec(npoints)))
    no_error = 0;

  /*
   * Loop through flux, at each step compute the value of the function
   *  and then subtract it from the flux.
   */

  if(no_error) {
    for(i=0,fptr=flux,rptr=resid; i<npoints; i++,fptr++,rptr++) {

    /*
     * Compute the function value at this step
     */

    sinpoly(fptr->day,polyx-1,ncoeff);
    ytmp = 0;
    for(j=0; j<ncoeff; j++)
      ytmp += a[j] * polyx[j];

    /*
     * Now set resid->flux to be the difference between flux->flux and the
     *  fitted function
     */

    *rptr = *fptr;
    rptr->flux -= ytmp;
    }
  }

  /*
   * Now plot the points
   */

  if(no_error)
    if(plot_lcurve(resid,npoints,"Days","Residual Flux Density",""))
      no_error = 0;

  /*
   * Draw a line at 0.0 residual
   */

  if(no_error) {
    cpgsci(2);
    cpgslw(5);
    cpgmove(-999,0.0);
    cpgdraw(999,0.0);
    cpgslw(1);
    cpgsci(1);
  }

  /*
   * Calculate mean and rms
   */

  if(no_error) {
    if(calc_mean(resid,npoints,&mean,meanrms))
      no_error = 0;
    else {
      *meanrms /= sqrt(npoints);
      printf("\nplot_resid: Mean of residuals = %8.4f. ",mean);
      printf("RMS uncertainty in mean = %6.4f\n",*meanrms);
    }
  }

  /*
   * Clean up and exit
   */

  cpgslw(1);
  cpgsci(1);
  polyx = del_array(polyx);
  resid = del_fluxrec(resid);

  if(no_error)
    return 0;
  else {
    fprintf(stderr,"ERROR: plot_resid\n");
    return 1;
  }
}
/*
 * Class:     pulsarhunter_PgplotInterface
 * Method:    pgmove
 * Signature: (FF)V
 */
JNIEXPORT void JNICALL Java_pulsarhunter_PgplotInterface_pgmove
(JNIEnv *env, jclass cl, jfloat x, jfloat y){

	cpgmove(x,y);

}
void oppositionPlot(void) {
  int i;
  double rasun, decsun, distsun, toporasun, topodecsun, x, y, z;
  double jd, lstm, trueam, alt, ha, phi, longEcliptic, latEcliptic;
  double objra, objdec;
  
  openPlot("opposition");
  cpgpap(PLOTSIZE/0.5,0.5);

  cpgbbuf();

  cpgsubp(2,2);

  cpgpanl(1,1);
  cpgswin(PHIMIN, PHIMAX, AMMIN, AMMAX);
  cpgbox("BCNTS",0.0,0,"BVCNTS",0.0,0);
  cpgmtxt("L",2.0,0.5,0.5,"airmass");
  cpgmtxt("B",2.0,0.5,0.5,"angle from Sun");

  cpgsci(2);
  for(i=0; i<numobs; i++) {

    jd = obs[i].date + 2400000.5;
    lstm = lst(jd,longitude_hrs);

    // get ecliptic coordinates
    slaEqecl(obs[i].ra, obs[i].dec, obs[i].date, &longEcliptic, &latEcliptic);

    if(fabs(latEcliptic) < 10.0/DEG_IN_RADIAN && obs[i].twilight==0) {

      // get position of Sun
      accusun(jd, lstm, latitude_deg, &rasun, &decsun, &distsun,
              &toporasun, &topodecsun, &x, &y, &z);

      // sun-object angle in degrees
      // takes ra in hours, dec in degrees
      objra = adj_time(obs[i].ra*HRS_IN_RADIAN);
      objdec = obs[i].dec*DEG_IN_RADIAN;
      phi = mysubtend(rasun, decsun, objra, objdec)*DEG_IN_RADIAN;
      
      // angle from opposition is 180-phi
      //      FIXRANGE(phi,-180.0,180.0);
      
      //airmass takes ra, dec, in radians, returns true airmass
      airmass(obs[i].date, obs[i].ra, obs[i].dec, &trueam, &alt, &ha);
      
      cpgpt1(phi, trueam, -1);

    }
  }

  cpgsci(1);
  cpgptxt(0.0,3.0,0.0,0.5,"|ecliptic latitude|<10");
  cpgptxt(0.0,2.5,0.0,0.5,"night");

  cpgsci(3);
  cpgmove(-90.0,0.0);
  cpgdraw(-90.0,4.0);
  cpgmove( 90.0,0.0);
  cpgdraw( 90.0,4.0);
  cpgsci(1);


  cpgpanl(1,2);
  cpgswin(PHIMIN, PHIMAX, AMMIN, AMMAX);
  cpgbox("BCNTS",0.0,0,"BVCNTS",0.0,0);
  cpgmtxt("L",2.0,0.5,0.5,"airmass");
  cpgmtxt("B",2.0,0.5,0.5,"angle from Sun");

  cpgsci(2);
  for(i=0; i<numobs; i++) {

    jd = obs[i].date + 2400000.5;
    lstm = lst(jd,longitude_hrs);

    // get ecliptic coordinates
    slaEqecl(obs[i].ra, obs[i].dec, obs[i].date, &longEcliptic, &latEcliptic);

    if(fabs(latEcliptic) >= 10.0/DEG_IN_RADIAN  && obs[i].twilight==0 ) {

      // get position of Sun
      accusun(jd, lstm, latitude_deg, &rasun, &decsun, &distsun,
              &toporasun, &topodecsun, &x, &y, &z);

      // sun-object angle in degrees
      phi = mysubtend(rasun, decsun, obs[i].ra*HRS_IN_RADIAN, obs[i].dec*DEG_IN_RADIAN)*DEG_IN_RADIAN;
      
      // angle from opposition is 180-phi
      FIXRANGE(phi,-180.0,180.0);
      
      airmass(obs[i].date, obs[i].ra, obs[i].dec, &trueam, &alt, &ha);
      
      cpgpt1(phi, trueam, -1);

    }
  }

  cpgsci(1);
  cpgptxt(0.0,3.0,0.0,0.5,"|ecliptic latitude|>10");
  cpgptxt(0.0,2.5,0.0,0.5,"night");

  cpgsci(3);
  cpgmove(-90.0,0.0);
  cpgdraw(-90.0,4.0);
  cpgmove( 90.0,0.0);
  cpgdraw( 90.0,4.0);
  cpgsci(1);


  cpgpanl(2,1);
  cpgswin(PHIMIN, PHIMAX, AMMIN, AMMAX);
  cpgbox("BCNTS",0.0,0,"BVCNTS",0.0,0);
  cpgmtxt("L",2.0,0.5,0.5,"airmass");
  cpgmtxt("B",2.0,0.5,0.5,"angle from Sun");

  cpgsci(2);
  for(i=0; i<numobs; i++) {

    jd = obs[i].date + 2400000.5;
    lstm = lst(jd,longitude_hrs);

    // get ecliptic coordinates
    slaEqecl(obs[i].ra, obs[i].dec, obs[i].date, &longEcliptic, &latEcliptic);

    if(fabs(latEcliptic) < 10.0/DEG_IN_RADIAN  && obs[i].twilight==1) {

      // get position of Sun
      accusun(jd, lstm, latitude_deg, &rasun, &decsun, &distsun,
              &toporasun, &topodecsun, &x, &y, &z);

      // sun-object angle in degrees
      // takes ra in hours, dec in degrees
      objra = adj_time(obs[i].ra*HRS_IN_RADIAN);
      objdec = obs[i].dec*DEG_IN_RADIAN;
      phi = mysubtend(rasun, decsun, objra, objdec)*DEG_IN_RADIAN;
      
      // angle from opposition is 180-phi
      //      FIXRANGE(phi,-180.0,180.0);
      
      //airmass takes ra, dec, in radians, returns true airmass
      airmass(obs[i].date, obs[i].ra, obs[i].dec, &trueam, &alt, &ha);
      
      cpgpt1(phi, trueam, -1);

    }
  }

  cpgsci(1);
  cpgptxt(0.0,3.0,0.0,0.5,"|ecliptic latitude|<10");
  cpgptxt(0.0,2.5,0.0,0.5,"twilight");

  cpgsci(3);
  cpgmove(-90.0,0.0);
  cpgdraw(-90.0,4.0);
  cpgmove( 90.0,0.0);
  cpgdraw( 90.0,4.0);
  cpgsci(1);


  cpgpanl(2,2);
  cpgswin(PHIMIN, PHIMAX, AMMIN, AMMAX);
  cpgbox("BCNTS",0.0,0,"BVCNTS",0.0,0);
  cpgmtxt("L",2.0,0.5,0.5,"airmass");
  cpgmtxt("B",2.0,0.5,0.5,"angle from Sun");

  cpgsci(2);
  for(i=0; i<numobs; i++) {

    jd = obs[i].date + 2400000.5;
    lstm = lst(jd,longitude_hrs);

    // get ecliptic coordinates
    slaEqecl(obs[i].ra, obs[i].dec, obs[i].date, &longEcliptic, &latEcliptic);

    if(fabs(latEcliptic) >= 10.0/DEG_IN_RADIAN  && obs[i].twilight==1) {

      // get position of Sun
      accusun(jd, lstm, latitude_deg, &rasun, &decsun, &distsun,
              &toporasun, &topodecsun, &x, &y, &z);

      // sun-object angle in degrees
      phi = mysubtend(rasun, decsun, obs[i].ra*HRS_IN_RADIAN, obs[i].dec*DEG_IN_RADIAN)*DEG_IN_RADIAN;
      
      // angle from opposition is 180-phi
      FIXRANGE(phi,-180.0,180.0);
      
      airmass(obs[i].date, obs[i].ra, obs[i].dec, &trueam, &alt, &ha);
      
      cpgpt1(phi, trueam, -1);

    }
  }

  cpgsci(1);
  cpgptxt(0.0,3.0,0.0,0.5,"|ecliptic latitude|>10");
  cpgptxt(0.0,2.5,0.0,0.5,"twilight");

  cpgsci(3);
  cpgmove(-90.0,0.0);
  cpgdraw(-90.0,4.0);
  cpgmove( 90.0,0.0);
  cpgdraw( 90.0,4.0);
  cpgsci(1);


  cpgebuf();
  closePlot();
}
Example #12
0
void
cupdate(Chan *c, uchar *buf, int len, vlong off)
{
	Mntcache *m;
	Extent *tail;
	Extent *e, *f, *p;
	int o, ee, eblock;
	ulong offset;

	if(off > maxcache || len == 0)
		return;

	m = c->mcp;
	if(m == 0)
		return;
	qlock(m);
	if(cdev(m, c) == 0) {
		qunlock(m);
		return;
	}

	/*
	 * Find the insertion point
	 */
	offset = off;
	p = 0;
	for(f = m->list; f; f = f->next) {
		if(f->start > offset)
			break;
		p = f;
	}

	/* trim if there is a successor */
	eblock = offset+len;
	if(f != 0 && eblock > f->start) {
		len -= (eblock - f->start);
		if(len <= 0) {
			qunlock(m);
			return;
		}
	}

	if(p == 0) {		/* at the head */
		e = cchain(buf, offset, len, &tail);
		if(e != 0) {
			m->list = e;
			tail->next = f;
		}
		qunlock(m);
		return;
	}

	/* trim to the predecessor */
	ee = p->start+p->len;
	if(offset < ee) {
		o = ee - offset;
		len -= o;
		if(len <= 0) {
			qunlock(m);
			return;
		}
		buf += o;
		offset += o;
	}

	/* try and pack data into the predecessor */
	if(offset == ee && p->len < BY2PG) {
		o = len;
		if(o > BY2PG - p->len)
			o = BY2PG - p->len;
		if(cpgmove(p, buf, p->len, o)) {
			p->len += o;
			buf += o;
			len -= o;
			offset += o;
			if(len <= 0) {
if(f && p->start + p->len > f->start) print("CACHE: p->start=%uld p->len=%d f->start=%uld\n", p->start, p->len, f->start);
				qunlock(m);
				return;
			}
		}
	}

	e = cchain(buf, offset, len, &tail);
	if(e != 0) {
		p->next = e;
		tail->next = f;
	}
	qunlock(m);
}
Example #13
0
void
cwrite(Chan* c, uchar *buf, int len, vlong off)
{
	int o, eo;
	Mntcache *m;
	ulong eblock, ee;
	Extent *p, *f, *e, *tail;
	ulong offset;

	if(off > maxcache || len == 0)
		return;

	m = c->mcp;
	if(m == 0)
		return;

	qlock(m);
	if(cdev(m, c) == 0) {
		qunlock(m);
		return;
	}

	offset = off;
	m->qid.vers++;
	c->qid.vers++;

	p = 0;
	for(f = m->list; f; f = f->next) {
		if(f->start >= offset)
			break;
		p = f;
	}

	if(p != 0) {
		ee = p->start+p->len;
		eo = offset - p->start;
		/* pack in predecessor if there is space */
		if(offset <= ee && eo < BY2PG) {
			o = len;
			if(o > BY2PG - eo)
				o = BY2PG - eo;
			if(cpgmove(p, buf, eo, o)) {
				if(eo+o > p->len)
					p->len = eo+o;
				buf += o;
				len -= o;
				offset += o;
			}
		}
	}

	/* free the overlap -- it's a rare case */
	eblock = offset+len;
	while(f && f->start < eblock) {
		e = f->next;
		extentfree(f);
		f = e;
	}

	/* link the block (if any) into the middle */
	e = cchain(buf, offset, len, &tail);
	if(e != 0) {
		tail->next = f;
		f = e;
	}

	if(p == 0)
		m->list = f;
	else
		p->next = f;
	qunlock(m);
}
Example #14
0
int main(int argc, char *argv[])
{
   float maxpow = 0.0, inx = 0.0, iny = 0.0;
   double centerr, offsetf;
   int zoomlevel, maxzoom, minzoom, xid, psid;
   char *rootfilenm, inchar;
   fftpart *lofp;
   fftview *fv;

   if (argc == 1) {
      printf("\nusage:  explorefft fftfilename\n\n");
      exit(0);
   }

   printf("\n\n");
   printf("      Interactive FFT Explorer\n");
   printf("         by Scott M. Ransom\n");
   printf("            October, 2001\n");
   print_help();

   {
      int hassuffix = 0;
      char *suffix;

      hassuffix = split_root_suffix(argv[1], &rootfilenm, &suffix);
      if (hassuffix) {
         if (strcmp(suffix, "fft") != 0) {
            printf("\nInput file ('%s') must be a FFT file ('.fft')!\n\n", argv[1]);
            free(suffix);
            exit(0);
         }
         free(suffix);
      } else {
         printf("\nInput file ('%s') must be a FFT file ('.fft')!\n\n", argv[1]);
         exit(0);
      }
   }

   /* Read the info file */

   readinf(&idata, rootfilenm);
   if (strlen(remove_whitespace(idata.object)) > 0) {
      printf("Examining %s data from '%s'.\n\n",
             remove_whitespace(idata.object), argv[1]);
   } else {
      printf("Examining data from '%s'.\n\n", argv[1]);
   }
   N = idata.N;
   T = idata.dt * idata.N;
#ifdef USEMMAP
   printf("Memory mapping the input FFT.  This may take a while...\n");
   mmap_file = open(argv[1], O_RDONLY);
   {
      int rt;
      struct stat buf;

      rt = fstat(mmap_file, &buf);
      if (rt == -1) {
         perror("\nError in fstat() in explorefft.c");
         printf("\n");
         exit(-1);
      }
      Nfft = buf.st_size / sizeof(fcomplex);
   }
   lofp = get_fftpart(0, Nfft);
#else
   {
      int numamps;

      fftfile = chkfopen(argv[1], "rb");
      Nfft = chkfilelen(fftfile, sizeof(fcomplex));
      numamps = (Nfft > MAXBINS) ? (int) MAXBINS : (int) Nfft;
      lofp = get_fftpart(0, numamps);
   }
#endif

   /* Plot the initial data */

   {
      int initnumbins = INITIALNUMBINS;

      if (initnumbins > Nfft) {
         initnumbins = next2_to_n(Nfft) / 2;
         zoomlevel = LOGDISPLAYNUM - (int) (log(initnumbins) / log(2.0));
         minzoom = zoomlevel;
      } else {
         zoomlevel = LOGDISPLAYNUM - LOGINITIALNUMBINS;
         minzoom = LOGDISPLAYNUM - LOGMAXBINS;
      }
      maxzoom = LOGDISPLAYNUM - LOGMINBINS;
      centerr = initnumbins / 2;
   }
   fv = get_fftview(centerr, zoomlevel, lofp);

   /* Prep the XWIN device for PGPLOT */

   xid = cpgopen("/XWIN");
   if (xid <= 0) {
      free(fv);
#ifdef USEMMAP
      close(mmap_file);
#else
      fclose(fftfile);
#endif
      free_fftpart(lofp);
      exit(EXIT_FAILURE);
   }
   cpgscr(15, 0.4, 0.4, 0.4);
   cpgask(0);
   cpgpage();
   offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);

   do {
      cpgcurs(&inx, &iny, &inchar);
      if (DEBUGOUT)
         printf("You pressed '%c'\n", inchar);

      switch (inchar) {
      case 'A':                /* Zoom in */
      case 'a':
         centerr = (inx + offsetf) * T;
      case 'I':
      case 'i':
         if (DEBUGOUT)
            printf("  Zooming in  (zoomlevel = %d)...\n", zoomlevel);
         if (zoomlevel < maxzoom) {
            zoomlevel++;
            free(fv);
            fv = get_fftview(centerr, zoomlevel, lofp);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         } else
            printf("  Already at maximum zoom level (%d).\n", zoomlevel);
         break;
      case 'X':                /* Zoom out */
      case 'x':
      case 'O':
      case 'o':
         if (DEBUGOUT)
            printf("  Zooming out  (zoomlevel = %d)...\n", zoomlevel);
         if (zoomlevel > minzoom) {
            zoomlevel--;
            free(fv);
            fv = get_fftview(centerr, zoomlevel, lofp);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         } else
            printf("  Already at minimum zoom level (%d).\n", zoomlevel);
         break;
      case '<':                /* Shift left 1 full screen */
         centerr -= fv->numbins + fv->numbins / 8;
      case ',':                /* Shift left 1/8 screen */
         if (DEBUGOUT)
            printf("  Shifting left...\n");
         centerr -= fv->numbins / 8;
         {                      /* Should probably get the previous chunk from the fftfile... */
            double lowestr;

            lowestr = 0.5 * fv->numbins;
            if (centerr < lowestr)
               centerr = lowestr;
         }
         free(fv);
         fv = get_fftview(centerr, zoomlevel, lofp);
         cpgpage();
         offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         break;
      case '>':                /* Shift right 1 full screen */
         centerr += fv->numbins - fv->numbins / 8;
      case '.':                /* Shift right 1/8 screen */
         if (DEBUGOUT)
            printf("  Shifting right...\n");
         centerr += fv->numbins / 8;
         {                      /* Should probably get the next chunk from the fftfile... */
            double highestr;

            highestr = lofp->rlo + lofp->numamps - 0.5 * fv->numbins;
            if (centerr > highestr)
               centerr = highestr;
         }
         free(fv);
         fv = get_fftview(centerr, zoomlevel, lofp);
         cpgpage();
         offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         break;
      case '+':                /* Increase height of powers */
      case '=':
         if (maxpow == 0.0) {
            printf("  Auto-scaling is off.\n");
            maxpow = 1.1 * fv->maxpow;
         }
         maxpow = 3.0 / 4.0 * maxpow;
         cpgpage();
         offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         break;
      case '-':                /* Decrease height of powers */
      case '_':
         if (maxpow == 0.0) {
            printf("  Auto-scaling is off.\n");
            maxpow = 1.1 * fv->maxpow;
         }
         maxpow = 4.0 / 3.0 * maxpow;
         cpgpage();
         offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         break;
      case 'S':                /* Auto-scale */
      case 's':
         if (maxpow == 0.0)
            break;
         else {
            printf("  Auto-scaling is on.\n");
            maxpow = 0.0;
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
            break;
         }
      case 'G':                /* Goto a frequency */
      case 'g':
         {
            char freqstr[50];
            double freq = -1.0;

            while (freq < 0.0) {
               printf("  Enter the frequency (Hz) to go to:\n");
               fgets(freqstr, 50, stdin);
               freqstr[strlen(freqstr) - 1] = '\0';
               freq = atof(freqstr);
            }
            offsetf = 0.0;
            centerr = freq * T;
            printf("  Moving to frequency %.15g.\n", freq);
            free(fv);
            fv = get_fftview(centerr, zoomlevel, lofp);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, centerr, 2);
         }
         break;
      case 'H':                /* Show harmonics */
      case 'h':
         {
            double retval;

            retval = harmonic_loop(xid, centerr, zoomlevel, lofp);
            if (retval > 0.0) {
               offsetf = 0.0;
               centerr = retval;
               free(fv);
               fv = get_fftview(centerr, zoomlevel, lofp);
               cpgpage();
               offsetf = plot_fftview(fv, maxpow, 1.0, centerr, 2);
            }
         }
         break;
      case '?':                /* Print help screen */
         print_help();
         break;
      case 'D':                /* Show details about a selected point  */
      case 'd':
         {
            double newr;

            printf("  Searching for peak near freq = %.7g Hz...\n", (inx + offsetf));
            newr = find_peak(inx + offsetf, fv, lofp);
            centerr = newr;
            free(fv);
            fv = get_fftview(centerr, zoomlevel, lofp);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, centerr, 2);
         }
         break;
      case 'L':                /* Load a zaplist */
      case 'l':
         {
            int ii, len;
            char filename[200];
            double *lobins, *hibins;

            printf("  Enter the filename containing the zaplist to load:\n");
            fgets(filename, 199, stdin);
            len = strlen(filename) - 1;
            filename[len] = '\0';
            numzaplist = get_birdies(filename, T, 0.0, &lobins, &hibins);
            lenzaplist = numzaplist + 20;       /* Allow some room to add more */
            if (lenzaplist)
               free(zaplist);
            zaplist = (bird *) malloc(sizeof(bird) * lenzaplist);
            for (ii = 0; ii < numzaplist; ii++) {
               zaplist[ii].lobin = lobins[ii];
               zaplist[ii].hibin = hibins[ii];
            }
            vect_free(lobins);
            vect_free(hibins);
            printf("\n");
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         }
         break;
      case 'Z':                /* Add a birdie to a zaplist */
      case 'z':
         {
            int badchoice = 2;
            float lox, hix, loy, hiy;
            double rs[2];
            char choice;

            if (numzaplist + 1 > lenzaplist) {
               lenzaplist += 10;
               zaplist = (bird *) realloc(zaplist, sizeof(bird) * lenzaplist);
            }
            cpgqwin(&lox, &hix, &loy, &hiy);
            printf("  Click the left mouse button on the first frequency limit.\n");
            while (badchoice) {
               cpgcurs(&inx, &iny, &choice);
               if (choice == 'A' || choice == 'a') {
                  rs[2 - badchoice] = ((double) inx + offsetf) * T;
                  cpgsave();
                  cpgsci(7);
                  cpgmove(inx, 0.0);
                  cpgdraw(inx, hiy);
                  cpgunsa();
                  badchoice--;
                  if (badchoice == 1)
                     printf
                         ("  Click the left mouse button on the second frequency limit.\n");
               } else {
                  printf("  Option not recognized.\n");
               }
            };
            if (rs[1] > rs[0]) {
               zaplist[numzaplist].lobin = rs[0];
               zaplist[numzaplist].hibin = rs[1];
            } else {
               zaplist[numzaplist].lobin = rs[1];
               zaplist[numzaplist].hibin = rs[0];
            }
            printf("    The new birdie has:  f_avg = %.15g  f_width = %.15g\n\n",
                   0.5 * (zaplist[numzaplist].hibin + zaplist[numzaplist].lobin) / T,
                   (zaplist[numzaplist].hibin - zaplist[numzaplist].lobin) / T);
            numzaplist++;
            qsort(zaplist, numzaplist, sizeof(bird), compare_birds);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         }
         break;
      case 'P':                /* Print the current plot */
      case 'p':
         {
            int len;
            char filename[200];

            printf("  Enter the filename to save the plot as:\n");
            fgets(filename, 196, stdin);
            len = strlen(filename) - 1;
            filename[len + 0] = '/';
            filename[len + 1] = 'P';
            filename[len + 2] = 'S';
            filename[len + 3] = '\0';
            psid = cpgopen(filename);
            cpgslct(psid);
            cpgpap(10.25, 8.5 / 11.0);
            cpgiden();
            cpgscr(15, 0.8, 0.8, 0.8);
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
            cpgclos();
            cpgslct(xid);
            cpgscr(15, 0.4, 0.4, 0.4);
            filename[len] = '\0';
            printf("  Wrote the plot to the file '%s'.\n", filename);
         }
         break;
      case 'N':                /* Changing power normalization */
      case 'n':
         {
            float inx2 = 0.0, iny2 = 0.0;
            char choice;
            unsigned char badchoice = 1;

            printf("  Specify the type of power normalization:\n"
                   "       m,M  :  Median values determined locally\n"
                   "       d,D  :  DC frequency amplitude\n"
                   "       r,R  :  Raw powers (i.e. no normalization)\n"
                   "       u,U  :  User specified interval (the average powers)\n");
            while (badchoice) {
               cpgcurs(&inx2, &iny2, &choice);
               switch (choice) {
               case 'M':
               case 'm':
                  norm_const = 0.0;
                  maxpow = 0.0;
                  badchoice = 0;
                  printf
                      ("  Using local median normalization.  Autoscaling is on.\n");
                  break;
               case 'D':
               case 'd':
                  norm_const = 1.0 / r0;
                  maxpow = 0.0;
                  badchoice = 0;
                  printf
                      ("  Using DC frequency (%f) normalization.  Autoscaling is on.\n",
                       r0);
                  break;
               case 'R':
               case 'r':
                  norm_const = 1.0;
                  maxpow = 0.0;
                  badchoice = 0;
                  printf
                      ("  Using raw powers (i.e. no normalization).  Autoscaling is on.\n");
                  break;
               case 'U':
               case 'u':
                  {
                     char choice2;
                     float xx = inx, yy = iny;
                     int lor, hir, numr;
                     double avg, var;

                     printf
                         ("  Use the left mouse button to select a left and right boundary\n"
                          "  of a region to calculate the average power.\n");
                     do {
                        cpgcurs(&xx, &yy, &choice2);
                     } while (choice2 != 'A' && choice2 != 'a');
                     lor = (int) ((xx + offsetf) * T);
                     cpgsci(7);
                     cpgmove(xx, 0.0);
                     cpgdraw(xx, 10.0 * fv->maxpow);
                     do {
                        cpgcurs(&xx, &yy, &choice2);
                     } while (choice2 != 'A' && choice2 != 'a');
                     hir = (int) ((xx + offsetf) * T);
                     cpgmove(xx, 0.0);
                     cpgdraw(xx, 10.0 * fv->maxpow);
                     cpgsci(1);
                     if (lor > hir) {
                        int tempr;
                        tempr = hir;
                        hir = lor;
                        lor = tempr;
                     }
                     numr = hir - lor + 1;
                     avg_var(lofp->rawpowers + lor - lofp->rlo, numr, &avg, &var);
                     printf("  Selection has:  average = %.5g\n"
                            "                  std dev = %.5g\n", avg, sqrt(var));
                     norm_const = 1.0 / avg;
                     maxpow = 0.0;
                     badchoice = 0;
                     printf
                         ("  Using %.5g as the normalization constant.  Autoscaling is on.\n",
                          avg);
                     break;
                  }
               default:
                  printf("  Unrecognized choice '%c'.\n", choice);
                  break;
               }
            }
            free(fv);
            fv = get_fftview(centerr, zoomlevel, lofp);
            cpgpage();
            offsetf = plot_fftview(fv, maxpow, 1.0, 0.0, 0);
         }
         break;
      case 'Q':                /* Quit */
      case 'q':
         printf("  Quitting...\n");
         free(fv);
         cpgclos();
         break;
      default:
         printf("  Unrecognized option '%c'.\n", inchar);
         break;
      }
   } while (inchar != 'Q' && inchar != 'q');

   free_fftpart(lofp);
#ifdef USEMMAP
   close(mmap_file);
#else
   fclose(fftfile);
#endif
   if (lenzaplist)
      free(zaplist);
   printf("Done\n\n");
   return 0;
}
Example #15
0
int main(){
	printf("\n====================================================================\n");
	printf("This program is able to simulate the diffusion of heat\n");
	printf("across a metal plate of size %i x %i\n", ENV_SIZE_X, ENV_SIZE_Y);
	printf("====================================================================\n");

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

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

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

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

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


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

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

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

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

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

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

	// rates
	float rateDiff = 0.2;
	float delta;

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

	// background heat
	float bgHeat;

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

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

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

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

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

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

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

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


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

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

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

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

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

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

		copyArray2D(simEnvEven, simEnvOdd, ENV_SIZE_X, ENV_SIZE_Y);

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

		flux = 0;

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

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



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

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

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

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

		totalHeatPre = 0;
		for (x=x1; x<=x2; x++)
			for (y=y1; y<=y2; y++)
				totalHeatPre += simEnvEven[x][y];
	}
}
Example #16
0
/* move pen (change current pen position) */
static void _pgmove (double *x, double *y)
{
   cpgmove ((float) *x, (float) *y);
}
Example #17
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 #18
0
void plot(GRAPHCONTROL *gr, SET *p) {
	char t[1024];

	cpgsch(FS);
	cpgsci(1);

	cpgsvp(0.07, 0.93, 0.35, 0.9);
	cpgeras();
	cpgswin(gr->xmin, gr->xmax, gr->ymin, gr->ymax);
	cpgbox("BCNST", 0.0, 0, "BCNST", 0.0, 0);

	cpgbbuf();

	cpgsch(0.8);
	float yp = 3.4;

	sprintf(t,"[n] Ano: %d/%d", p->y1, p->y2);
	cpgmtxt("T", yp, 0.0, 0.0, t);

	sprintf(t,"[m] Magnitude: %.2f/%.2f", p->m1, p->m2);
	cpgmtxt("T", yp, 0.25, 0.0, t);

	sprintf(t,"[s/0] Selecionar Regiao");
	(p->region) ? cpgsci(ON) : cpgsci(OFF);
	cpgmtxt("T", yp, 0.6, 0.0, t);
	cpgsci(1);

	cpgmtxt("T", yp, 0.85, 0.0, "[=] Salvar Print-out");


	yp -= 1.2;

	sprintf(t,"N: %ld",p->n);
	cpgmtxt("T", yp, 0.0, 0.0, t);

	sprintf(t,"[p] Profundidade(p): %.1f/%.1f",p->d1, p->d2);
	cpgmtxt("T", yp, 0.25, 0.0, t);

	sprintf(t,"Longitude: %.2f/%.2f",p->lon1, p->lon2);
	cpgmtxt("T", yp, 0.6, 0.0, t);

        cpgmtxt("T", yp, 0.85, 0.0, "[J] Definir intervalo");

	yp -= 1.2;

	sprintf(t,"Latitude: %.2f/%.2f", p->lat1, p->lat2);
	cpgmtxt("T", yp, 0.6, 0.0, t);

	sprintf(t,"[w] Zoom para todo o mapa");
	cpgmtxt("T", yp, 0.25, 0.0, t);
        
        cpgmtxt("T", yp, 0.85, 0.0, "    de ajuste");
        
	sprintf(t,"[c] Cor: %s", (gr->colormode == COLORDEPTH) ? "Profundidade" : (gr->colormode == COLORMAG) ? "Magnitude" : "Neutra");
	cpgmtxt("R", 1.0, 1.0, 1.0, t);


	(gr->hascontinents) ? cpgsci(ON) : cpgsci(OFF);
	sprintf(t,"[1] Continentes");
	cpgmtxt("R", 1.0, 0.25, 0.0, t);
	cpgsci(1);

	(gr->hasplates) ? cpgsci(ON) : cpgsci(OFF);
	sprintf(t,"[2] Placas");
	cpgmtxt("R", 1.0, 0.0, 0.0, t);
	cpgsci(1);

	// Legenda cores
	cpgsci(1);
	cpgsch(FS);

		/* Graphs */
	int i;
	if (gr->haspoints && p->n > 0) {

		int symbol = 17;
		(p->n > 50) ?  cpgsch(0.4) : cpgsch(FS);

		if (gr->colormode == COLORDEPTH)
			for(i = 0; i< p->n; i++) {
				cpgsci(depthcolor(p->d[i]));
				cpgpt1(p->x[i], p->y[i], symbol);
			}
		else if (gr->colormode == COLORMAG)
			for(i = 0; i< p->n; i++) {
				cpgsci(magcolor(p->m[i]));
				cpgpt1(p->x[i], p->y[i], symbol);
			}
		else
			cpgpt(p->n, p->x, p->y, symbol);

		cpgsci(1);
		cpgsch(FS);
	}

	if (gr->hascontinents >= 1) {
		cpgsci(1);
		cpgslw(2);
		for(i=0; i < ncontinentes; i++) {
			if (continentes[i][0] == -999 && continentes[i][1] == 999 ) {
				i++;
				cpgmove(continentes[i][0], continentes[i][1]);
				continue;
			}
			cpgdraw(continentes[i][0], continentes[i][1]);
		}

		if (gr->hascontinents >=2) {
			cpgslw(1);
			cpgsci(15);
			for(i=0; i < nborders; i++) {
				if (borders[i][0] == -999 && borders[i][1] == 999 ) {
					i++;
					cpgmove(borders[i][0], borders[i][1]);
					continue;
				}
				cpgdraw(borders[i][0], borders[i][1]);
			}
		}
	}

	if (gr->hasplates == 1) {
		cpgsci(3);
		cpgslw(3);
		for(i=0; i < nplates; i++) {
			if (plates[i][0] == -999 && plates[i][1] == 999 ) {
				i++;
				cpgmove(plates[i][0], plates[i][1]);
				continue;
			}
			if (fabs(plates[i][0] - plates[i-1][0]) > 180) {
				cpgmove(plates[i][0], plates[i][1]);
			}
			cpgdraw(plates[i][0], plates[i][1]);
		}
	}

	if (gr->colormode == COLORMAG)
		scalemag();
	else if (gr->colormode == COLORDEPTH)
		scaledep();

	cpgsci(1);
	cpgslw(1);

	cpgebuf();

	cpgsvp(0.07, 0.93, 0.35, 0.9);
	cpgswin(gr->xmin, gr->xmax, gr->ymin, gr->ymax);

	return;
}
Example #19
0
void plothistogram(SET *p, float w, int mode, float lm, float hm) {
	float *x = (mode == MAG) ? p->m : p->d;
	int i;
	char t[1024];

	float x1, x2, y1, y2;

	float *bins = NULL;
	float *freq = NULL;
	int nb;

	float a, b;
	float rms = -1;

	cpgsvp(0.63, 0.93, 0.07, 0.30);

	/* Check we have data */
	if (p->n ==0) {
		cpgswin(0.0, 1.0, 0.0, 1.0);
		cpgmtxt("T",-3, 0.5, 0.5, "-- Sem Dados -- ");
		return;
	}

	if (mode == MAG) {
		nb = gomag(x, p->n, w, &bins, &freq);
		rms = linefit(bins, freq, nb, lm, hm, &a, &b);
	} else {
		nb = godep(x, p->n, w, &bins, &freq);
	}

	/*
	 * Plot
	 */

	minmax(x, p->n, &x1, &x2);
	minmax(freq, nb, &y1, &y2);
	cpgswin(x1, x2, y1 - (y2-y1)*0.1, y2 * 1.2);
	cpgbox("BCNST", 0.0, 0, "BCMST", 0.0, 0);

	/*
	 * Labels
	 */
	cpgsch(0.7);
	cpgmtxt("L", 2.2, 0.0, 0.0, "[H] Trocar Mag/Dep");
	cpgmtxt("L", 1.0, 0.0, 0.0, "[B] Ajustar largura do bin");

	if (mode == MAG) {
		cpgmtxt("R", 3.0, 0.5, 0.5, "Log(n) Acumulado");
		cpgmtxt("B", 3.0, 0.5, 0.5, "Magnitude");

	} else {
		cpgmtxt("R", 3.0, 0.5, 0.5, "Log(n)");
		cpgmtxt("B", 3.0, 0.5, 0.5, "Profundidade (km)");
	}
	sprintf(t,"Min: %.1f Max: %.1f",x1,x2);
	if (mode == MAG) {
		cpgmtxt("B", -1.0, 0.05, 0.0,t);
	} else {
		cpgmtxt("T", -2.0, 0.95, 1.0,t);
	}
	cpgsch(FS);

	/*
	 * Plots
	 */
	cpgbin(nb, bins, freq, 1);

	if (mode == MAG) {
		cpgmove(x1, a*x1 + b);
		cpgdraw(x2, a*x2 + b);
		if ( lm >= 0.0 ) {
			float temp;
			
			cpgsci(2);
			cpgsch(1.2);
			temp = fabs((a*x1+b) - (a*x2+b));
			cpgpt1(lm, a*lm+b -temp * 0.06, 30);
			cpgpt1(hm, a*hm+b -temp * 0.06, 30);
			cpgsci(1);
			cpgsch(FS);
		}
	}

	if (mode == MAG) {
		cpgsch(0.7);
		sprintf(t,"f(x)=%.2f\\.x+%.2f",a,b);
		cpgmtxt("T",-2.0, 0.9, 1.0,t);

		sprintf(t,"b=%.2f",fabs(a));
		cpgmtxt("T",-3.2, 0.9, 1.0,t);
		cpgsch(FS);
	}

	cpgbbuf();

	/*
	 * Terminate
	 */
	cpgsci(1);
	cpgslw(1);

	cpgebuf();

	if (bins != NULL) free(bins);
	if (freq != NULL) free(freq);

	bins = NULL;
	freq = NULL;

	return;
}
Example #20
0
static double plot_fftview(fftview * fv, float maxpow, float charhgt,
                           float vertline, int vertline_color)
/* The return value is offsetf */
{
   int ii;
   double lor, lof, hir, hif, offsetf = 0.0;
   float *freqs;

   cpgsave();
   cpgbbuf();

   /* Set the "Normal" plotting attributes */

   cpgsls(1);
   cpgslw(1);
   cpgsch(charhgt);
   cpgsci(1);
   cpgvstd();

   if (maxpow == 0.0)           /* Autoscale for the maximum value */
      maxpow = 1.1 * fv->maxpow;

   lor = fv->lor;
   lof = lor / T;
   hir = lor + fv->dr * DISPLAYNUM;
   hif = hir / T;
   offsetf = 0.0;

   /* Period Labels */

   if (fv->zoomlevel >= 0 && lof > 1.0) {
      double lop, hip, offsetp = 0.0;
      lop = 1.0 / lof;
      hip = 1.0 / hif;
      offsetp = 0.0;

      if ((lop - hip) / hip < 0.001) {
         int numchar;
         char label[50];

         offsetp = 0.5 * (hip + lop);
         numchar = snprintf(label, 50, "Period - %.15g (s)", offsetp);
         cpgmtxt("T", 2.5, 0.5, 0.5, label);
      } else {
         cpgmtxt("T", 2.5, 0.5, 0.5, "Period (s)");
      }
      cpgswin(lop - offsetp, hip - offsetp, 0.0, maxpow);
      cpgbox("CIMST", 0.0, 0, "", 0.0, 0);
   }

   /* Frequency Labels */

   if ((hif - lof) / hif < 0.001) {
      int numchar;
      char label[50];

      offsetf = 0.5 * (hif + lof);
      numchar = snprintf(label, 50, "Frequency - %.15g (Hz)", offsetf);
      cpgmtxt("B", 2.8, 0.5, 0.5, label);
   } else {
      cpgmtxt("B", 2.8, 0.5, 0.5, "Frequency (Hz)");
   }
   cpgswin(lof - offsetf, hif - offsetf, 0.0, maxpow);

   /* Add zapboxes if required */

   if (numzaplist) {
      double zaplo, zaphi;

      cpgsave();
      cpgsci(15);
      cpgsfs(1);
      for (ii = 0; ii < numzaplist; ii++) {
         zaplo = zaplist[ii].lobin;
         zaphi = zaplist[ii].hibin;
         if ((zaplo < hir && zaplo > lor) || (zaphi < hir && zaphi > lor)) {
            cpgrect(zaplo / T - offsetf, zaphi / T - offsetf, 0.0, 0.95 * maxpow);
         }
      }
      cpgunsa();
   }

   /* Add a background vertical line if requested */

   if (vertline != 0.0 && vertline_color != 0) {
      cpgsave();
      cpgsci(vertline_color);
      cpgmove(vertline / T - offsetf, 0.0);
      cpgdraw(vertline / T - offsetf, maxpow);
      cpgunsa();
   }

   if (fv->zoomlevel >= 0 && lof > 1.0)
      cpgbox("BINST", 0.0, 0, "BCNST", 0.0, 0);
   else
      cpgbox("BCINST", 0.0, 0, "BCNST", 0.0, 0);

   /* Plot the spectrum */

   freqs = gen_fvect(DISPLAYNUM);
   for (ii = 0; ii < DISPLAYNUM; ii++)
      freqs[ii] = fv->rs[ii] / T - offsetf;
   if (fv->zoomlevel > 0) {     /* Magnified power spectrum */
      cpgline(DISPLAYNUM, freqs, fv->powers);
   } else {                     /* Down-sampled power spectrum */
      for (ii = 0; ii < DISPLAYNUM; ii++) {
         cpgmove(freqs[ii], 0.0);
         cpgdraw(freqs[ii], fv->powers[ii]);
      }
   }
   vect_free(freqs);
   cpgmtxt("L", 2.5, 0.5, 0.5, "Normalized Power");
   cpgebuf();
   cpgunsa();
   return offsetf;
}
Example #21
0
static int plot_dataview(dataview * dv, float minval, float maxval, float charhgt)
/* The return value is offsetn */
{
   int ii, lon, hin, offsetn = 0, tmpn;
   double lot, hit, offsett = 0.0;
   float ns[MAXDISPNUM], hiavg[MAXDISPNUM], loavg[MAXDISPNUM];
   float scalemin = 0.0, scalemax = 0.0, dscale;

   cpgsave();
   cpgbbuf();

   /* Set the "Normal" plotting attributes */

   cpgsls(1);
   cpgslw(1);
   cpgsch(charhgt);
   cpgsci(1);
   cpgvstd();

   /* Autoscale for the maximum value */
   if (maxval > 0.5 * LARGENUM)
      scalemax = dv->maxval;
   else
      scalemax = maxval;
   /* Autoscale for the minimum value */
   if (minval < 0.5 * SMALLNUM)
      scalemin = dv->minval;
   else
      scalemin = minval;
   dscale = 0.1 * (scalemax - scalemin);
   if (maxval > 0.5 * LARGENUM)
      maxval = scalemax + dscale;
   if (minval < 0.5 * SMALLNUM)
      minval = scalemin - dscale;

   lon = dv->lon;
   lot = lon * idata.dt;
   hin = lon + dv->numsamps;
   hit = hin * idata.dt;

   /* Time Labels (top of box) */

   if ((hit - lot) / hit < 0.001) {
      int numchar;
      char label[50];

      offsett = 0.5 * (hit + lot);
      numchar = snprintf(label, 50, "Time - %.15g (s)", offsett);
      cpgmtxt("T", 2.5, 0.5, 0.5, label);
   } else {
      cpgmtxt("T", 2.5, 0.5, 0.5, "Time (s)");
   }
   cpgswin(lot - offsett, hit - offsett, minval, maxval);
   cpgbox("CMST", 0.0, 0, "", 0.0, 0);

   /* Sample number labels */

   if (lon > 10000000 || (double) (hin - lon) / (double) hin < 0.001) {
      int numchar;
      char label[50];

      offsetn = (lon / 10000) * 10000;
      numchar = snprintf(label, 50, "Sample - %d", offsetn);
      cpgmtxt("B", 2.8, 0.5, 0.5, label);
   } else {
      cpgmtxt("B", 2.8, 0.5, 0.5, "Sample");
   }
   cpgswin(lon - offsetn, hin - offsetn, minval, maxval);
   cpgbox("BNST", 0.0, 0, "BCNST", 0.0, 0);

   /* Plot the rawdata if required */

   tmpn = lon - offsetn;
   if (plotstats == 0 || plotstats == 2) {
      if (dv->zoomlevel > 0) {
         for (ii = 0; ii < dv->dispnum; ii++)
            ns[ii] = tmpn + ii;
         cpgbin(dv->dispnum, ns, dv->vals, 0);
      } else {                  /* Plot the min/max values */
         for (ii = 0; ii < dv->numchunks; ii++, tmpn += dv->chunklen) {
            cpgmove((float) tmpn, dv->mins[ii]);
            cpgdraw((float) tmpn, dv->maxs[ii]);
         }
      }
   }

   /* Plot the other statistics if requested */

   if (plotstats == 0 || plotstats == 1) {
      tmpn = lon - offsetn;
      for (ii = 0; ii < dv->numchunks; ii++, tmpn += dv->chunklen) {
         ns[ii] = tmpn;
         hiavg[ii] = dv->avgmeds[ii] + dv->stds[ii];
         loavg[ii] = dv->avgmeds[ii] - dv->stds[ii];
      }
      if (dv->numchunks > 512) {
         if (plotstats == 1) {
            cpgline(dv->numchunks, ns, dv->mins);
            cpgline(dv->numchunks, ns, dv->maxs);
         }
         cpgsci(AVGMED_COLOR);
         cpgline(dv->numchunks, ns, dv->avgmeds);
         if (usemedian)
            cpgmtxt("T", -1.4, 0.02, 0.0, "Median");
         else
            cpgmtxt("T", -1.4, 0.02, 0.0, "Average");
         cpgsci(STDDEV_COLOR);
         cpgline(dv->numchunks, ns, hiavg);
         cpgline(dv->numchunks, ns, loavg);
         cpgmtxt("T", -2.6, 0.02, 0.0, "+/- 1 Std Dev");
      } else {
         if (plotstats == 1) {
            cpgbin(dv->numchunks, ns, dv->mins, 0);
            cpgbin(dv->numchunks, ns, dv->maxs, 0);
         }
         cpgsci(AVGMED_COLOR);
         cpgbin(dv->numchunks, ns, dv->avgmeds, 0);
         if (usemedian)
            cpgmtxt("T", -1.4, 0.02, 0.0, "Median");
         else
            cpgmtxt("T", -1.4, 0.02, 0.0, "Average");
         cpgsci(STDDEV_COLOR);
         cpgbin(dv->numchunks, ns, hiavg, 0);
         cpgbin(dv->numchunks, ns, loavg, 0);
         cpgmtxt("T", -2.6, 0.02, 0.0, "+/- 1 Std Dev");
      }
   }
   cpgsci(1);
   cpgmtxt("L", 2.5, 0.5, 0.5, "Sample Value");
   cpgebuf();
   cpgunsa();
   return offsetn;
}
Example #22
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;
}