예제 #1
0
void Pulsar::RemoveBaseline::Each::transform (Archive* archive)
{
  const unsigned nsub = archive->get_nsubint();
  const unsigned nchan = archive->get_nchan();
  const unsigned npol = archive->get_npol();

  bool pscrunch = (archive->get_state() == Signal::Coherence ||
		   archive->get_state() == Signal::PPQQ);

  for (unsigned isub=0; isub < nsub; isub++)
  {
    Integration* subint = archive->get_Integration (isub);
    for (unsigned ichan=0; ichan < nchan; ichan++)
    {
      Reference::To<Profile> profile = subint->get_Profile (0,ichan);
      if (pscrunch)
      {
	profile = profile->clone();
	profile->sum (subint->get_Profile (1,ichan));
      }

      Reference::To<PhaseWeight> baseline = profile->baseline();

      for (unsigned ipol=0; ipol < npol; ipol++)
      {
	Profile* p = subint->get_Profile(ipol, ichan);
	baseline->set_Profile (p);
	p->offset (-baseline->get_mean().val);
      }
    }
  }
};
예제 #2
0
파일: psrpca.C 프로젝트: lbaehren/lofarsoft
void psrpca::finalize ()
{
  arrival->set_observation ( total );
  arrival->get_toas(toas);

  if ( remove_std_baseline )
    std_archive -> remove_baseline ();
  Reference::To<Profile> std_prof = std_archive->get_Profile(0, 0, 0);
  float *s_amps = std_prof->get_amps ();
  const float nbin = std_prof->get_nbin ();

  double scale, offset, snr;

  if ( total_count < nbin )
    cerr << "WARNING: psrpca::finalize - not enough observations provided, "
	    "covariance matrix will not have full rank" << endl;

  //total->remove_baseline();

  gsl_matrix *profiles = gsl_matrix_alloc ( (unsigned)nbin, total_count );

  for (unsigned i_subint = 0; i_subint < total->get_nsubint(); i_subint++ )
  {
    Reference::To<Profile> prof = total->get_Profile ( i_subint, 0, 0 );
    if ( apply_shift )
      prof->rotate_phase ( toas[i_subint].get_phase_shift() );
    snr = prof->snr ();

    //calculate the scale
    float *p_amps = prof->get_amps ();
    scale = 0.0;

    for ( unsigned i_bin = 0; i_bin < nbin; i_bin++ )
    {
      scale += s_amps[i_bin] * p_amps[i_bin];
    }
    scale = (prof->get_nbin()* scale - prof->sum() * std_prof->sum()) /
	    (prof->get_nbin()* std_prof->sumsq() - std_prof->sum() * std_prof->sum());

    // calculate the baseline offset
    offset = (scale * std_prof->sum() - prof->sum()) / nbin;

    if ( prof_to_std )
    {
      //match the profile to standard and subtract the standard
      if ( apply_offset )
	prof->offset  ( offset );
      if ( apply_scale )
	prof->scale ( 1.0/scale );
      prof->diff ( std_prof );

      double* damps;
      damps = new double [ (unsigned)nbin ];
      transform( prof->get_amps(), prof->get_amps() + (unsigned)nbin, damps, CastToDouble() );

      gsl_vector_const_view view = gsl_vector_const_view_array( damps, nbin );
      gsl_matrix_set_col ( profiles, i_subint, &view.vector );
      t_cov->add_Profile ( prof, snr );
    }
    else
    {// prof_to_std is false
      Reference::To<Profile> diff = prof->clone ();
      diff->set_amps ( std_prof->get_amps () );
      if ( apply_offset ) 
	diff->offset( -offset );
      if ( apply_scale ) 
	diff->scale (scale);
      diff->diff ( prof );
      diff->scale (-1);

      double* damps;
      damps = new double [ (unsigned)nbin ];
      transform( diff->get_amps(), diff->get_amps() + (unsigned)nbin, damps, CastToDouble() );

      gsl_vector_const_view view = gsl_vector_const_view_array( damps, nbin );
      gsl_matrix_set_col ( profiles, i_subint, &view.vector );

      t_cov->add_Profile ( diff, snr );
      prof->set_amps ( diff->get_amps() );
    }
  }

  covariance = gsl_matrix_alloc ( (int) nbin, (int) nbin );
  t_cov->get_covariance_matrix_gsl ( covariance );

  // write the covariance matrix and difference profiles
  FILE *out;
  if ( save_covariance_matrix )
  {
    out = fopen ( (prefix+"_covariance.dat").c_str(), "w" );
    gsl_matrix_fprintf(out, covariance, "%g");
    fclose ( out );
  } // save covariance matrix

  if ( save_diffs ) 
    total->unload ( prefix+"_diffs.ar" );

  //solve the eigenproblem
  gsl_matrix_view m = gsl_matrix_submatrix ( covariance, 0, 0, (int)nbin, (int)nbin );
  gsl_vector *eval = gsl_vector_alloc ( (int)nbin );
  gsl_matrix *evec = gsl_matrix_alloc ( (int)nbin, (int)nbin );

  gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc ( (int)nbin );
  gsl_eigen_symmv ( &m.matrix, eval, evec, w );
  gsl_eigen_symmv_free ( w );
  gsl_eigen_symmv_sort ( eval, evec, GSL_EIGEN_SORT_VAL_DESC );

  // save evectors
  if ( save_evecs )
  {
    Reference::To<Archive> evecs_archive = total->clone();
    gsl_vector *evec_copy = gsl_vector_alloc ( (int)nbin );

    for (unsigned iext=0; iext < evecs_archive->get_nextension(); iext++)
    {
      delete evecs_archive->get_extension(iext);
    }

    evecs_archive->resize ( (unsigned)nbin, 1, 1, (unsigned)nbin );

    for (unsigned i_evec = 0; i_evec < (unsigned)nbin; i_evec++ )
    {
      gsl_vector_view view = gsl_matrix_column(evec, i_evec);

      gsl_vector_memcpy ( evec_copy, &view.vector );
      evecs_archive->get_Profile ( i_evec, 0, 0 ) -> set_amps ( evec_copy->data );
    }
    evecs_archive->unload ( prefix+"_evecs.ar" );
  } // save evectors

  if ( save_evals )
  {
    out = fopen ( (prefix+"_evals.dat").c_str(), "w" );
    gsl_vector_fprintf ( out, eval, "%g" );
    fclose ( out );
  } // save_evals

  // decompose profiles onto eigenvectors
  gsl_matrix *decompositions = gsl_matrix_alloc ( (unsigned)nbin, total_count );

  gsl_blas_dgemm ( CblasTrans, CblasNoTrans, 1.0, evec, profiles, 0.0, decompositions );

  if ( save_decomps )
  {
    out = fopen ( (prefix + "_decomposition.dat").c_str(), "w" );
    gsl_matrix_fprintf ( out, decompositions, "%g");
    fclose ( out );
  } // save decompositions

  if ( !residuals_file.empty() )
  {
    //read in the residuals:
    double tmp;
    unsigned residual_count = 0;

    gsl_vector *mjds = gsl_vector_alloc ( total->get_nsubint() );
    gsl_vector *residuals = gsl_vector_alloc ( total->get_nsubint() );
    gsl_vector *residuals_err = gsl_vector_alloc ( total->get_nsubint() );
    //TODO check the format of the input
    ifstream inFile( residuals_file.c_str() );
    if ( inFile.is_open() )
    {
      while ( inFile.good() )
      {
	inFile >> tmp;
	if ( !inFile.good() )
	  break;
	gsl_vector_set(mjds, residual_count, tmp);

	inFile >> tmp;
	gsl_vector_set(residuals, residual_count, tmp*1e6);

	inFile >> tmp;
	gsl_vector_set(residuals_err, residual_count, tmp);

	residual_count ++ ;
      }
      inFile.close ();
      if ( residual_count != total->get_nsubint() )
      {
	cerr << "psrpca::finalize wrong number of residuals provided. Got " << residual_count 
		<< " while needed " << total->get_nsubint()<< endl;
	exit (-1) ;
      }

    }
    else
    {
예제 #3
0
파일: psrzap.C 프로젝트: SkyTian13/psrchive
int main(int argc, char *argv[]) {

  /* Process any args */
  int opt=0;
  int verb=0;

  string expression;

  while ((opt=getopt(argc,argv,"hve:E:"))!=-1) {
    switch (opt) {

      case 'v':
        verb++;
        Archive::set_verbosity(verb);
        break;
        
      case 'e':
        output_ext.assign(optarg);
        break;

      case 'E':
	expression = optarg;
	break;

      case 'h':
      default:
        usage();
        usage_interactive();
        exit(0);
        break;

    }
  }

  if (optind==argc) {
    usage();
    cerr << PROG ": No filename given" << endl;
    exit(-1);
  }

  /* Load file */
  string filename = argv[optind];
  Reference::To<Archive> orig_arch = Archive::load(filename);
  Reference::To<Archive> arch = orig_arch->clone();
  arch->dedisperse();
  arch->remove_baseline();
  double bw = arch->get_bandwidth();
  string output_filename = replace_extension(filename, output_ext);
  string psrsh_filename = replace_extension(filename,"psh");

  // Create profile plots
  Reference::To<Archive> tot_arch=NULL,pf_arch=NULL,pt_arch=NULL;
  ProfilePlot *totplot=NULL;
  PhaseVsFrequency *pfplot=NULL;
  PhaseVsTime *ptplot=NULL;
  int totplot_id;

  totplot = new ProfilePlot;
  pfplot = new PhaseVsFrequency;
  ptplot= new PhaseVsTime;

  // Create window and subdivide
  totplot_id = cpgopen("/xs");
  cpgpap(0.0,1.5);
  cpgsubp(1,3);

  // Create Dynamic Spectrum Plot
  DynamicBaselineSpectrumPlot *dsplot = new DynamicBaselineSpectrumPlot;
  if (!expression.empty())
    dsplot->configure("exp="+expression);
  else
    dsplot->configure("var=1");

  dsplot->set_reuse_baseline();
  int dsplot_id = cpgopen("/xs");
  if (dsplot_id<=0) {
    cerr << PROG ": PGPLOT xwindows device open failed, exiting." << endl;
    exit(1);
  }
  cpgask(0);

  /* Input loop */
  char ch='\0';
  enum cursor_type curs=both_cursor;
  float x0=0.0, y0=0.0, x1, y1;
  int click=0, mode=0;
  int pol=0,izap=0;
  bool redraw=true, var=true, log=false, resum=true,remove_baseline=false,method=false;
  struct zap_range zap;
  vector<struct zap_range> zap_list;
  do {
    /* Redraw the plot if necessary */
    if (redraw) {

      char conf[256];
      sprintf(conf, "above:c=$file\\n%s %s, %s scale, %s baseline, pol %d.", 
	      method ? "total" : "off-pulse" ,
	      var ? "variance" : "mean",
	      log ? "log" : "linear",
	      remove_baseline ? "variable" : "constant",
          pol);

      dsplot->configure(conf);
      cpgslct(dsplot_id);
      //cpgeras();
      cpgpage();
      dsplot->plot(arch);
      if (resum) {
	// Total
	tot_arch = arch->total();
        cpgslct(totplot_id);
	cpgpanl(1,1);
        cpgeras();
        totplot->plot(tot_arch);

	// pulse vs frequency
	pf_arch = arch->clone();
	pf_arch->pscrunch();
	pt_arch = pf_arch->clone();
	pf_arch->tscrunch();
	//	pf_arch->remove_baseline();
	cpgpanl(1,2);
        cpgeras();
        pfplot->plot(pf_arch);

	// pulse vs time
	pt_arch->fscrunch();
	//	pt_arch->remove_baseline();
	cpgpanl(1,3);
        cpgeras();
        ptplot->plot(pt_arch);

        cpgslct(dsplot_id);
        resum = false;
      }
      redraw = false;
      cpgslct(dsplot_id);
    }

    // Mark zapped profiles
    for (unsigned i=izap; i<zap_list.size(); i++) {
      float df=zap_list[i].freq0-zap_list[i].freq1;
      float dt=zap_list[i].sub0-zap_list[i].sub1;

      cpgsfs(2);
      cpgsci(2);
      if (fabs(df)<0.001 && fabs(dt)<0.001)
	cpgpt1(zap_list[i].sub0+0.5,zap_list[i].freq0,2);
      else
	cpgrect(zap_list[i].sub0+0.5,zap_list[i].sub1+0.5,zap_list[i].freq0,zap_list[i].freq1);
      cpgsci(1);
    }

    /* On click 0 get start of a range */
    if (click==0) {
      if (curs==freq_cursor) mode=5;
      else if (curs==time_cursor) mode=6;
      else if (curs==both_cursor) mode=7;
      cpgband(mode,0,0,0,&x0,&y0,&ch);
    } 

    /* On click 1 get the end of a range */
    else if (click==1) {
      if (curs==freq_cursor) mode=3;
      else if (curs==time_cursor) mode=4;
      else if (curs==both_cursor) mode=2;
      cpgband(mode,0,x0,y0,&x1,&y1,&ch);
    }
    
#if 0 
    /* Debug */
    printf("x0=%.3f y0=%.3f x1=%.3f y1=%.3f ch='%c' click=%d\n",
        x0, y0, x1, y1, ch, click);
#endif

    /* Left mouse click = zoom*/
    if (ch=='A') {
      if (click==0) { click=1; continue; }
      if (click==1) {
        /* Do zoom here */
        char conf[256];
        float tmp,t0,t1;
        if (curs==freq_cursor || curs==both_cursor) {
          if (bw>0 && y0>y1) { tmp=y0; y0=y1; y1=tmp; }
          if (bw<0 && y0<y1) { tmp=y0; y0=y1; y1=tmp; }
          sprintf(conf,"y:win=(%.3f,%.3f)",y0,y1);
          dsplot->configure(string(conf));
          pfplot->configure(string(conf));
        }
        if (curs==time_cursor || curs==both_cursor) {
          if (x0>x1) { tmp=x0; x0=x1; x1=tmp; }
          sprintf(conf,"srange=(%d,%d)",(int)x0,(int)x1);
          dsplot->configure(string(conf));
	  t0=sub2time(pt_arch,(int) x0);
	  t1=sub2time(pt_arch,(int) x1);
	  sprintf(conf,"y:win=(%.3f,%.3f)",t0,t1);
	  ptplot->configure(string(conf));
        }
        redraw = true;
        click = 0;
        continue;
      }
    }

    /* Middle mouse click = redraw diagnostics */
    if (ch=='D' || ch==CMD_UPDATE) {
      redraw = true;
      resum = true;
      izap=zap_list.size();
      continue;
    }

    /* Right mouse click = zap */
    if (ch=='X') {

      /* Zap a single row or pixel */
      if (click==0) {
        zap.freq0 = zap.freq1 = y0;
        zap.sub0 = zap.sub1 = (int)x0;
      }

      /* Zap a range */
      if (click==1) {
        zap.freq0 = y0;
        zap.freq1 = y1;
        zap.sub0 = (int)x0;
        zap.sub1 = (int)x1;
      }

      /* Apply it */
      zap.type = curs;
      apply_zap(arch, &zap);

      zap_list.push_back(zap);
      redraw = false;
      resum = false;
      click=0;

      continue;
    }

    /* Undo last zap */
    if (ch==CMD_UNDO) {
      if (!zap_list.empty()) {
        zap = zap_list.back();
        apply_zap_range(arch, &zap, true, orig_arch);
        zap_list.pop_back();
        /* Reapply whole list in case of overlapping zaps */
        for (unsigned i=0; i<zap_list.size(); i++) {
          zap = zap_list[i];
          apply_zap_range(arch, &zap);
        }
        redraw = true;
        resum = false;
      }
      click = 0;
      continue;
    }

    /* Show help */
    if (ch==CMD_HELP) {
      usage_interactive();
      click = 0;
      continue; 
    }

    /* Esc = cancel */
    if (ch==27) {
      click=0;
      continue;
    }

    /* Switch to freq mode */
    if (ch==CMD_FREQMODE) {
      curs = freq_cursor;
      click = 0;
      continue;
    }

    /* Switch to time mode */
    if (ch==CMD_TIMEMODE) {
      curs = time_cursor;
      click = 0;
      continue;
    }

    /* Switch to time/freq mode */
    if (ch==CMD_BOTHMODE) {
      curs = both_cursor;
      click = 0;
      continue;
    }

    /* Toggle variance plot */
    if (ch==CMD_VAR) {
      var = !var;
      redraw = true;
      if (var) 
        dsplot->configure("var=1");
      else
        dsplot->configure("var=0");
      click = 0;
      continue;
    }

    // Toggle dynamic spectrum
    if (ch==CMD_METHOD) {
      method = !method;
      redraw = true;
      if (method) 
        dsplot->configure("method=1");
      else
        dsplot->configure("method=0");
      click = 0;
      continue;
    }

    /* toggle log scale */
    if (ch==CMD_LOG) {
      log = !log;
      redraw = true;
      if (log) 
        dsplot->configure("cmap:log=1");
      else
        dsplot->configure("cmap:log=0");
      click = 0;
      continue;
    }

    /* Flip through polarizations */
    if (ch==CMD_POL) {
      pol = (pol + 1) % arch->get_npol();
      char conf[256];
      sprintf(conf, "pol=%d", pol);
      dsplot->configure(conf);
      redraw = true;
      click = 0;
      continue;
    }

    /* Unset zoom */
    if (ch==CMD_UNZOOM) {
      dsplot->configure("srange=(-1,-1)");
      dsplot->configure("y:win=(0,0)");
      pfplot->configure("y:win=(0,0)");
      ptplot->configure("y:win=(0,0)");
      redraw = true;
      click = 0;
      izap=zap_list.size();
      continue;
    }

    /* Save file */
    if (ch==CMD_SAVE || ch==CMD_SAVE_QUIT) {
      /* Apply zaps to original file */
      for (unsigned i=0; i<zap_list.size(); i++) {
        zap = zap_list[i];
        apply_zap_range(orig_arch, &zap);
      }
      cout << "Unloading '" << output_filename << "'..." << endl;
      orig_arch->unload(output_filename);
      click = 0;
      if (ch==CMD_SAVE_QUIT) { ch=CMD_QUIT; }
      continue;
    }

    /* Print paz command */
    if (ch==CMD_PRINT) {
      char *cstr;
      cstr=new char [output_ext.size()+1];
      strcpy(cstr,output_ext.c_str());
      if (zap_list.size()>0) 
        printf("paz -e %s",cstr);
      /* Full time/freq zaps */
      for (unsigned i=0; i<zap_list.size(); i++) {
        if (zap_list[i].type == freq_cursor) {
          int chan0 = freq2chan(arch, zap_list[i].freq0);
          int chan1 = freq2chan(arch, zap_list[i].freq1);
          if (chan1<chan0) { int tmp=chan0; chan0=chan1; chan1=tmp; }
          if (chan0==chan1) 
	    printf(" -z %d", chan0);
          else 
	    printf(" -Z \"%d %d\"", chan0, chan1);
        } else if (zap_list[i].type == time_cursor) {
          if (zap_list[i].sub0==zap_list[i].sub1) 
            printf(" -w %d", zap_list[i].sub0);
          else 
            printf(" -W \"%d %d\"", zap_list[i].sub0, zap_list[i].sub1);
        } 
      }
      if (zap_list.size()>0) 
        printf(" %s\n", filename.c_str());
      /* Small ranges */
      for (unsigned i=0; i<zap_list.size(); i++) {
        if (zap_list[i].type == both_cursor) {
	  printf("paz -m -I");
	  int chan0 = freq2chan(arch, zap_list[i].freq0);
          int chan1 = freq2chan(arch, zap_list[i].freq1);
          if (chan1<chan0) { int tmp=chan0; chan0=chan1; chan1=tmp; }
          if (chan0==chan1)
            printf(" -z %d", chan0);
          else
            printf(" -Z \"%d %d\"", chan0, chan1);
	  if (zap_list[i].sub0==zap_list[i].sub1)
            printf(" -w %d", zap_list[i].sub0);
          else
            printf(" -W \"%d %d\"", zap_list[i].sub0, zap_list[i].sub1);
	  cstr=new char [output_filename.size()+1];
	  strcpy(cstr,output_filename.c_str());
	  printf(" %s\n", (char *) cstr);
	}
      }
    }

    // Toggle variable baseline
    if (ch==CMD_BASELINE) {
      // Set baselining strategy
      if (remove_baseline) {
	fprintf(stderr, "Unsetting remove_baseline_strategy.\n");
	Pulsar::Archive::remove_baseline_strategy.set (new Pulsar::RemoveBaseline::Total, &Pulsar::RemoveBaseline::Total::transform);
	remove_baseline=false;
	arch=orig_arch->clone();
	arch->dedisperse();
	arch->remove_baseline();
	for (unsigned i=0; i<zap_list.size(); i++) {
	  zap = zap_list[i];
	  apply_zap_range(arch, &zap);
	}
      } else {
	fprintf(stderr, "Set remove_baseline_strategy.\n");
	Pulsar::Archive::remove_baseline_strategy.set (new Pulsar::RemoveVariableBaseline, &Pulsar::RemoveVariableBaseline::transform);
	remove_baseline=true;
	arch=orig_arch->clone();
	arch->dedisperse();
	arch->remove_baseline();
	for (unsigned i=0; i<zap_list.size(); i++) {
	  zap = zap_list[i];
	  apply_zap_range(arch, &zap);
	}
      }
      redraw=true;
      resum=true;
    }
    
    // Generate PSRSH script
    if (ch==CMD_PSRSH) {
      FILE *file;
      file=fopen(psrsh_filename.c_str(),"w");
      fprintf(file,"#!/usr/bin/env psrsh\n\n# Run with psrsh -e <ext> <script>.psh <archive>.ar\n\n");

      // Full sub/chan zap
      for (unsigned i=0; i<zap_list.size(); i++) {
        if (zap_list[i].type == freq_cursor) {
          int chan0 = freq2chan(arch, zap_list[i].freq0);
          int chan1 = freq2chan(arch, zap_list[i].freq1);
          if (chan1<chan0) { int tmp=chan0; chan0=chan1; chan1=tmp; }
          if (chan0==chan1) 
	    fprintf(file,"zap chan %d\n",chan0);
          else 
	    fprintf(file,"zap chan %d-%d\n", chan0, chan1);
        } else if (zap_list[i].type == time_cursor) {
          if (zap_list[i].sub0==zap_list[i].sub1) 
            fprintf(file,"zap subint %d\n", zap_list[i].sub0);
          else 
            fprintf(file,"zap subint %d-%d\n", zap_list[i].sub0, zap_list[i].sub1);
        } 
      }

      // Subint/channel intersections
      for (unsigned i=0; i<zap_list.size(); i++) {
        if (zap_list[i].type == both_cursor) {
	  int chan0 = freq2chan(arch, zap_list[i].freq0);
          int chan1 = freq2chan(arch, zap_list[i].freq1);
	  int sub0 = zap_list[i].sub0;
	  int sub1 = zap_list[i].sub1;
          if (chan1<chan0) { int tmp=chan0; chan0=chan1; chan1=tmp; }
          if (chan0==chan1 && sub0==sub1) {
            fprintf(file,"zap such %d,%d\n",sub0,chan0);
	  } else {
	    fprintf(file,"zap such");
	    for (int sub=sub0;sub<=sub1;sub++) {
	      for (int chan=chan0;chan<=chan1;chan++) {
		fprintf(file," %d,%d",sub,chan);
	      }
	    }
	    fprintf(file,"\n");
	  }
	}
      }
      fclose(file);
      printf("PSRSH script written\n");
    }

  } while (ch!=CMD_QUIT);

}
예제 #4
0
파일: pam.C 프로젝트: lbaehren/lofarsoft
int main (int argc, char *argv[]) try {
  
    bool verbose = false;
    char* metafile = 0;
 
    string ulpath;

    bool save = false;
    string ext;
  
    bool tscr = false;
    int tscr_fac = 0;

    bool fscr = false;
    int fscr_fac = 0;

    bool bscr = false;
    int bscr_fac = 0;

    bool newdm = false;
    double dm = 0.0;

    bool scattered_power_correction = false;

    bool defaraday = false;

    bool newrm = false;
    double rm = 0.0;

    bool reset_weights = false;
    float new_weight = 1.0;

    float smear_dc = 0.0;

    bool rotate = false;
    double rphase = 0.0;

    bool dedisperse = false;
    bool dededisperse = false;

    bool pscr = false;

    bool invint = false;

    bool stokesify = false;
    bool unstokesify = false;

    bool flipsb = false;
    bool flip_freq = false;
    double flip_freq_mhz = 0.0;

    Pulsar::Parameters* new_eph = 0;

    string command = "pam";

    char* archive_class = 0;

    int new_nchn = 0;
    int new_nsub = 0;
    int new_nbin = 0;

    float tsub = 0.0;

    bool circ = false;
    bool lin = false;

    unsigned ronsub = 0;
    bool cbppo = false;
    bool cbpao = false;
    bool cblpo = false;
    bool cblao = false;

    int subint_extract_start = -1;
    int subint_extract_end = -1;

    bool new_cfreq = false;
    double new_fr = 0.0;
    Signal::Source new_type = Signal::Unknown;
    string instrument;
    bool reverse_freqs = false;
    string site;
    string name;
    float mult = -1.0;
    double new_folding_period = -1.0;

    bool update_dm_from_eph = false;
    double aux_rm = 0.0;

    Reference::To<Pulsar::IntegrationOrder> myio;
    Reference::To<Pulsar::Receiver> install_receiver;

    Pulsar::ReflectStokes reflections;

    int c = 0;

    const int TYPE = 1208;
    const int INST = 1209;
    const int REVERSE_FREQS = 1210;
    const int SITE = 1211;
    const int NAME = 1212;
    const int DD   = 1213;
    const int RR   = 1214;
    const int SPC  = 1215;
    const int RM   = 1216;
    const int MULT = 1218;
    const int PERIOD=1219;
    const int SS   = 1220;
    const int FLIP = 1221;
    const int UPDATE_DM = 1222;
    const int AUX_RM = 1223;

    while (1) {

      int options_index = 0;

      static struct option long_options[] = {
	{"setnchn",    1, 0, 200},
	{"setnsub",    1, 0, 201},
	{"setnbin",    1, 0, 202},
	{"binphsperi", 1, 0, 203},
	{"binphsasc",  1, 0, 204},
	{"binlngperi", 1, 0, 205},
	{"binlngasc",  1, 0, 206},
	{"receiver",   1, 0, 207},
	{"settsub",    1, 0, 208},
	{"type",       1, 0, TYPE},
	{"inst",       1, 0, INST},
	{"reverse_freqs",no_argument,0,REVERSE_FREQS},
	{"flip",       1 ,0, FLIP},
	{"site",       1, 0, SITE},
	{"name",       1, 0, NAME},
	{"DD",         no_argument,      0,DD},
	{"RR",         no_argument,      0,RR},
	{"RM",         required_argument,0,RM},
	{"spc",        no_argument,      0,SPC},
	{"mult",       required_argument,0,MULT},
	{"period",     required_argument,0,PERIOD},
	{"SS",         no_argument,      0,SS},
	{"update_dm",   no_argument,      0,UPDATE_DM},
	{"aux_rm",    required_argument,0,AUX_RM},
	{0, 0, 0, 0}
      };

      c = getopt_long(argc, argv, "hqvViM:mn:a:e:E:TFpIt:f:b:d:o:s:r:u:w:DSBLCx:R:",
		      long_options, &options_index);

      if (c == -1)
	break;

      switch (c) {
      case 'h':
	usage();
	return (0);
	break;
      case 'q':
	Pulsar::Archive::set_verbosity(0);
	break;
      case 'v':
	verbose = true;
	Pulsar::Archive::set_verbosity(2);
	break;
      case 'V':
	verbose = true;
	Pulsar::Archive::set_verbosity(3);
	break;
      case 'i':
	cout << "$Id: pam.C,v 1.101 2010/10/05 23:59:50 jonathan_khoo Exp $" << endl;
	return 0;
      case 'm':
	save = true;
	break;
      case 'M':
        metafile = optarg;
        break;
      case 'L':
	lin = true;
	break;
      case 'C':
	circ = true;
	break;
      case 'a':
	archive_class = optarg;
	break;
      case 'e':
	ext = optarg;
	if( !ext.empty() )
	  save = true;
	break;
      case 'E':

	try {
	  new_eph = factory<Pulsar::Parameters> (optarg);
	}
	catch (Error& error) {
	  cerr << "Could not load new ephemeris from " << optarg << endl;
	  return -1;
	}

	command += " -E";
	break;
      case 'T':
	tscr = true;
	command += " -T";
	break;
      case 'F':
	fscr = true;
	command += " -F";
	break;
      case 'p':
	pscr = true;
	command += " -p";
	break;
      case 'I':
	invint = true;
	pscr = false;
	command += " -I";
	break;
      case 'f':
	fscr = true;
	if (sscanf(optarg, "%d", &fscr_fac) != 1) {
	  cout << "That is not a valid fscrunch factor" << endl;
	  return -1;
	}
	command += " -f ";
	command += optarg;
	break;
	
      case 'n':

	reflections.add_reflection( optarg[0] );

	command += " -n ";
	command += optarg;
	break;

      case 'o':
	new_cfreq = true;
	if (sscanf(optarg, "%lf", &new_fr) != 1) {
	  cout << "That is not a valid centre frequency" << endl;
	  return -1;
	}
	command += " -o ";
	command += optarg;
	break;
      case 't':
	tscr = true;
	if (sscanf(optarg, "%d", &tscr_fac) != 1) {
	  cout << "That is not a valid tscrunch factor" << endl;
	  return -1;
	}
	command += " -t ";
	command += optarg;
	break;
      case 'b':
	bscr = true;
	if (sscanf(optarg, "%d", &bscr_fac) != 1) {
	  cout << "That is not a valid bscrunch factor" << endl;
	  return -1;
	}
	if (bscr_fac <= 0) {
	  cout << "That is not a valid bscrunch factor" << endl;
	  return -1;
	}
	command += " -b ";
	command += optarg;
	break;
      case 'd':
	newdm = true;
	if (sscanf(optarg, "%lf", &dm) != 1) {
	  cout << "That is not a valid dispersion measure" << endl;
	  return -1;
	}
	command += " -d ";
	command += optarg;
	break;
      case 'D':
	dedisperse = true;
	command += " -D ";
	break;
      case 'R':
	if (sscanf(optarg, "%lf", &rm) != 1) {
	  cout << "That is not a valid rotation measure" << endl;
	  return -1;
	}
	newrm = true;
	defaraday = true;
	command += " -R ";
	command += optarg;
	break;
      case 's':
	if (sscanf(optarg, "%f", &smear_dc) != 1) {
	  cout << "That is not a valid smearing duty cycle" << endl;
	  return -1;
	}
	command += " -s ";
	command += optarg;
	break;
      case 'r':
	rotate = true;
	if (sscanf(optarg, "%lf", &rphase) != 1) {
	  cout << "That is not a valid rotation phase" << endl;
	  return -1;
	}
	if (rphase <= -1.0 || rphase >= 1.0) {
	  cout << "That is not a valid rotation phase" << endl;
	  return -1;
	}
	command += " -r ";
	command += optarg;
	break;
      case 'u':
	ulpath = optarg;
	if( !ulpath.empty() )
	{
	  save = true;
	  if (ulpath.substr(ulpath.length()-1,1) != "/")
	    ulpath += "/";
	}
	break;
      case 'w':
	reset_weights = true;
	if (sscanf(optarg, "%f", &new_weight) != 1) {
	  cout << "That is not a valid weight" << endl;
	  return -1;
	}
	command += " -w ";
	command += optarg;
	break;
      case 'S':
	stokesify = true;
	break;
      case SS:
        unstokesify = true;
        break;
      case 'B':
	flipsb = true;
	break;
      case 'x' :
	if (sscanf(optarg, "%d %d", 
		   &subint_extract_start, &subint_extract_end) !=2 ) {
	  cout << "That is not a valid subint range" << endl;
	  return -1;
	}
	subint_extract_end++;
	break;
      case 200:
	fscr = true;
	if (sscanf(optarg, "%d", &new_nchn) != 1) {
	  cout << "That is not a valid number of channels" << endl;
	  return -1;
	}
	if (new_nchn <= 0) {
	  cout << "That is not a valid number of channels" << endl;
	  return -1;
	}
	command += " --setnchn ";
	command += optarg;
	break;
      case 201:
	tscr = true;
	if (sscanf(optarg, "%d", &new_nsub) != 1) {
	  cout << "That is not a valid number of subints" << endl;
	  return -1;
	}
	if (new_nsub <= 0) {
	  cout << "That is not a valid number of subints" << endl;
	  return -1;
	}
	command += " --setnsub ";
	command += optarg;
	break;
      case 202:
	bscr = true;
	if (sscanf(optarg, "%d", &new_nbin) != 1) {
	  cout << "That is not a valid number of bins" << endl;
	  return -1;
	}
	if (new_nbin <= 0) {
	  cout << "That is not a valid number of bins" << endl;
	  return -1;
	}
	command += " --setnbin ";
	command += optarg;
	break;
      case 203: {
	if (cbpao || cblpo || cblao) {
	  cerr << "You can only specify one re-ordering scheme!"
	       << endl;
	  return -1;
	}
	if (sscanf(optarg, "%ud", &ronsub) != 1) {
	  cerr << "Invalid nsub given" << endl;
	  return -1;
	}
	cbppo = true;
	break;
      } 
      case 204: {
	if (cbppo || cblpo || cblao) {
	  cerr << "You can only specify one re-ordering scheme!"
	       << endl;
	  return -1;
	}
	if (sscanf(optarg, "%ud", &ronsub) != 1) {
	  cerr << "Invalid nsub given" << endl;
	  return -1;
	}
	cbpao = true;
	break;
      }      
      case 205: {
	if (cblao || cbppo || cbpao) {
	  cerr << "You can only specify one re-ordering scheme!"
	       << endl;
	  return -1;
	}
	if (sscanf(optarg, "%ud", &ronsub) != 1) {
	  cerr << "Invalid nsub given" << endl;
	  return -1;
	}
	cblpo = true;
	break;
      } 
      case 206: {
	if (cblpo || cbppo || cbpao) {
	  cerr << "You can only specify one re-ordering scheme!"
	       << endl;
	  return -1;
	}
	if (sscanf(optarg, "%ud", &ronsub) != 1) {
	  cerr << "Invalid nsub given" << endl;
	  return -1;
	}
	cblao = true;
	break;
      }

      case 207: try {
	install_receiver = Pulsar::Receiver::load (optarg);
	break;
      }
      catch (Error& error) {
	cerr << "pam: Error loading Receiver from " << optarg << endl
	     << error.get_message() << endl;
	return -1;
      }

      case 208: {
	if (sscanf(optarg, "%f", &tsub) != 1) {
	  cerr << "Invalid tsub given" << endl;
	  return -1;
	}
	tscr = true;
	break;
      }

      case TYPE:
	{
	  string s = optarg;
	  if(s=="Pulsar")     new_type = Signal::Pulsar;
	  else if(s=="PolnCal")    new_type = Signal::PolnCal;
	  else if(s=="FluxCalOn")  new_type = Signal::FluxCalOn;
	  else if(s=="FluxCalOff") new_type = Signal::FluxCalOff;
	  else if(s=="Calibrator") new_type = Signal::Calibrator;
	  else{
	    fprintf(stderr,"Unrecognised argument to --type: '%s'\n",optarg);
	    exit(-1);
	  }
	  command += " --type " + s;
	}
	break;

      case INST: instrument = optarg; break;

      case REVERSE_FREQS: reverse_freqs = true; break;

      case SITE: site = optarg; break;

      case NAME: name = optarg; break;

      case DD: dededisperse = true; break;

      case RM:
        aux_rm = fromstring<double>(optarg);
        newrm = true;
        command += " --RM ";
        command += optarg;
        break;

      case SPC: scattered_power_correction = true; break;
	
      case MULT: mult = atof(optarg); break;

      case PERIOD: new_folding_period = fromstring<double>(optarg); break;

      case FLIP: flip_freq = true; flip_freq_mhz = atof(optarg); break;

      case UPDATE_DM: update_dm_from_eph = true; break;

      case AUX_RM:
        aux_rm = fromstring<double>(optarg);
        command += " --aux_rm ";
        command += optarg;
        break;

      default:
	cout << "Unrecognised option" << endl;
      }
    }

   if (verbose)
     cerr << "pam: parsing filenames" << endl;
 
   vector <string> filenames;

    if (metafile)
      stringfload (&filenames, metafile);
    else
      for (int ai=optind; ai<argc; ai++)
        dirglob (&filenames, argv[ai]);
 
    if (filenames.empty())
    {
      cerr << "pam: no filenames were specified" << endl;
      exit(-1);
    } 
  
    Reference::To<Pulsar::Archive> arch;

    if (!save)
    {
      cout << "Changes will not be saved. Use -m, -u or -e to write results to disk"
	   << endl;
    }

    if (stokesify && unstokesify)
    {
      cerr << "pam: Both -S and --SS options were given.  Poln state will not be changed!" << endl;
      stokesify = false;
      unstokesify = false;
    }

    int flip_option_count=0;
    if (flipsb) flip_option_count++;
    if (flip_freq) flip_option_count++;
    if (reverse_freqs) flip_option_count++;
    if (flip_option_count > 1) {
      cerr << "pam: More than one band-flip option was given, exiting." << endl;
      exit(-1);
    }

    for (unsigned i = 0; i < filenames.size(); i++) try
    {
      if (verbose)
	cerr << "Loading " << filenames[i] << endl;
      
      arch = Pulsar::Archive::load(filenames[i]);

      if( mult > 0.0 ){
	for( unsigned isub=0; isub<arch->get_nsubint();isub++)
	  for( unsigned ichan=0; ichan<arch->get_nchan();ichan++)
	    for( unsigned ipol=0; ipol<arch->get_npol();ipol++)
	      arch->get_Profile(isub,ipol,ichan)->scale( mult );
      }

      if( new_folding_period > 0.0 ){
	Pulsar::counter_drift( arch, new_folding_period, 0.0);
	for( unsigned isub=0; isub<arch->get_nsubint();isub++)
	  arch->get_Integration(isub)->set_folding_period( new_folding_period );
      }

      if (install_receiver) {
	if (verbose)
	  cerr << "pam: Installing receiver: " << install_receiver->get_name()
	       << " in archive" << endl;

	arch->add_extension (install_receiver);
      }

      if (lin || circ) {
	Pulsar::Receiver* receiver = arch->get<Pulsar::Receiver>();

	if (!receiver)
	  cerr << "No Receiver Extension in " << filenames[i] << endl;
	else {
	  if (lin) {
	    receiver->set_basis (Signal::Linear);
	    cout << "Feed basis set to Linear" << endl;
	  }

	  if (circ) {
	    receiver->set_basis (Signal::Circular);
	    cout << "Feed basis set to Circular" << endl;
	  }
	}
      }

      reflections.transform( arch );

      if (new_cfreq)
      {
	double nc = arch->get_nchan();
	double bw = arch->get_bandwidth();
	double cw = bw / nc;

	double fr = new_fr - (bw / 2.0) + (cw / 2.0);
	
	for (unsigned i = 0; i < arch->get_nsubint(); i++) {
	  for (unsigned j = 0; j < arch->get_nchan(); j++) {
	    arch->get_Integration(i)->set_centre_frequency(j,(fr + (j*cw)));
	  }
	}
	
	arch->set_centre_frequency(new_fr);
      }

      if( new_type != Signal::Unknown )
	arch->set_type( new_type );

      if( instrument != string() ){
	Pulsar::Backend* b = arch->get<Pulsar::Backend>();
	if( !b )
	  fprintf(stderr,"Could not change instrument name- archive does not have Backend extension\n");
	else
	  b->set_name(instrument);
      }

      if( site != string() )
	arch->set_telescope( site );

      if( name != string() )
	arch->set_source( name );

      if (new_eph) try
      {
        arch->set_ephemeris(new_eph);

        if (update_dm_from_eph) {
          update_dm(arch);
        }
      }
      catch (Error& error)
      {
	cerr << "Error while installing new ephemeris: " 
	     << error.get_message() << endl;
        continue;
      }

      if (flipsb) {
	for (unsigned i = 0; i < arch->get_nsubint(); i++) {
	  vector<double> labels;
	  labels.resize(arch->get_nchan());
	  for (unsigned j = 0; j < arch->get_nchan(); j++) {
	    labels[j] = arch->get_Integration(i)->get_centre_frequency(j);
	  }
	  for (unsigned j = 0; j < arch->get_nchan(); j++) {
	    double new_frequency = labels[labels.size()-1-j];
	    arch->get_Integration(i)->set_centre_frequency(j,new_frequency);
	  }
	}
	arch->set_bandwidth(-1.0 * arch->get_bandwidth());
      }

      if (flip_freq) {
        for (unsigned isub = 0; isub < arch->get_nsubint(); isub++) {
          Reference::To<Pulsar::Integration> 
            subint = arch->get_Integration(isub);
          for (unsigned ichan = 0; ichan < arch->get_nchan(); ichan++) {
            double new_freq = flip_freq_mhz 
              - (subint->get_centre_frequency(ichan) - flip_freq_mhz);
            subint->set_centre_frequency(ichan, new_freq);
          }
        }
        arch->set_bandwidth(-1.0 * arch->get_bandwidth());
      }

      if( reverse_freqs ) {
	// Of course it would be nice to do this with pointers.... but oh well I guess copying will have to do HSK 27/8/04

	unsigned nchan = arch->get_nchan();

	for( unsigned isub=0; isub<arch->get_nsubint(); isub++){
	  for( unsigned ipol =0; ipol<arch->get_npol(); ipol++){
	    for( unsigned ichan=0; ichan<nchan/2; ichan++){
	      Reference::To<Pulsar::Profile> lo = arch->get_Profile(isub,ipol,ichan);	      
	      Reference::To<Pulsar::Profile> tmp = lo->clone();

	      Reference::To<Pulsar::Profile> hi = arch->get_Profile(isub,ipol,nchan-1-ichan);

	      lo->operator=(*hi);
	      hi->operator=(*tmp);
	    }
	  }
	}
	arch->set_bandwidth( -1.0 * arch->get_bandwidth() );
      }

      if (reset_weights) {
	arch->uniform_weight(new_weight);
	if (verbose)
	  cout << "All profile weights set to " << new_weight << endl;
      }
      
      if (rotate)
	arch->rotate_phase (rphase);

      if (scattered_power_correction) {

	Pulsar::ScatteredPowerCorrection spc;
	if (arch->get_state() == Signal::Stokes)
	  arch->convert_state(Signal::Coherence);

	spc.correct (arch);

      }

      if (newdm)
      {
	arch->set_dispersion_measure(dm);
	if (verbose)
	  cout << "Archive dispersion measure set to " << dm << endl;

	if (arch->get_dedispersed())
        {
	  arch->dedisperse();

	  if (verbose)
	    cout << "Archive re-dedipsersed" << endl;
        }
      }

      if (dedisperse)
      {
	arch->dedisperse();
	if (verbose)
	  cout << "Archive dedipsersed" << endl;
      }

      if (dededisperse)
      {
	Pulsar::Dispersion correction;
	correction.revert (arch);
      }

      if (stokesify) {
	if (arch->get_npol() != 4)
	  throw Error(InvalidState, "Convert to Stokes",
		      "Not enough polarisation information");
	arch->convert_state(Signal::Stokes);
	if (verbose)
	  cout << "Archive converted to Stokes parameters" << endl;
      }

      if (unstokesify) {
	if (arch->get_npol() != 4)
	  throw Error(InvalidState, "Convert to coherence",
		      "Not enough polarisation information");
	arch->convert_state(Signal::Coherence);
	if (verbose)
	  cout << "Archive converted to coherence parameters" << endl;
      }

      if (cbppo) {
	myio = new Pulsar::PeriastronOrder();
	arch->add_extension(myio);
	myio->organise(arch, ronsub);
      }
      
      if (cbpao) {
	myio = new Pulsar::BinaryPhaseOrder();
	arch->add_extension(myio);
	myio->organise(arch, ronsub);
      }
      
      if (cblpo) {
	myio = new Pulsar::BinLngPeriOrder();
	arch->add_extension(myio);
	myio->organise(arch, ronsub);
      }
      
      if (cblao) {
	myio = new Pulsar::BinLngAscOrder();
	arch->add_extension(myio);
	myio->organise(arch, ronsub);
      }
      
      if( subint_extract_start >= 0 && subint_extract_end >= 0 ) {
	vector<unsigned> subints;
	unsigned isub = subint_extract_start;

	while ( isub<arch->get_nsubint() && isub<unsigned(subint_extract_end) ) {
	  subints.push_back( isub );
	  isub++;
	}

	Reference::To<Pulsar::Archive> extracted( arch->extract(subints) );
	extracted->set_filename( arch->get_filename() );

	arch = extracted;
      }

      if (tscr) {
	if (tsub > 0.0) {
	  unsigned factor = 
	    unsigned (tsub / arch->get_Integration(0)->get_duration());
	  if (factor == 0) {
	    cerr << "Warning: subints already too long" << endl;
	  }
	  else {
	    arch->tscrunch(factor);
	  }
	  if (verbose)
	    cout << arch->get_filename() << " tscrunched by a factor of " 
		 << factor << endl;
	}
	else if (new_nsub > 0) {
	  arch->tscrunch_to_nsub(new_nsub);
	  if (verbose)
	    cout << arch->get_filename() << " tscrunched to " 
		 << new_nsub << " subints" << endl;
	}
	else if (tscr_fac > 0) {
	  arch->tscrunch(tscr_fac);
	  if (verbose)
	    cout << arch->get_filename() << " tscrunched by a factor of " 
		 << tscr_fac << endl;
	}
	else {
	  arch->tscrunch();
	  if (verbose)
	    cout << arch->get_filename() << " tscrunched" << endl;
	}
      }
      
      if (pscr) {
	arch->pscrunch();
	if (verbose)
	  cout << arch->get_filename() << " pscrunched" << endl;
      } 

      if (invint) {
	arch->invint();
	if (verbose)
	  cout << arch->get_filename() << " invinted" << endl;
      }

      if (newrm) {
	arch->set_rotation_measure (rm);
	if (verbose)
	  cout << arch->get_filename() << " RM set to " << rm << endl;
      }

      if (defaraday) {
	arch->defaraday();
	if (verbose)
	  cout << arch->get_filename() << " defaradayed" <<endl;
      }

      if (aux_rm)
      {
	if (verbose)
	  cout << "pam: correct auxiliary Faraday rotation; iono RM="
	       << aux_rm << endl;
	correct_auxiliary_rm (arch, aux_rm);
      }

      if (fscr) {
	if (new_nchn > 0) {
	  arch->fscrunch_to_nchan(new_nchn);
	  if (verbose)
	    cout << arch->get_filename() << " fscrunched to " 
		 << new_nchn << " channels" << endl;
	}
	else if (fscr_fac > 0) {
	  arch->fscrunch(fscr_fac);
	  if (verbose)
	    cout << arch->get_filename() << " fscrunched by a factor of " 
		 << fscr_fac << endl;
	}
	else {
	  arch->fscrunch();
	  if (verbose)
	    cout << arch->get_filename() << " fscrunched" << endl;
	}
      }

      if (bscr) {
	if (new_nbin > 0) {
	  arch->bscrunch_to_nbin(new_nbin);
	  if (verbose)
	    cout << arch->get_filename() << " bscrunched to " 
		 << new_nbin << " bins" << endl;
	}
	else {
	  arch->bscrunch(bscr_fac);
	  if (verbose)
	    cout << arch->get_filename() << " bscrunched by a factor of " 
		 << bscr_fac << endl;
	}
      }     

      if (smear_dc) {
	for (unsigned i = 0; i < arch->get_nsubint(); i++) {
	  for (unsigned j = 0; j < arch->get_npol(); j++) {
	    for (unsigned k = 0; k < arch->get_nchan(); k++) {
	      smear (arch->get_Profile(i,j,k), smear_dc);
	    }
	  }
	}
      }
      
      if (save) {

	if (archive_class)  {

	  // unload an archive of the specified class
	  Reference::To<Pulsar::Archive> output;
	  output = Pulsar::Archive::new_Archive (archive_class);
	  output -> copy (*arch);
	  output -> set_filename ( arch->get_filename() );

	  arch = output;

	}


	// See if the archive contains a history that should be updated:
	
	Pulsar::ProcHistory* fitsext = arch->get<Pulsar::ProcHistory>();
	
	if (fitsext) {
	  
	  if (command.length() > 80) {
	    cout << "WARNING: ProcHistory command string truncated to 80 chars" 
		 << endl;
	    fitsext->set_command_str(command.substr(0, 80));
	  }
	  else {
	    fitsext->set_command_str(command);
	  }
	  
	}
	
	string out_filename = arch->get_filename();
	
	if( !ext.empty() )
	  out_filename = replace_extension( out_filename, ext );
	
	if( !ulpath.empty() )
	  out_filename = ulpath + basename(out_filename);
	
	arch->unload( out_filename );
	cout << out_filename << " written to disk" << endl;
      }
    }  
    catch (Error& error) {
      cerr << error << endl;
    } 
  
    return 0;

}
catch(Error& er) 
{
  cerr << er << endl;
  return -1;
}
catch (string& error)
{
  cerr << "exception thrown: " << error << endl;
  return -1;
}
catch (bad_alloc& ba)
{
  cerr << "Caught a bad_alloc: '" << ba.what() << "'" << endl ;
  return -1;
}
catch (exception& e)
{
  cerr << "caught an exception of type '" 
				 << typeid(e).name() << "'" << endl; 
  return -1;
}
catch(...)
{
  fprintf(stderr,"Unknown exception caught\n");
  return -1;
}
예제 #5
0
파일: paas.C 프로젝트: lbaehren/lofarsoft
int main (int argc, char** argv) try
{
  // the multiple component model
  ComponentModel model;

  string model_filename_in;
  string model_filename_out = "paas.m";
  string details_filename   = "paas.txt";
  string std_filename       = "paas.std";

  bool fit = false;
  vector<string> new_components;
  string fit_flags;

  int bscrunch = 1;

  string pgdev;

  bool line_plot=false;
  bool interactive = false;
  bool centre_model = false, rotate_peak=false;
  float rotate_amount = 0.0;
  bool align = false;

  const char* args = "hb:r:w:c:fF:it:d:Dl:j:Ws:CpR:a";
  int c;

  while ((c = getopt(argc, argv, args)) != -1)
    switch (c) {

    case 'h':
      usage ();
      return 0;

    case 'r':
      model_filename_in = optarg;
      break;
      
    case 'w':
      model_filename_out = optarg;
      break;
      
    case 'f':
      fit = true;
      break;

    case 'W':
      model.set_fit_derivative (true);
      break;

    case 'c':
      new_components.push_back(optarg);
      break;

    case 'F':
      fit_flags = optarg;
      break;

    case 'b':
      bscrunch = atoi (optarg);
      break;

    case 't':
      model.set_threshold( atof(optarg) );
      break;

    case 'd':
      pgdev = optarg;
      break;

    case 'i':
      interactive = true;
    case 'D':
      pgdev = "/xs";
      break;
      
    case 'l':
      line_plot = true;
      break;

    case 's':
      std_filename = optarg;
      break;

    case 'C':
      centre_model = true;
      break;

    case 'p':
      rotate_peak = true;
      break;

    case 'R':
      rotate_amount = atof(optarg);
      break;

    case 'a':
      align = true;
      break;

    case 'j':
      details_filename = optarg;
      break;

   default:
      cerr << "invalid param '" << c << "'" << endl;
    }

  if (!pgdev.empty())
  {
    cpgopen(pgdev.c_str());
    cpgask(0);
    cpgsvp(0.1, 0.9, 0.1, 0.9);
  }
  
  Reference::To<Archive> archive = Archive::load (argv[optind]);

  // preprocess
  archive->fscrunch();
  archive->tscrunch();
  archive->pscrunch();

  // phase up as requested
  if (centre_model)
    archive->centre();
  else if (rotate_peak)
    archive->centre_max_bin(0.0);
  
  if (rotate_amount != 0.0)
    archive->rotate_phase(-rotate_amount);
  
  archive->remove_baseline();

  // load from file if specified
  if (!model_filename_in.empty())
  {
    cerr << "paas: loading model from " << model_filename_in << endl;
    model.load(model_filename_in.c_str());
    
    // align to profile first if asked
    if (align)
      model.align(archive->get_Integration(0)->get_Profile(0,0));
  }

  // add any new components specified
  unsigned ic, nc=new_components.size();
  double centre, concentration, height;
  int name_start;
  for (ic=0; ic < nc; ic++)
  {
    if (sscanf(new_components[ic].c_str(), 
	       "%lf %lf %lf %n", &centre, &concentration, &height,
	       &name_start)!=3)
    {
      cerr << "Could not parse component " << ic << endl;
      return -1;
    }

    model.add_component(centre, concentration, height, 
			new_components[ic].c_str()+name_start);
  }

  bool iterate = true;

  while (iterate)
  {
    iterate = false;

    // fit if specified
    if (fit)
    {
      // set fit flags
      model.set_infit(fit_flags.c_str());
      // fit
      model.fit(archive->get_Integration(0)->get_Profile(0,0));
    }
 
    // plot
    if (!pgdev.empty())
    {
      Reference::To<Pulsar::Archive> scrunched;
      scrunched = archive->clone();
      if (bscrunch > 1)
	scrunched->bscrunch(bscrunch);

      cpgpage();

      Profile *prof = scrunched->get_Integration(0)->get_Profile(0,0);
      float ymin = prof->min();
      float ymax = prof->max();
      float extra = 0.05*(ymax-ymin);

      ymin -= extra;
      ymax += extra;
      cpgswin(0.0, 1.0, ymin, ymax);
      cpgbox("bcnst", 0, 0, "bcnst", 0, 0);
      cpglab("Pulse phase", "Intensity", "");
      unsigned i, npts=prof->get_nbin();
      cpgsci(14);
      for (ic=0; ic < model.get_ncomponents(); ic++)
	plot(model, npts, true, ic);
      vector<float> xvals(npts);
      cpgsci(4);
      for (i=0; i < npts; i++)
	xvals[i] = i/((double)npts);
      if (line_plot)
	cpgline(npts, &xvals[0], prof->get_amps());
      else
	cpgbin(npts, &xvals[0], prof->get_amps(), 0);
      cpgsci(2);
      plot_difference(model, prof, line_plot);
      cpgsci(1);
      plot(model, npts, true);
    }
    
    
    while (interactive)
    {
      iterate = true;
      fit = false;

      cerr << "Enter command ('h' for help)" << endl;

      float curs_x=0, curs_y=0;
      char key = ' ';
      if (cpgband(6,0,0,0,&curs_x, &curs_y, &key) != 1 || key == 'q')
      {
	cerr << "Quitting ..." << endl;
	iterate = false;
	break;
      }

      if (key == 'h')
      {
	cerr << 
	  "\n"
	  "left click - add a component at cursor position\n"
	  "f key      - fit current set of components\n"
	  "q key      - quit\n"
	  "\n"
	  "After left click:\n"
	  "   1) any key    - select width of new component, then \n"
	  "   2) any key    - select height of new component \n"
	  "\n"
	  "   right click or <Escape> to abort addition of new component \n"
	     << endl;
	continue;
      }
      
      if (key == 'f')
      {
	cerr << "Fitting components" << endl;
	fit = true;
	break;
      }
      
      if (key == 'a' || key == 65)
      {
	cerr << "Adding component centred at pulse phase " << curs_x << endl;
	double centre = curs_x;

	cerr << "Select width and hit any key" << endl;
	if (cpgband(4, 1, curs_x, curs_y, &curs_x, &curs_y, &key) != 1) {
	  cerr << "paas: cpgband error" << endl;
	  return -1;
	}
	
	// right click or escape to abort
	if (key == 88 || key == 27)
	  continue;
	
	double width = fabs(centre - curs_x);
	
	cerr << "Select height and hit any key" << endl;
	if (cpgband(5,0,0,0,&curs_x, &curs_y, &key) != 1) {
	  cerr << "paas: cpgband error" << endl;
	  return -1;
	}
	
	// right click or escape to abort
	if (key == 88 || key == 27)
	  continue;
	
	double height = curs_y;
	
	model.add_component (centre, 0.25/(width*width), height, "");
	
	break;
	
      }
      
      cerr << "Unrecognized command" << endl;
      
    }
    
  }
  
  // write out if specified
  if (!model_filename_out.empty())
  {
    cerr << "paas: writing model to " << model_filename_out << endl;
    model.unload (model_filename_out.c_str());
  }
  
  Reference::To<Pulsar::Archive> copy = archive->clone();

  // write out standard
  model.evaluate (archive->get_Integration(0)->get_Profile(0,0)->get_amps(),
		  archive->get_nbin());

  write_details_to_file (model, copy, archive, details_filename);
  
  cerr << "paas: writing standard to " << std_filename << endl;
  archive->unload (std_filename);

  if (!pgdev.empty())
    cpgend();

  return 0;
}
catch (Error& error)
{
  cerr << error << endl;
  return -1;
}
예제 #6
0
void Pulsar::PolnSpectrumStats::build () try
{
  if (!profile)
    return;

  fourier = fourier_transform (profile, plan);

  // convert to Stokes parameters and drop the Nyquist bin
  fourier->convert_state (Signal::Stokes);
  fourier->resize( profile->get_nbin() );

  // form the power spectral density
  Reference::To<PolnProfile> psd = fourier_to_psd (fourier);

  // separate fourier into real and imaginary components
  Reference::To<PolnProfile> re = psd->clone();
  Reference::To<PolnProfile> im = psd->clone();

  unsigned npol = 4;
  unsigned nbin = psd -> get_nbin();

  for (unsigned ipol=0; ipol < npol; ipol++)
  {
    float* C_ptr = fourier->get_Profile(ipol)->get_amps();
    float* re_ptr = re->get_Profile(ipol)->get_amps();
    float* im_ptr = im->get_Profile(ipol)->get_amps();

    for (unsigned ibin=0; ibin < nbin; ibin++)
    {
      re_ptr[ibin] = C_ptr[ibin*2];
      im_ptr[ibin] = C_ptr[ibin*2+1];
    }
  }

  if (!regions_set)
  {
    LastHarmonic last;
    last.set_Profile( psd->get_Profile(0) );

    last.get_weight (&onpulse);
    last.get_baseline_estimator()->get_weight (&baseline);

    last_harmonic = last.get_last_harmonic();

#ifdef _DEBUG
    cerr << "Pulsar::PolnSpectrumStats::build last harmonic=" 
	 << last_harmonic << " nbin on=" << onpulse.get_weight_sum() << endl;
#endif

    real->set_regions (onpulse, baseline);
    imag->set_regions (onpulse, baseline);
  }

  if (onpulse.get_nbin () != re->get_nbin())
  {
    PhaseWeight on_temp = onpulse;
    PhaseWeight off_temp = baseline;

    on_temp.resize( re->get_nbin() );
    off_temp.resize( re->get_nbin() );

    if (re->get_nbin() > onpulse.get_nbin ())
    {
      copy_pad( on_temp, onpulse, 0 );
      copy_pad( off_temp, baseline, 1 );
    }

    real->set_regions (on_temp, off_temp);
    imag->set_regions (on_temp, off_temp);
  }

  real->set_profile (re.release());
  imag->set_profile (im.release());

}
catch (Error& error)
{
  throw error += "Pulsar::PolnSpectrumStats::build";
}
예제 #7
0
int main(int argc, char* argv[]) try
{
  if (argc < 2) {
    usage();
    return EXIT_SUCCESS;
  }
  
  int gotc = 0;
  while ((gotc = getopt(argc, argv, "hvV")) != -1) {
    switch (gotc) {
    case 'h':
      usage();
      return EXIT_SUCCESS;
    case 'V':
      Pulsar::Archive::set_verbosity(3);
      break;
    case 'v':
      Pulsar::Archive::set_verbosity(2);
      break;
    }
  }
  
  if (optind >= argc)
    {
      cerr << "pazi: please specify filename" << endl;
      return -1;
    }
  
  string filename = argv[optind];
  string extension = filename.substr(filename.length() - 2, 2);
  
  if (extension == "rf")
    extension = "rz";
  else if (extension == "cf")
    extension = "cz";
  else
    extension = "pazi";
  
  string write_filename = filename + ".";
  write_filename += extension;
  
  cerr << "pazi: loading data" << endl;
  base_archive = Archive::load(filename);
  
  if (base_archive->get_npol() == 4)
  {
    original_state = base_archive->get_state();
    base_archive->convert_state( Signal::Stokes );
  }
  
  backup_archive = base_archive->clone();
  
  cerr << "pazi: making fscrunched clone" << endl;
  mod_archive = base_archive->clone();
  mod_archive->pscrunch();
  mod_archive->remove_baseline();
  mod_archive->dedisperse();
  mod_archive->fscrunch();

  scrunched_archive = mod_archive->clone();
  scrunched_archive->tscrunch();

  ranges.second = get_max_value(base_archive, plot_type);
  positive_direction = base_archive->get_bandwidth() < 0.0;

  time_orig_plot = factory.construct("time");
  time_mod_plot = factory.construct("time");
  time_fui = time_mod_plot->get_frame_interface();

  freq_orig_plot = factory.construct("freq");
  freq_mod_plot = factory.construct("freq");
  freq_fui = freq_mod_plot->get_frame_interface();

  total_plot = factory.construct("flux");
  total_plot->configure("info=1");

  subint_orig_plot = new ProfilePlot;
  subint_mod_plot = new ProfilePlot;
  subint_fui = subint_mod_plot->get_frame_interface();

  subint_orig_plot->configure("info=1");
  subint_mod_plot->configure("info=1");

  unsigned window = 0;
  char device [8];

  for (unsigned i=0; i<2; i++) do {
    window ++;
    snprintf (device, 8, "%u/XS", window);
  }
  while ( cpgopen (device) < 0 );

  cpgask(0);

  cerr << endl << "Total S/N = " <<
    scrunched_archive->get_Profile(0,0,0)->snr() << endl << endl;

  total_plot->plot(scrunched_archive);
  cpgslct(1);
  time_orig_plot->plot(mod_archive);

  do
  {
    cpgswin(0, 1, 0, 1);

    // plot:
    //   frequency = horizontal mouse band
    //   time      = horizontal mouse band
    //   profile   = vertical mouse band

    int band = 0;

    if (prune_start != UNDEF_MOUSE)
    {
      band = BOX_ANCHOR;
      mouse_ref = prune_start;
    }
    else if (mouse_ref != UNDEF_MOUSE)
    {
      if (plot_type == FscrunchedSubint)
	band = VERTICAL_ANCHOR;
      else
	band = HORIZONTAL_ANCHOR;
    }
    else
    {
      if (plot_type == FscrunchedSubint)
	band = VERTICAL_LINE;
      else
	band = HORIZONTAL_LINE;
    }


    cpgband(band, 0, mouse_ref.first, mouse_ref.second, &(mouse.first),
	    &(mouse.second), &ch);

    switch (ch)
    {

    case 'A': // zoom
      {
	constrain_range(mouse.first);
	constrain_range(mouse.second);

	if (mouse_ref == UNDEF_MOUSE)
        {
	  mouse_ref = mouse;
	  continue;
	}


	// store the current range so it can be restored if the user selects
	// a zoom region too small
	const RangeType old_ranges = ranges;
	bool horizontal = plot_type == FscrunchedSubint ? false : true;
	ranges = get_range(mouse_ref, mouse, ranges, horizontal);

	// ignore mouse clicks if the index values are too close (< 1)
	if (ranges.first == ranges.second) {
	  ranges = old_ranges;
	  break;
	}

	zoomed = true;

	const unsigned max_value = get_max_value(base_archive, plot_type);
	const string zoom_option = get_zoom_option(ranges, max_value);

	switch (plot_type) {
	case PhaseVsTime:
	  time_fui->set_value("y:range", zoom_option);
	  redraw(mod_archive, time_orig_plot, time_mod_plot, zoomed);
	  break;
	case PhaseVsFrequency:
	  freq_fui->set_value("y:range", zoom_option);
	  freq_redraw(mod_archive, base_archive, freq_orig_plot,
		      freq_mod_plot, zoomed);
	  break;
	case FscrunchedSubint:
	  subint_fui->set_value("x:range", zoom_option);
	  redraw(mod_archive, subint_orig_plot, subint_mod_plot, zoomed);
	  break;
	}
      }
      break; // case 'A'
    case 'h':
      usage();
      break;

    case 'b': // plot specific subint
      if (plot_type == PhaseVsTime) {
	plot_type = FscrunchedSubint;
	zoomed = false;

	*mod_archive = *base_archive;
	mod_archive->set_dispersion_measure(0);
	mod_archive->fscrunch();
	mod_archive->pscrunch();
	mod_archive->remove_baseline();

	subint = get_indexed_value(mouse);

	ranges.first = 0;
	ranges.second = get_max_value(base_archive, plot_type);

	char add[3];
	sprintf(add, "%d", subint);
	string subint_option = "subint=";
	subint_option += add;

	subint_orig_plot->configure(subint_option);
	subint_mod_plot->configure(subint_option);

	cpgeras();
	subint_orig_plot->plot(mod_archive);
	update_total(scrunched_archive, base_archive, total_plot);
      }
      break;

      /*case 'c': // center pulse
	set_centre(mod_archive, base_archive, centered, plot_type, dedispersed);

	if (plot_type == "freq")
	redraw(mod_archive, freq_orig_plot, freq_mod_plot, zoomed);
	else if (plot_type == "time")
	redraw(mod_archive, time_orig_plot, time_mod_plot, zoomed);

	update_total(scrunched_archive, base_archive, total_plot);
	break;*/

    case 'd': // toggle dedispersion on/off
      set_dedispersion(mod_archive, base_archive, dedispersed);

      if (plot_type == PhaseVsFrequency) {
	mod_archive->tscrunch();
	redraw(mod_archive, freq_orig_plot, freq_mod_plot, zoomed);
      } else if (plot_type == PhaseVsTime) {
	mod_archive->fscrunch();
	redraw(mod_archive, time_orig_plot, time_mod_plot, zoomed);
      }

      update_total(scrunched_archive, base_archive, total_plot);
      break;

    case 'f': // frequency plot
      plot_type = PhaseVsFrequency;
      ranges.first = 0;
      ranges.second = get_max_value(base_archive, plot_type);
      zoomed = false;
      freq_redraw(mod_archive, base_archive, freq_orig_plot, freq_mod_plot, zoomed);
      break;

    case 'm':

      if (plot_type != FscrunchedSubint)
      {
	cerr << "pazi: can only mow lawn in binzap-subint mode" << endl;
	continue;
      }

      cerr << "pazi: mowing lawn" << endl;
      mowlawn (mod_archive, base_archive, subint);

      cerr << "pazi: replotting" << endl;
      redraw(mod_archive, subint_orig_plot, subint_mod_plot, zoomed);
      cerr << "pazi: updating total" << endl;
      update_total(scrunched_archive, base_archive, total_plot);

      break;

    case 'x': // prune

      if (plot_type != FscrunchedSubint)
      {
	cerr << "pazi: can only prune hedge in binzap-subint mode" << endl;
	continue;
      }

      constrain_range(mouse.first);
      constrain_range(mouse.second);

      if (prune_start == UNDEF_MOUSE)
      {
	prune_start = mouse;
	continue;
      }

      prune_end = mouse;

      cerr << "pazi: pruning hedge" << endl;
      prune_hedge (mod_archive, base_archive, subint);

      cerr << "pazi: replotting" << endl;
      redraw(mod_archive, subint_orig_plot, subint_mod_plot, zoomed);
      cerr << "pazi: updating total" << endl;
      update_total(scrunched_archive, base_archive, total_plot);

      break;

    case 'o': // toggle frequency scrunching on/off
      if (plot_type == PhaseVsTime)
      {
	if (fscrunched) {
	  fscrunched = false;
	  *mod_archive = *base_archive;
	}
	else {
	  fscrunched = true;
	  mod_archive->fscrunch();
	}
	redraw(mod_archive, time_orig_plot, time_mod_plot, zoomed);
      }
      break;

    case 'q': // quit
      cpgclos();
      return EXIT_SUCCESS;

    case 'p':
      print_command(channels_to_zap, subints_to_zap, extension, filename);
      break;

    case 'r': // reset zoom
      zoomed = false;
      ranges.first = 0;
      ranges.second = get_max_value(base_archive, plot_type);

      switch (plot_type) {
      case PhaseVsTime:
	redraw(mod_archive, time_orig_plot, time_mod_plot, zoomed);
	break;
      case PhaseVsFrequency:
	freq_redraw(mod_archive, base_archive, freq_orig_plot,
		    freq_mod_plot, zoomed);
	break;
      case FscrunchedSubint:
	redraw(mod_archive, subint_orig_plot, subint_mod_plot, zoomed);
	break;
      }
      break;

    case 's': // save current archive changes:
      {
	Pulsar::ProcHistory* ext = base_archive->get<Pulsar::ProcHistory>();
	if (ext) {
	  ext->set_command_str("pazi");
	}

	if ( base_archive->get_npol() == 4 )
	  base_archive->convert_state( original_state );
	base_archive->unload(write_filename);
	if ( base_archive->get_npol() == 4 )
	  base_archive->convert_state( Signal::Stokes );
	break;
      }

    case 't': // time plot
      plot_type = PhaseVsTime;
      ranges.first = 0;
      ranges.second = get_max_value(base_archive, plot_type);
      zoomed = false;
      time_redraw(mod_archive, base_archive, time_orig_plot, time_mod_plot, zoomed);
      break;

    case 'u': // undo last change

      if (mouse_ref != UNDEF_MOUSE) {
	mouse_ref = UNDEF_MOUSE;
	continue;
      }

      switch (plot_type) {
      case PhaseVsTime:
	{
	  const unsigned value = get_indexed_value(mouse);
	  remove_channel(value, subints_to_zap);
	  time_unzap_subint(base_archive, backup_archive, value);
	  time_redraw(mod_archive, base_archive, time_orig_plot,
		      time_mod_plot, zoomed);
	}
	break;
      case PhaseVsFrequency:
	{
	  const unsigned value = get_indexed_value(mouse);
	  remove_channel(value, channels_to_zap);
	  freq_unzap_chan(base_archive, backup_archive, value);
	  freq_redraw(mod_archive, base_archive, freq_orig_plot,
		      freq_mod_plot, zoomed);
	}
	break;
      case FscrunchedSubint:
	if (bins_to_zap.size()) {
	  bins_to_zap.erase(bins_to_zap.end() - 5, bins_to_zap.end());

	  *base_archive = *backup_archive;
	  *mod_archive = *backup_archive;

	  mod_archive->set_dispersion_measure(0);
	  mod_archive->pscrunch();
	  mod_archive->fscrunch();
	  mod_archive->remove_baseline();
	  redraw(mod_archive, subint_orig_plot, subint_mod_plot, zoomed);
	}
	break;
      }
      update_total(scrunched_archive, base_archive, total_plot);
      break;

    case 'z':
    case 'X': // zap single channel

      if (mouse_ref == UNDEF_MOUSE)
	zap_single ();
      else
	zap_multiple ();

      break;
    }

    prune_start = UNDEF_MOUSE;
    mouse_ref = UNDEF_MOUSE;

  } while (ch != 'q');

  return 0;

 } // end main

 catch (Error& error) {
   cerr << "pazi: " << error << endl;
   return -1;
 }