Exemplo n.º 1
0
void dsp::TimeDivide::set_start_time (MJD _start_time)
{
  if (start_time == _start_time)
    return;

  if (Operation::verbose)
    cerr << "dsp::TimeDivide::set_start_time start_time=" 
         << _start_time.printall() << endl;

  start_time = _start_time;
  start_phase = Pulsar::Phase::zero;
  is_valid = false;

  if( reference_epoch != MJD::zero )
  {
    if (Operation::verbose)
      cerr << "dsp::TimeDivide::set_start_time set to reference_epoch=" 
           << reference_epoch.printall() << endl;

    start_time = reference_epoch;
  }
  else if( division_seconds && division_seconds == unsigned(division_seconds) )
  {
    unsigned integer_seconds = unsigned(division_seconds);
    unsigned seconds = start_time.get_secs();
    unsigned divisions = seconds / integer_seconds;
    start_time = MJD (start_time.intday(), divisions * integer_seconds, 0.0);

    if (Operation::verbose)
      cerr << "dsp::TimeDivide::set_start_time rounded start_time=" 
           << _start_time.printall() << endl;
  }
}
Exemplo n.º 2
0
//! Get the mid-time of the integration
MJD dsp::PhaseSeries::get_mid_time (bool phased) const
{
  if (verbose)
  {
    cerr << "PhaseSeries::get_mid_time start=" 
      << start_time << " end=" << end_time << endl;
  }

  MJD midtime = 0.5 * (start_time + end_time);

  if (!phased)
    return midtime;

  if (folding_predictor)
  {
    // truncate midtime to the nearest pulse phase = reference_phase
    Pulsar::Phase phase = folding_predictor->phase(midtime).Floor() + reference_phase;
    midtime = folding_predictor->iphase (phase, &midtime);
  }

  if (folding_period)
  {
    double phase = reference_phase + 
      fmod (midtime.in_seconds(), folding_period)/folding_period;
    midtime -= phase * folding_period;
  }

  return midtime;
}
Exemplo n.º 3
0
//! convert an MJD to long double
long double from_MJD (const MJD& t)
{
  const long double secs_in_day = 86400.0L;

  return 
    (long double) (t.intday()) +
    (long double) (t.get_secs()) / secs_in_day +
    (long double) (t.get_fracsec()) / secs_in_day;
}
Exemplo n.º 4
0
void qt_MJD::value_Entered_CB ()
{
  MJD newval;
  if (newval.Construct (value.text().ascii()) < 0) {
    if (MJD::verbose)
      std::cerr << "qt_MJD:: invalid mjd:" << value.text() << std::endl;
    newval = valset;
  }
  setMJD (newval);
}
Exemplo n.º 5
0
//! Return the phase, given the epoch
Phase Tempo2::Predictor::phase (const MJD& t) const
{
  if (verbose)
    cerr << "Tempo2::Predictor::phase epoch=" << t << " frequency=" 
	 << observing_frequency << endl;

  if (observing_frequency <= 0)
    Error error (InvalidState, "Tempo2::Predictor::phase",
		 "observing_frequency=%lf", (double) observing_frequency);

  long double p = T2Predictor_GetPhase ( &predictor, from_MJD (t),
					 observing_frequency );

  if (ChebyModelSet_OutOfRange)
    throw Error (InvalidParam, "Tempo2::Predictor::phase",
		 "epoch %s not spanned by ChebyModelSet",
		 t.printdays(20).c_str());

  if (!finite(p)) {
    Error error (InvalidState, "Tempo2::Predictor::phase",
		 "T2Predictor_GetPhase result = ");
    error << p;
    throw error;
  }

  return to_Phase( p );
}
Exemplo n.º 6
0
//! Return the spin frequency, given the epoch
long double Pulsar::SimplePredictor::frequency (const MJD& t) const
{
  if (reference_epoch == MJD::zero)
     const_cast<SimplePredictor*>(this)->reference_epoch = t;

  MJD diff = t - reference_epoch;
  long double seconds = diff.get_secs();
  seconds += diff.get_fracsec();

  long double power_of_t = 1.0;
  long double result = 0;

  for (unsigned i=0; i<coefs.size(); i++)
  {
    result += coefs[i] * (i+1) * power_of_t;
    power_of_t *= seconds;
  }

  return result;
}
Exemplo n.º 7
0
//! Return the spin frequency, given the epoch
long double Tempo2::Predictor::frequency (const MJD& t) const
{
  long double f = T2Predictor_GetFrequency (&predictor, from_MJD (t),
					    observing_frequency);

  if (ChebyModelSet_OutOfRange)
    throw Error (InvalidParam, "Tempo2::Predictor::frequency",
		 "epoch %s not spanned by ChebyModelSet",
		 t.printdays(20).c_str());

  return f;
}
Exemplo n.º 8
0
//! Return the phase, given the epoch
Pulsar::Phase Pulsar::SimplePredictor::phase (const MJD& t) const
{
  if (reference_epoch == MJD::zero)
    const_cast<SimplePredictor*>(this)->reference_epoch = t;

  MJD diff = t - reference_epoch;
  long double seconds = diff.get_secs();
  seconds += diff.get_fracsec();

  long double power_of_t = seconds;
  long double result = 0;

  for (unsigned i=0; i<coefs.size(); i++)
  {
    result += coefs[i] * power_of_t;
    power_of_t *= seconds;
  }

  int64_t iphase = int64_t(result);

  return Pulsar::Phase(iphase,result-iphase);
}
Exemplo n.º 9
0
MJD dsp::LoadToFold::parse_epoch (const std::string& epoch_string)
{
  MJD epoch;

  if (epoch_string == "start")
  {
    epoch = manager->get_info()->get_start_time();
    epoch += manager->get_input()->tell_seconds();

    if (Operation::verbose)
      cerr << "dsp::LoadToFold::parse reference epoch=start_time=" 
	   << epoch.printdays(13) << endl;
  }
  else if (!epoch_string.empty())
  {
    epoch = MJD( epoch_string );
    if (Operation::verbose)
      cerr << "dsp::LoadToFold::parse reference epoch="
	   << epoch.printdays(13) << endl;
  }

  return epoch;
}
Exemplo n.º 10
0
//! Seek to a sample close to the specified MJD
void dsp::Input::seek(MJD mjd)
{
  int misplacement = 0;

  if (mjd+1.0/get_info()->get_rate() < get_info()->get_start_time())
    misplacement = -1;

  if (mjd-1.0/get_info()->get_rate() > get_info()->get_end_time())
    misplacement = 1;

  double seek_seconds = (mjd-get_info()->get_start_time()).in_seconds();

  if (misplacement)
  {
    string msg = "The given MJD (" + mjd.printall() + ") is ";
    if (misplacement < 0)
      msg += "before the start time";
    else
      msg += "after the end time";
    msg += "of the input data "
           "(" + get_info()->get_start_time().printall() + "); "
           "difference is %lf seconds";

    throw Error (InvalidParam, "dsp::Input::seek", msg.c_str(), seek_seconds);
  }
 
  double seek_samples = seek_seconds*get_info()->get_rate();
  uint64_t actual_seek = 0;

  if( seek_samples<0.0 )
    actual_seek = 0;
  else if( uint64_t(seek_samples) > get_info()->get_ndat() )
    actual_seek = get_info()->get_ndat();
  else
    actual_seek = uint64_t(seek_samples);

  if( verbose )
    fprintf(stderr,"dsp::Input::seek(MJD) will seek %f = "UI64" samples\n",
	    seek_samples, actual_seek);

  seek( actual_seek, SEEK_SET );
}
Exemplo n.º 11
0
std::string dsp::FilenameEpoch::get_filename (const PhaseSeries* data)
{
  MJD epoch = data->get_start_time();

  if (Observation::verbose)
    cerr << "dsp::FilenameEpoch::get_filename epoch=" 
         << epoch.printall() << endl;

  if (integer_seconds)
  {
    // ensure that the epoch is rounded up into the current division
    epoch = data->get_mid_time (false);

    DEBUG("dsp::FilenameEpoch::get_filename mid_time=" << epoch.printall());

    unsigned seconds = epoch.get_secs();
    unsigned divisions = seconds / integer_seconds;
    epoch = MJD (epoch.intday(), divisions * integer_seconds, 0.0);

    if (Observation::verbose)
      cerr << "dsp::FilenameEpoch::get_filename division_start=" 
           << epoch.printall() << endl;
  }

  vector<char> fname (FILENAME_MAX);
  char* filename = &fname[0];

  if (!epoch.datestr( filename, FILENAME_MAX, datestr_pattern.c_str() ))
    throw Error (FailedSys, "dsp::PhaseSeriesUnloader::get_filename",
       "error MJD::datestr(" + datestr_pattern + ")");

  if (report_unload)
    cerr << "unloading " << tostring(data->get_integration_length(),2)
	 << " seconds: " << filename << endl;

  return filename;
}
Exemplo n.º 12
0
double double_cast (const MJD& mjd)
{
  return mjd.in_seconds();
}
Exemplo n.º 13
0
void qt_MJD::setMJD (const MJD& mjd)
{
  value.setText (mjd.printdays(val_precision).c_str());
  valset = mjd;
}
Exemplo n.º 14
0
void dsp::WAPPFile::open_file (const char* filename)
{
  header = malloc(sizeof(struct WAPP_HEADER));

  struct WAPP_HEADER* head = (struct WAPP_HEADER*) header;

#ifdef KEVINS_CODE
  fd=::open(filename,O_RDONLY);
  if(fd==-1)
    throw Error(FailedSys,"DSP::WAPPFile::Open_File","Could not open %s",filename);
  readheader(fd,head);
#else
  struct HEADERP* h = head_parse( filename );

  if (!h)
    throw Error (InvalidParam, "dsp::WAPPFile::open_file",
		 "not a WAPP file");


  fetch(src_name);
  fetch(obs_type);

  /* user-requested length of this integration (s) */
  fetch(obs_time);
  /* size (in bytes) of this header (nom =1024) */
  fetch(header_size);

  fetch(obs_date);
  fetch(start_time);

  /* user-requested sample time (us) */
  fetch(samp_time);
  fetch(wapp_time);

  fetch(num_lags);

  fetch(nifs);

  /* user-requested: 1 means 3-level; 2 mean 9-level  */
  fetch(level);

  fetch(lagformat);

  /* if we truncate data (0 no trunc)                 */
  /* for 16 bit lagmux modes, selects which 16 bits   */
  /* of the 32 are included as data                   */
  /* 0 is bits 15-0 1,16-1 2,17-2...7,22-7            */
  fetch(lagtrunc);

  fetch(cent_freq);

  fetch(bandwidth);

  fetch(freqinversion);

  /* requested ra J2000 (10000*hr+100*min+sec) */
  fetch(src_ra);

  /* requested dec J2000 (10000*deg+100*min+sec) */
  fetch(src_dec);

  fetch(start_az);
  fetch(start_za);
  fetch(start_ast);
  fetch(start_lst);

  /* user-requested: 1 means that data is sum of IFs  */
  fetch(sum);

  fetch(project_id);
  fetch(observers);

  fetch(psr_dm);

  fetch(dumptime);

  /* get number of bins which will be non zero in folding mode */
  fetch(nbins);

  // close_parse(h);
  fd = h->fd;
#endif

  cerr << "LEVEL=" << head->level << endl;

  // ////////////////////////////////////////////////////////////////////
  //
  // mode
  //
  /* what kind of observation is this */
  get_info()->set_mode(head->obs_type);

  // ////////////////////////////////////////////////////////////////////
  //
  // source
  //
  /* user-supplied source name (usually pulsar name) */
  get_info()->set_source (head->src_name);

  cerr << "Source = " << get_info()->get_source() << endl;

  // ////////////////////////////////////////////////////////////////////
  //
  // centre_frequency
  //
  /* user-supplied band center frequency (MHz) */
  get_info()->set_centre_frequency (head->cent_freq);

  // ////////////////////////////////////////////////////////////////////
  //
  // bandwidth
  //
  /* total bandwidth (MHz) for this observation */
  double bandwidth = head->bandwidth;
  /* 1 band is inverted, else band is not inverted    */
  if (head->freqinversion)
    bandwidth = -bandwidth;
  get_info()->set_bandwidth (bandwidth);

  // ////////////////////////////////////////////////////////////////////
  //
  // npol
  //
  /* user-requested: number of IFs to be recorded     */
  get_info()->set_npol (head->nifs);

  // ////////////////////////////////////////////////////////////////////
  //
  // state
  //
  if (head->nifs == 4)
    get_info()->set_state (Signal::Coherence);
  else if (head->nifs == 2)
    get_info()->set_state (Signal::PPQQ);
  else
    get_info()->set_state (Signal::Intensity);

  // ////////////////////////////////////////////////////////////////////
  //
  // nchan
  //
  /* user-requested number of lags per dump per spect */
  get_info()->set_nchan (head->num_lags);

  // ////////////////////////////////////////////////////////////////////
  //
  // nbit
  //
  /* 0=16 bit uint lags , 1=32 bit uint lags          */
  /* 2=32 bit float lags, 3=32 bit float spectra      */
  switch (head->lagformat) {
  case 0:
    get_info()->set_nbit (16);
    break;
  case 1:
    get_info()->set_nbit (32);
    break;
  case 3: /* timing mode data - not relevant, but needs to work! */
    break;
  case 4:
    get_info()->set_nbit (8);
    break;
  default:
    throw Error (InvalidState, "dsp::WAPPFile::open_file",
		 "lagformat variable in header should be 0, 1 or 4");
    break;
  }

  cerr << "WAPP nbit=" << get_info()->get_nbit() << endl;

  // ////////////////////////////////////////////////////////////////////
  //
  // start_time
  //

  /* built by WAPP from yyyymmdd */  
  string utc = head->obs_date;  utc += "-";

  /* UT seconds after midnight (start on 1-sec tick) [hh:mm:ss] */
  utc += head->start_time;

#if WVS_FIXES_STR2TM

  struct tm time;

  /* the str2tm function has been deprecated in favour of the standard C strptime */
  if (str2tm (&time, utc.c_str()) < 0)
    throw Error (InvalidState, "dsp::WAPPFile::open_file",
		 "Could not parse UTC from " + utc);

  MJD mjd (time);

#else

  // copied from WAPPArchive

  struct tm obs_date_greg;
  struct WAPP_HEADER* hdr = head;

  int rv = sscanf(hdr->obs_date, "%4d%2d%2d", 
      &obs_date_greg.tm_year, &obs_date_greg.tm_mon,
      &obs_date_greg.tm_mday);
  obs_date_greg.tm_year -= 1900;
  obs_date_greg.tm_mon -= 1;
  if (rv!=3) 
    throw Error (InvalidState, "dsp::WAPPFile::open_file",
        "Error converting obs_date string (rv=%d, obs_date=%s)", 
        rv, hdr->obs_date);
  rv = sscanf(hdr->start_time, "%2d:%2d:%2d", 
      &obs_date_greg.tm_hour, &obs_date_greg.tm_min, 
      &obs_date_greg.tm_sec);
  if (rv!=3) 
    throw Error (InvalidState, "dsp::WAPPFile::open_file",
        "Error converting start_time string (rv=%d, start_time=%s)", 
        rv, hdr->start_time);

  MJD mjd (obs_date_greg); 

#endif

  char buff[64];
  cerr << "UTC=" << utc << " MJD=" << mjd << " -> "
       << mjd.datestr (buff, 64, "%Y-%m-%d %H:%M:%S") << endl;

  // from sigproc-2.4
  /* for data between April 17 and May 8 inclusive, the start times are
     off by 0.5 days due to the ntp daemon not running... fix here.
     this also occured on May 17! hopefully will not happen again... */
  if ( ((mjd.intday() >= 52016) && (mjd.intday() <= 52039)) 
       || (mjd.intday() == 52046.0)) {
    cerr << "WARNING: MJD start time off by 0.5 days! fixed..." << endl;
    MJD half_day (0.5);
    mjd -= half_day;
  }

  get_info()->set_start_time (mjd);

  // ////////////////////////////////////////////////////////////////////
  //
  // rate
  //
  /* actual sample time (us) i.e. requested+dead time */
  double tsamp_us = head->wapp_time;

  // from sigproc-2.4
  tsamp_us += wappcorrect( mjd.in_days() );

  get_info()->set_rate ( 1e6 / tsamp_us );

  // ////////////////////////////////////////////////////////////////////
  //
  // telscope code
  //
  get_info()->set_telescope ("Arecibo");  // assume Arecibo

  string prefix="wapp";
  get_info()->set_machine("WAPP");	

  header_bytes = lseek(fd,0,SEEK_CUR);

  cerr << "header bytes=" << header_bytes << endl;

  set_total_samples();

}
Exemplo n.º 15
0
/*! This function assumes that the Integration will have the global
  attributes of the file. */
Pulsar::Integration* 
Pulsar::FITSArchive::load_Integration (const char* filename, unsigned isubint)
try {

  if (!filename)
    throw Error (InvalidParam, "FITSArchive::load_Integration",
		 "filename unspecified");

  if (search_mode)
    throw Error (InvalidParam, "FITSArchive::load_Integration",
		 "SEARCH mode data -- no Integrations to load");

  Reference::To<Pulsar::Integration> integ = new_Integration();
  init_Integration (integ);

  int row = isubint + 1;
  
  int status = 0;  

  if (verbose > 2)
    cerr << "FITSArchive::load_Integration number " << isubint << endl;
  
  double nulldouble = 0.0;
  float nullfloat = 0.0;
  
  int initflag = 0;
  int colnum = 0;
  
  // Open the file

  fitsfile* fptr = 0;
  
  if (verbose > 2)
    cerr << "FITSArchive::load_Integration"
      " fits_open_file (" << filename << ")" << endl;
  
  fits_open_file (&fptr, filename, READONLY, &status);
  
  if (status != 0)
    throw FITSError (status, "FITSArchive::load_Integration", 
		     "fits_open_file(%s)", filename);
  

  // Move to the SUBINT Header Data Unit
  
  fits_movnam_hdu (fptr, BINARY_TBL, "SUBINT", 0, &status);
  if (status != 0)
    throw FITSError (status, "FITSArchive::load_Integration", 
		     "fits_movnam_hdu SUBINT");


  // Load the convention for the epoch definition
  string epoch_def;
  string default_def = "STT_MJD";
  psrfits_read_key (fptr, "EPOCHS", &epoch_def,
		    default_def, verbose > 2);

  if (verbose > 2)
    cerr << "FITSArchive::load_Integration epochs are " << epoch_def << endl;

  // By default, correct epochs using the phase model
  bool correct_epoch_phase = true;

  // By default, correct epochs such that phase(epoch)=phase(start)
  bool phase_match_start_time = true;

  if (epoch_def == "VALID")
    correct_epoch_phase = phase_match_start_time = false;

  if (epoch_def == "MIDTIME")
    phase_match_start_time = false;

  if (get<Pulsar::IntegrationOrder>())
  {
    colnum = 0;
    fits_get_colnum (fptr, CASEINSEN, "INDEXVAL", &colnum, &status);
    
    double value = 0.0;

    fits_read_col (fptr, TDOUBLE, colnum, row, 1, 1, &nulldouble,
		   &value, &initflag, &status);
    
    if (status != 0)
      throw FITSError (status, "FITSArchive::load_Integration", 
		       "fits_read_col INDEXVAL");
    
    get<Pulsar::IntegrationOrder>()->set_Index(row-1,value);
  }
  
  // Get the reference epoch from the primary header
  const Pulsar::FITSHdrExtension* hdr_ext = get<Pulsar::FITSHdrExtension>();
  
  if (!hdr_ext)
  {
    throw Error (InvalidParam, "FITSArchive::load_Integration",
		 "No FITSHdrExtension found");
  }
  
  // Set the duration of the integration
  
  colnum = 0;
  fits_get_colnum (fptr, CASEINSEN, "TSUBINT", &colnum, &status);
  
  double duration = 0.0;
  
  fits_read_col (fptr, TDOUBLE, colnum, row, 1, 1, &nulldouble,
		 &duration, &initflag, &status);
  
  integ->set_duration (duration);

  // Set the start time of the integration
  
  initflag = 0;
  colnum = 0;
  
  fits_get_colnum (fptr, CASEINSEN, "OFFS_SUB", &colnum, &status);
  
  double time = 0.0;
  fits_read_col (fptr, TDOUBLE, colnum, row, 1, 1, &nulldouble,
		 &time, &initflag, &status);
  
  if (status != 0)
    throw FITSError (status, "FITSArchive::load_Integration", 
		     "fits_read_col OFFS_SUB");


  MJD epoch = hdr_ext->get_start_time() + time;

  if (verbose > 2)
    cerr << "Pulsar::FITSArchive::load_Integration"
      " header epoch=" << hdr_ext->get_start_time().printdays(13) << "\n "
      " offset=" << time << "s epoch=" << epoch.printdays(13) << endl;
  
  // Set a preliminary epoch to avoid problems loading the polyco
  integ->set_epoch (epoch);

  // Set the folding period to 0 until one of three possible methods succeeds
  integ->set_folding_period (0.0);

  /* **********************************************************************

     METHOD 1: folding period defined by a pulse phase model

     ********************************************************************** */

  if (hdr_model)
  {
    // Set the folding period, using the polyco from the file header
    // This was taken out of the condition clause below because period
    // wasn't set when TSUB was 0
    integ->set_folding_period (1.0 / hdr_model->frequency(epoch));

    if (integ->get_folding_period() <= 0.0)
      throw Error( InvalidState, "Pulsar::FITSArchive::load_Integration",
		   "header polyco/predictor corrupted; "
		   "period(epoch=%s)=%lf", epoch.printdays(5).c_str(),
		   integ->get_folding_period() );

    if (integ->get_folding_period() < 1.0e-3)
      warning << "Pulsar::FITSArchive::load_Integration folding_period=" 
	      << integ->get_folding_period() << " is less than 1ms" << endl;

    else if (verbose > 2)
      cerr << "Pulsar::FITSArchive::load_Integration folding_period = "
      	   << integ->get_folding_period () << endl;

    if (duration && correct_epoch_phase)
    {

      if (verbose > 2)
	cerr << "Pulsar::FITSArchive::load_Integration correcting epoch phase"
	     << endl;

      Phase reference_phs = 0.0;

      if (phase_match_start_time)
      {
	// Correct epoch such that its phase equals that of the start time
	if (verbose > 2)
	  cerr << "Pulsar::FITSArchive::load_Integration matching phase(start)"
	       << endl;

	reference_phs = hdr_model->phase(hdr_ext->get_start_time());
      }

      Phase off_phs = hdr_model->phase(epoch);
      Phase dphase  = off_phs - reference_phs;
      
      double dtime = dphase.fracturns() * integ->get_folding_period();
      epoch -= dtime;
      integ->set_epoch (epoch);

      if (verbose > 2)
      {
      	cerr << "Pulsar::FITSArchive::load_Integration row=" << row <<
	  "\n  PRED_PHS=" << predicted_phase;

	if (phase_match_start_time)
	  cerr << "\n  reference epoch=" 
	       << hdr_ext->get_start_time().printdays(13);

	cerr <<
	  "\n  reference phase=" << reference_phs <<
	  "\n      input phase=" << off_phs <<
	  "\n     phase offset=" << dphase << " = " << dtime << "s" 
	  "\n     subint epoch=" << epoch.printdays(13) << 
	  "\n     subint phase=" << hdr_model->phase(epoch) << endl;
      }
    }
  }
  else
  {

    /* *******************************************************************

       METHOD 2: folding period defined by CAL_FREQ in primary header

       ******************************************************************* */

    CalInfoExtension* calinfo = get<CalInfoExtension>();
    if (calinfo && calinfo->cal_frequency > 0.0)
    {
      if (verbose > 2)
        cerr << "FITSArchive::load_Integration CAL_FREQ=" 
	     << calinfo->cal_frequency << endl;
      integ->set_folding_period( 1.0/calinfo->cal_frequency );
    }

    /* *******************************************************************

       METHOD 3: folding period defined by PERIOD column of SUBINT HDU

       ******************************************************************* */

    double period = 0.0;
    status = 0;
    fits_get_colnum (fptr, CASEINSEN, "PERIOD", &colnum, &status);
    fits_read_col (fptr, TDOUBLE, colnum, row, 1, 1, &nulldouble,
                   &period, &initflag, &status);

    if (status == 0 && period > 0.0)
    {
      if (verbose > 2)
	cerr << "FITSArchive::load_Integration PERIOD=" << period << endl;
      integ->set_folding_period (period);
    }

    if (integ->get_folding_period() == 0.0)
      throw FITSError (status, "FITSArchive::load_Integration",
                       "folding period unknown: no model, CAL_FREQ or PERIOD");
  }

  status = 0;

  // Load other useful info

  load_Pointing (fptr,row,integ);
  load_Plasma (fptr,row,integ);

  // Set up the data vector, only Pulsar::Archive base class is friend

  resize_Integration (integ);

  const unsigned nchan = get_nchan();

  if (naux_profile)
    for (unsigned ichan=0; ichan < nchan; ichan++)
    {
      FourthMoments* fourth = new FourthMoments;
      fourth->resize (naux_profile, get_nbin());
      integ->get_Profile(0,ichan)->add_extension (fourth);
    }

  // Load the channel centre frequencies
  
  if (verbose > 2)
    cerr << "Pulsar::FITSArchive::load_Integration reading channel freqs" 
	 << endl;
  
  int counter = 1;
  vector < float >  chan_freqs(get_nchan());
  
  colnum = 0;
  fits_get_colnum (fptr, CASEINSEN, "DAT_FREQ", &colnum, &status);
  
  fits_read_col (fptr, TFLOAT, colnum, row, counter, get_nchan(),
		 &nullfloat, &(chan_freqs[0]), &initflag, &status);

  if (status != 0)
    throw FITSError (status, "FITSArchive::load_Integration",
                     "fits_read_col DAT_FREQ");

  // Set the profile channel centre frequencies
  
  if (verbose > 2)
    cerr << "Pulsar::FITSArchive::load_Integration setting frequencies" 
	 << endl;

  bool all_ones = true;
  for (unsigned j = 0; j < get_nchan(); j++)
    if (chan_freqs[j] != 1)
      all_ones = false;
  
  double chanbw = get_bandwidth() / get_nchan();
  
  if ( all_ones )
  {
    if (verbose > 2)
      cerr << "FITSArchive::load_Integration all frequencies unity - reseting"
	   << endl;
    for (unsigned j = 0; j < get_nchan(); j++)
      integ->set_centre_frequency (j, get_centre_frequency()
				   -0.5*(get_bandwidth()+chanbw)+j*chanbw);
  }
  else
  {
    for (unsigned j = 0; j < get_nchan(); j++)
      integ->set_centre_frequency(j, chan_freqs[j]);
  }
  
  // Load the profile weights

  if (verbose > 2)
    cerr << "Pulsar::FITSArchive::load_Integration reading weights" 
	 << endl;
  
  counter = 1;
  vector < float >  weights(get_nchan());
  
  colnum = 0;
  fits_get_colnum (fptr, CASEINSEN, "DAT_WTS", &colnum, &status);
  
  for (unsigned b = 0; b < get_nchan(); b++) {
    fits_read_col (fptr, TFLOAT, colnum, row, counter, 1, &nullfloat, 
		   &weights[b], &initflag, &status);
    counter ++;
  }

  if (status != 0)
    throw FITSError (status, "FITSArchive::load_Integration",
                     "fits_read_col DAT_WTS");

  // Set the profile weights
  
  if (verbose > 2)
    cerr << "Pulsar::FITSArchive::load_Integration setting weights" 
	 << endl;
  
  for(unsigned j = 0; j < get_nchan(); j++)
    integ->set_weight(j, weights[j]);
  
  // Load the profile offsets
  
  if (!Profile::no_amps)
  {
    vector<Profile*> profiles;

    setup_profiles_dat (integ, profiles);
    setup_dat (fptr, load_dat_io);

    if (verbose > 2)
      cerr << "FITSArchive::load_Integration dat_io=" << load_dat_io.ptr()
           << endl;

    load_dat_io->load (isubint + 1, profiles);

    if (scale_cross_products && integ->get_state() == Signal::Coherence)
      for (unsigned ichan=0; ichan < get_nchan(); ichan++)
      {
	integ->get_Profile(2, ichan)->scale(2.0);
	integ->get_Profile(3, ichan)->scale(2.0);
      }

    if (naux_profile)
    {
      setup_profiles<MoreProfiles> (integ, profiles);
      setup_aux (fptr, load_aux_io, naux_profile);
      load_aux_io->load (isubint + 1, profiles);
    }
  }

  if (verbose > 2)
    cerr << "Pulsar::FITSArchive::load_Integration load complete" << endl;  
  
  // Finished with the file for now
  
  fits_close_file (fptr, &status);

  return integ.release();
}
catch (Error& error)
{
  throw error += "Pulsar::FITSArchive::load_Integration";
}
Exemplo n.º 16
0
   void scanTime( CommonTime& t,
                  const string& str,
                  const string& fmt )
   {
      try
      {
         using namespace gpstk::StringUtils;

            // Get the mapping of character (from fmt) to value (from str).
         TimeTag::IdToValue info;
         TimeTag::getInfo( str, fmt, info );
         
            // These indicate which information has been found.
         bool hmjd( false ), hsow( false ), hweek( false ), hfullweek( false ),
            hdow( false ), hyear( false ), hmonth( false ), hday( false ),
            hzcount( false ), hdoy( false ), hzcount29( false ), 
            hzcount32( false ), hhour( false ), hmin( false ), hsec( false ),
            hsod( false ), hunixsec( false ), hunixusec( false ), 
            hepoch( false ), hansi( false ), hjulian( false ),
            hbdsw( false ), hqzsw( false ), hgalw( false ),
            hbdsfw( false ), hqzsfw( false ), hgalfw( false ),
            hbdse( false ), hqzse( false ), hgale( false);

            // These are to hold data that no one parses.
         int idow(0);
         TimeSystem ts;

         for( TimeTag::IdToValue::iterator itr = info.begin();
              itr != info.end(); itr++ )
         {
            switch( itr->first )
            {
               case 'P':
                  ts.fromString(itr->second);
                  t.setTimeSystem(ts);
                  break;

               case 'Q':
                  hmjd = true;
                  break;

               case 'Z':
                  hzcount = true;
                  break;

               case 's':
                  hsod = true;
                  break;

               case 'g':
                  hsow = true;
                  break;

               case 'w':
                  idow = asInt( itr->second );
                  hdow = true;
                  break;

               case 'G':
                  hweek = true;
                  break;

               case 'F':
                  hfullweek = true;
                  break;

               case 'j':
                  hdoy = true;
                  break;

               case 'b':
               case 'B':
                  hmonth = true;
                  break;

               case 'Y':
               case 'y':
                  hyear = true;
                  break;

               case 'a':
               case 'A':
                  {
                     hdow = true;
                     string thisDay = firstWord( itr->second );
                     lowerCase(thisDay);
                     if (isLike(thisDay, "sun.*")) idow = 0;
                     else if (isLike(thisDay, "mon.*")) idow = 1;
                     else if (isLike(thisDay, "tue.*")) idow = 2;
                     else if (isLike(thisDay, "wed.*")) idow = 3;
                     else if (isLike(thisDay, "thu.*")) idow = 4;
                     else if (isLike(thisDay, "fri.*")) idow = 5;
                     else if (isLike(thisDay, "sat.*")) idow = 6;
                     else
                     {
                        hdow = false;
                     }
                  }
                  break;
                  
               case 'm':
                  hmonth = true;
                  break;

               case 'd':
                  hday = true;
                  break;

               case 'H':
                  hhour = true;
                  break;

               case 'M':
                  hmin = true;
                  break;

               case 'S':
                  hsec = true;
                  break;

               case 'f':
                  hsec = true;
                  // a small hack to make fractional seconds work
                  info['S'] = info['f'];
                  break;

               case 'U':
                  hunixsec = true;
                  break;

               case 'u':
                  hunixusec = true;
                  break;
                  
               case 'c':
                  hzcount29 = true;
                  break;

               case 'C':
                  hzcount32 = true;
                  break;

               case 'J':
                  hjulian = true;
                  break;
                  
               case 'K':
                  hansi = true;
                  break;
                  
               case 'E':
                  hepoch = true;
                  break;

               case 'R': hepoch = hbdse = true; break;
               case 'T': hepoch = hgale = true; break;
               case 'V': hepoch = hqzse = true; break;

               case 'D': hfullweek = hbdsfw = true; break;
               case 'e': hweek = hbdsw = true; break;
               case 'L': hfullweek = hgalfw = true; break;
               case 'l': hweek = hgalw = true; break;
               case 'I': hfullweek = hqzsfw = true; break;
               case 'i': hweek = hqzsw = true; break;

               default:
                  {
                     // do nothing
                  }
                  break;

            };
         }     // end loop over Id/Value pairs

         if( hyear )
         {
            if( hmonth && hday )
            {
               CivilTime tt;
               tt.setFromInfo( info );
               if( hsod )
               {
                  convertSODtoTime( asDouble( info['s'] ), 
                                    tt.hour, tt.minute, tt.second );
               }
               t = tt.convertToCommonTime();
               return;
            }
            else  // use YDSTime as default
            {
               YDSTime tt;
               tt.setFromInfo( info );
               if( hhour && hmin && hsec )
               {
                  tt.sod = convertTimeToSOD( asInt( info['H'] ), 
                                             asInt( info['M'] ), 
                                             asDouble( info['S'] ) );
               }
               t = tt.convertToCommonTime();
               return;
            }

         } // end of if( hyear )

         if( hzcount32 ||
             (hfullweek && hzcount) ||
             (hepoch && (hzcount29 || 
                         (hweek && hzcount))) )
         {
            GPSWeekZcount tt;
            tt.setFromInfo( info );
            t = tt.convertToCommonTime();
            return;
         }

         if ( (hepoch && hweek) || hfullweek )
         {
            WeekSecond* ptt;
            if(hbdse || hbdsfw || hbdsw) ptt = new BDSWeekSecond();
            else if(hqzse || hqzsfw || hqzsw) ptt = new QZSWeekSecond();
            else if(hgale || hgalfw || hgalw) ptt = new GALWeekSecond();
            else ptt = new GPSWeekSecond();
            ptt->setFromInfo(info);
            if( hdow && !hsow )
            {
               ptt->sow = asInt( info['w'] ) * SEC_PER_DAY;
               if( hsod )
               {
                  ptt->sow += asDouble( info['s'] );
               }
               else if( hhour && hmin && hsec )
               {
                  ptt->sow += convertTimeToSOD( asInt( info['H'] ), 
                                              asInt( info['M'] ), 
                                              asDouble( info['S'] ) );
               }
            }
            t = ptt->convertToCommonTime();
            return;
         }

         if( hmjd )
         {
            MJD tt;
            tt.setFromInfo( info );
            t = tt.convertToCommonTime();
            return;
         }

         if( hjulian )
         {
            JulianDate tt;
            tt.setFromInfo( info );
            t = tt.convertToCommonTime();
            return;
         }

         if( hansi )
         {
            ANSITime tt;
            tt.setFromInfo( info );
            t = tt.convertToCommonTime();
            return;
         } 
         
         if( hunixsec || hunixusec )
         {
            UnixTime tt;
            tt.setFromInfo( info );
            t = tt.convertToCommonTime();
            return;
         }

         InvalidRequest ir("Incomplete time specification for readTime");
         GPSTK_THROW( ir );
      }
      catch( gpstk::StringUtils::StringException& se )
      {
         GPSTK_RETHROW( se );
      }
   }   
Exemplo n.º 17
0
bool dsp::PhaseSeries::mixable (const Observation& obs, unsigned nbin,
				int64_t istart, int64_t fold_ndat)
{
  MJD obsStart = obs.get_start_time() + double (istart) / obs.get_rate();

  if (verbose)
    cerr << "PhaseSeries::mixable start mix=" << obsStart.printdays(8)
	 << " cur=" << get_start_time().printdays(8) << endl;

  MJD obsEnd;

  // if fold_ndat is not specified, fold to the end of the Observation
  // (works also for special case of adding dsp::PhaseSeriess together;
  // where using ndat=nbin would not make sense)
  if (fold_ndat == 0)
    obsEnd = obs.get_end_time();
  else
    obsEnd = obsStart + double (fold_ndat) / obs.get_rate();

  if (integration_length == 0.0)
  {
    // the integration is currently empty; prepare for integration

    if (verbose)
      cerr << "PhaseSeries::mixable reset" << endl;

    Observation::operator = (obs);
    if (verbose)
      cerr << "dsp::PhaseSeries::mixable rate=" << get_rate() << endl;

    const TimeSeries* series = dynamic_cast<const TimeSeries*> (&obs);
    if (series)
    {
      if (verbose)
        cerr << "dsp::PhaseSeries::mixable calling set_order" << endl;
      set_order( series->get_order() );
      if (verbose)
        cerr << "dsp::PhaseSeries::mixable calling set_zeroed_data" << endl;
      set_zeroed_data( series->get_zeroed_data() );
      if (get_zeroed_data())
        set_hits_nchan( series->get_nchan() );
    }

    end_time = obsEnd;
    start_time = obsStart;

    /*
      the integration length may be zero only because all of the samples
      have been dropped - maintain the record of dropped samples
    */
    uint64_t backup_ndat_total = ndat_total;

    if (verbose)
      cerr << "dsp::PhaseSeries::mixable calling resize(" << nbin << ")" << endl;
    resize (nbin);
    if (verbose)
      cerr << "dsp::PhaseSeries::mixable calling zero()" << endl;
    zero ();

    ndat_total = backup_ndat_total;

    return true;
  }

  if (!combinable (obs)) {
    cerr << "PhaseSeries::mixable differing observations" << endl;
    return false;
  }

  if (get_nbin() != nbin) {
    cerr << "PhaseSeries::mixable nbin=" << get_nbin() <<" != "<< nbin <<endl;
    return false;
  }

  end_time = std::max (end_time, obsEnd);
  start_time = std::min (start_time, obsStart);

  if (verbose)
    cerr << "PhaseSeries::mixable combine start=" << start_time.printdays(8)
	 << " end=" << end_time.printdays(8) << endl;

  return true;
}
Exemplo n.º 18
0
void dsp::TimeDivide::set_bounds (const Observation* input)
{
  observation = input;

  double sampling_rate = input->get_rate();
  uint64_t input_ndat = input->get_ndat();

  MJD input_start = input->get_start_time();
  MJD input_end   = input->get_end_time();

  //////////////////////////////////////////////////////////////////////////
  //
  // determine the MJD at which to start
  //
  MJD divide_start = input_start;

  if (is_valid)
  {
    divide_start = std::max (current_end, input_start);

    if (Operation::verbose)
      cerr << "dsp::TimeDivide::bound continue at" 
	   << "\n        start = " << divide_start
	   << "\n  current end = " << current_end
	   << "\n  input start = " << input_start
	   << endl;
  }

  new_division = false;
  end_reached = false;
  in_next = false;

  if (input_end < lower || divide_start + 0.5/sampling_rate > upper)
  {
    /*
      This state occurs when either:
      1) this method is first called (no boundaries set)
      2) the 
    */

    if (Operation::verbose)
    {
      cerr << "dsp::TimeDivide::bound start new division" << endl;
      if (input_end < lower)
        cerr << "      input end = " << input_end << " precedes\n"
                " division start = " << lower << endl;
       else
        cerr << "          start = " << divide_start << " is after\n"
                "   division end = " << upper << endl;
    }

    new_division = true;

    set_boundaries (divide_start + 0.55/sampling_rate);
  }

  divide_start = std::max (lower, divide_start);

  if (Operation::verbose)
    cerr << "dsp::TimeDivide::bound start division at" 
	 << "\n          start = " << divide_start
	 << "\n division start = " << lower
	 << "\n    input start = " << input_start
	 << endl;

  //////////////////////////////////////////////////////////////////////////
  //
  // determine how far into the current Observation to start
  //
  MJD offset = divide_start - input_start;

  double start_sample = offset.in_seconds() * sampling_rate;

  // cerr << "start_sample=" << start_sample << endl;
  start_sample = rint (start_sample);
  // cerr << "rint(start_sample)=" << start_sample << endl;

  assert (start_sample >= 0);

  idat_start = (uint64_t) start_sample;

  if (Operation::verbose)
    cerr << "dsp::TimeDivide::bound start offset " << offset.in_seconds()*1e3
	 << " ms (" << idat_start << "pts)" << endl;

  if (idat_start >= input_ndat)
  {
    // The current data end before the start of the current division

    if (Operation::verbose)
      cerr << "dsp::TimeDivide::bound input ends before division starts"<<endl;

    is_valid = false;
    return;
  }

  //////////////////////////////////////////////////////////////////////////
  //
  // determine how far into the current input TimeSeries to end
  //
  MJD divide_end = std::min (input_end, upper);

  if (Operation::verbose)
    cerr << "dsp::TimeDivide::bound end division at "
         << "\n           end = " << divide_end
         << "\n  division end = " << upper
         << "\n     input end = " << input_end
         << endl;

  offset = divide_end - input_start;

  double end_sample = offset.in_seconds() * sampling_rate;

  // cerr << "end_sample=" << end_sample << endl;
  end_sample = rint (end_sample);
  // cerr << "rint(end_sample)=" << end_sample << endl;

  assert (end_sample >= 0);

  uint64_t idat_end = (uint64_t) end_sample;

  if (Operation::verbose)
    cerr << "dsp::TimeDivide::bound end offset " << offset.in_seconds()*1e3
	 << " ms (" << idat_end << "pts)" << endl;
 
  if (idat_end <= idat_start)
  {
#ifdef _DEBUG
    cerr << "dsp::TimeDivide::bound start division at"
         << "\n          start = " << divide_start
         << "\n division start = " << lower
         << "\n    input start = " << input_start
         << endl;

    offset = divide_start - input_start;

    cerr << "dsp::TimeDivide::bound start offset " << offset.in_seconds()*1e3
         << " ms (" << idat_start << "pts)" << endl;

    cerr << "dsp::TimeDivide::bound end division at "
         << "\n           end = " << divide_end
         << "\n  division end = " << upper
         << "\n     input end = " << input_end
         << endl;

    offset = divide_end - input_start;

    cerr << "dsp::TimeDivide::bound end offset " << offset.in_seconds()*1e3
         << " ms (" << idat_end << "pts)" << endl; 
#endif

    throw Error (InvalidState, "dsp::TimeDivide::bound",
		 "idat_end="UI64" <= idat_start="UI64, idat_end, idat_start);
  }

  if (idat_end > input_ndat)
  {
    // this can happen owing to rounding in the above call to rint()

    if (Operation::verbose)
      cerr << "dsp::TimeDivide::bound division"
	"\n   end_sample=rint(" << end_sample << ")=" << idat_end << 
	" > input ndat=" << input_ndat << endl;

    idat_end = input_ndat;
  }
  else if (idat_end < input_ndat)
  {
    // The current input TimeSeries extends more than the current
    // division.  The in_next flag indicates that the input
    // TimeSeries should be used again.

    if (Operation::verbose)
      cerr << "dsp::TimeDivide::bound input data ends "
           << (input_end-divide_end).in_seconds()*1e3 <<
        " ms after current division" << endl;

    in_next = true;
  }

  ndat = idat_end - idat_start;

  //////////////////////////////////////////////////////////////////////////
  //
  // determine if the end of the current division has been reached
  //

  double samples_to_end = (upper - divide_end).in_seconds() * sampling_rate;

  if (Operation::verbose)
    cerr << "dsp::TimeDivide::bound " << samples_to_end << 
      " samples to end of current division" << endl;

  if (samples_to_end < 0.5)
  {
    if (Operation::verbose)
      cerr << "dsp::TimeDivide::bound end of division" << endl;

    end_reached = true;
  }

  if (Operation::verbose)
  {
    double start = 1e3*idat_start/sampling_rate;
    double used = 1e3*ndat/sampling_rate;
    double available = 1e3*input_ndat/sampling_rate;
    cerr << "dsp::TimeDivide::bound division=" << division << " using "
	 << used << "/" << available << " from " << start << " ms\n  (" 
	 << ndat << "/" << input_ndat << " from " << idat_start << " to "
	 << idat_start + ndat - 1 << " inclusive.)" << endl;
  }

  is_valid = true;
  current_end = input_start + idat_end/sampling_rate;
}
Exemplo n.º 19
0
int main (int argc, char ** argv) try
{
  bool phase_periastron = false;
  bool longitude_periastron = false;
  bool longitude_ascending = false;

  MJD mjd;
  double duration = 0.0;

  char site = '7';
  double freq = 1400.0;

  int gotc = 0;
  while ((gotc = getopt(argc, argv, "hd:f:m:s:pPaA")) != -1)
  {
    switch (gotc)
    {
    case 'h':
      usage ();
      return 0;

    case 'd':
      duration = atof (optarg);
      break;

    case 'f':
      freq = atof (optarg);
      break;

    case 'm':
      mjd = MJD(optarg);
      break;

    case 's':
      site = optarg[0];
      break;

    case 'p':
      phase_periastron = true;
      break;

    case 'P':
      longitude_periastron = true;
      break;

    case 'A':
      longitude_ascending = true;
      break;

    }
  }

  if (optind >= argc)
  {
    cerr << "Please provide tempo parameter file" << endl;
    return -1;
  }

  if (mjd == 0.0)
  {
    time_t temp = time(NULL);
    struct tm date = *gmtime(&temp);
    fprintf (stderr, "\nUsing current date/time: %s\n", asctime(&date));
    mjd = MJD (date);
  }

  psrephem eph (argv[optind]);

  double epoch = mjd.in_days();

  if (duration)
  {
    unsigned nsteps = 100;
    for (unsigned i=0; i<nsteps; i++)
    {
      double hours = (duration * i) / nsteps;
      double seconds = hours * 3600.0;

      MJD t = mjd + seconds;

      cout << hours << " " << t.datestr("%H:%M:%S") << " "
	   << get_binlng_asc (t.in_days(), eph, freq, site) << endl;
    }
    return 0;
  }

  cout << "================================================" << endl;

  if ( phase_periastron )
    cout << "Binary phase (wrt periastron) = " 
	 << get_binphs_peri (epoch, eph, freq, site)*360.0 << " deg" << endl;
  
  if ( longitude_periastron )
    cout << "Longitude wrt periastron = " 
	 << get_binlng_peri (epoch, eph, freq, site) << " deg" << endl;
  
  if ( longitude_ascending )
    cout << "Longitude wrt ascending node = "
	 << get_binlng_asc (epoch, eph, freq, site) << " deg" << endl;
  
  cout << "================================================" << endl;

  if ( longitude_ascending )
    cout <<
      "\n"
      "Superior conjunction occurs when longitude wrt ascending node = 90 deg"
      "\n"
	 << endl;

  return 0;
}
catch (Error& error)
{
  cerr << "ephorb: error" << error << endl;
  return -1;
}
Exemplo n.º 20
0
MJD dsp::Mark4File::decode_date(uint64_t from)
{
  char *timecode = new char[8*channels]; // 8 bytes per channel

  MJD date;
  MJD current;
  utc_t utcdate;
  utc_t tmpdate;
  
  // Special lookup table, see documentation for Mark4 formaters.
  // 0=0, 1=1.25, 2=2.5, 3=3.75, 4=NA, 5=5.0, 6=6.25, 7=7.5, 8=8.75, 9=NA
  //Required for Mark4 standard format
  float time_code_table[] = {0,1.25,2.5,3.75,0.0,5.0,6.25,7.50,8.75,0.0};

  current.Construct(time(NULL));
  
  uint64_t inital_pos = lseek(fd, 0, SEEK_CUR);
  
  uint64_t next_sync = find_sync(fd, from);
  
  // Read the 8 bytes after the SYNC - and handle them as per modes
  lseek(fd,next_sync+4*channels,SEEK_SET);
  
  read(fd, timecode, 8*channels);

  int stepsize = channels/8;

  int julian = 0;
  int year   = 0;
  int day    = 0;
  int hour   = 0;
  int minute = 0;
  double second = 0.0;
  char tmp[4];
  
  switch(mode) {
    
  case VLBA:

    // Date format for VLBA = JJJSSSSS.ssss
    
    // JJJ
    tmp[0] = timecode[0*stepsize];
    tmp[1] = timecode[1*stepsize];
    tmp[2] = timecode[2*stepsize];
    tmp[3] = timecode[3*stepsize];
    julian += decode_bcd(tmp)*100;

    tmp[0] = timecode[4*stepsize];
    tmp[1] = timecode[5*stepsize];
    tmp[2] = timecode[6*stepsize];
    tmp[3] = timecode[7*stepsize];
    julian += decode_bcd(tmp)*10;

    tmp[0] = timecode[8*stepsize];
    tmp[1] = timecode[9*stepsize];
    tmp[2] = timecode[10*stepsize];
    tmp[3] = timecode[11*stepsize];
    julian += decode_bcd(tmp)*1;
    
    //SSSSS
    tmp[0] = timecode[12*stepsize];
    tmp[1] = timecode[13*stepsize];
    tmp[2] = timecode[14*stepsize];
    tmp[3] = timecode[15*stepsize];
    second += decode_bcd(tmp)*10000.0;

    tmp[0] = timecode[16*stepsize];
    tmp[1] = timecode[17*stepsize];
    tmp[2] = timecode[18*stepsize];
    tmp[3] = timecode[19*stepsize];
    second += decode_bcd(tmp)*1000.0;

    tmp[0] = timecode[20*stepsize];
    tmp[1] = timecode[21*stepsize];
    tmp[2] = timecode[22*stepsize];
    tmp[3] = timecode[23*stepsize];
    second += decode_bcd(tmp)*100.0;

    tmp[0] = timecode[24*stepsize];
    tmp[1] = timecode[25*stepsize];
    tmp[2] = timecode[26*stepsize];
    tmp[3] = timecode[27*stepsize];
    second += decode_bcd(tmp)*10.0;

    tmp[0] = timecode[28*stepsize];
    tmp[1] = timecode[29*stepsize];
    tmp[2] = timecode[30*stepsize];
    tmp[3] = timecode[31*stepsize];
    second += decode_bcd(tmp)*1.0;

    //.ssss
    tmp[0] = timecode[32*stepsize];
    tmp[1] = timecode[33*stepsize];
    tmp[2] = timecode[34*stepsize];
    tmp[3] = timecode[35*stepsize];
    second += decode_bcd(tmp)*0.1;

    tmp[0] = timecode[36*stepsize];
    tmp[1] = timecode[37*stepsize];
    tmp[2] = timecode[38*stepsize];
    tmp[3] = timecode[39*stepsize];
    second += decode_bcd(tmp)*0.01;

    tmp[0] = timecode[40*stepsize];
    tmp[1] = timecode[41*stepsize];
    tmp[2] = timecode[42*stepsize];
    tmp[3] = timecode[43*stepsize];
    second += decode_bcd(tmp)*0.001;

    tmp[0] = timecode[44*stepsize];
    tmp[1] = timecode[45*stepsize];
    tmp[2] = timecode[46*stepsize];
    tmp[3] = timecode[47*stepsize];
    second += decode_bcd(tmp)*0.0001;
    
    if(int(current.in_days())%1000 >= julian){
      // 2 most significant digits of 5 digit julian are correct
      julian += ( int(current.in_days())/1000)*1000;
    }
    else{
      julian += ( int(current.in_days())/1000 -1 )*1000;
    }

    date = MJD(julian,int(second), (second-int(second)));
    
    break;
    
  case Standard:
    
    // Date format for VLBA = YDDDHHMMSS.sss
    
    // Y
    tmp[0] = timecode[0*stepsize];
    tmp[1] = timecode[1*stepsize];
    tmp[2] = timecode[2*stepsize];
    tmp[3] = timecode[3*stepsize];
    year = decode_bcd(tmp);


    // DDD
    tmp[0] = timecode[4*stepsize];
    tmp[1] = timecode[5*stepsize];
    tmp[2] = timecode[6*stepsize];
    tmp[3] = timecode[7*stepsize];
    day += decode_bcd(tmp)*100;

    tmp[0] = timecode[8*stepsize];
    tmp[1] = timecode[9*stepsize];
    tmp[2] = timecode[10*stepsize];
    tmp[3] = timecode[11*stepsize];
    day += decode_bcd(tmp)*10;
    
    tmp[0] = timecode[12*stepsize];
    tmp[1] = timecode[13*stepsize];
    tmp[2] = timecode[14*stepsize];
    tmp[3] = timecode[15*stepsize];
    day += decode_bcd(tmp)*1;


    // HH
    tmp[0] = timecode[16*stepsize];
    tmp[1] = timecode[17*stepsize];
    tmp[2] = timecode[18*stepsize];
    tmp[3] = timecode[19*stepsize];
    hour += decode_bcd(tmp)*10;

    tmp[0] = timecode[20*stepsize];
    tmp[1] = timecode[21*stepsize];
    tmp[2] = timecode[22*stepsize];
    tmp[3] = timecode[23*stepsize];
    hour += decode_bcd(tmp)*1;

    // MM
    tmp[0] = timecode[24*stepsize];
    tmp[1] = timecode[25*stepsize];
    tmp[2] = timecode[26*stepsize];
    tmp[3] = timecode[27*stepsize];
    minute += decode_bcd(tmp)*10;

    tmp[0] = timecode[28*stepsize];
    tmp[1] = timecode[29*stepsize];
    tmp[2] = timecode[30*stepsize];
    tmp[3] = timecode[31*stepsize];
    minute += decode_bcd(tmp)*1;


    // SS
    tmp[0] = timecode[32*stepsize];
    tmp[1] = timecode[33*stepsize];
    tmp[2] = timecode[34*stepsize];
    tmp[3] = timecode[35*stepsize];
    second += decode_bcd(tmp)*10.0;

    tmp[0] = timecode[36*stepsize];
    tmp[1] = timecode[37*stepsize];
    tmp[2] = timecode[38*stepsize];
    tmp[3] = timecode[39*stepsize];
    second += decode_bcd(tmp)*1.0;


    // .sss
    tmp[0] = timecode[40*stepsize];
    tmp[1] = timecode[41*stepsize];
    tmp[2] = timecode[42*stepsize];
    tmp[3] = timecode[43*stepsize];
    second += decode_bcd(tmp)*0.1;

    tmp[0] = timecode[44*stepsize];
    tmp[1] = timecode[45*stepsize];
    tmp[2] = timecode[46*stepsize];
    tmp[3] = timecode[47*stepsize];
    second += decode_bcd(tmp)*0.01;

    tmp[0] = timecode[48*stepsize];
    tmp[1] = timecode[49*stepsize];
    tmp[2] = timecode[50*stepsize];
    tmp[3] = timecode[51*stepsize];
    second += time_code_table[decode_bcd(tmp)]*0.001;
    
    
    current.UTC(&tmpdate,0);

    if(tmpdate.tm_year%10 >= year){
      year += int(tmpdate.tm_year/10)*10;
    }else{
      year += int((tmpdate.tm_year/10)-1)*10;
    }
    
    utcdate.tm_year = year;
    utcdate.tm_yday = day;
    utcdate.tm_hour = hour;
    utcdate.tm_min  = minute;
    utcdate.tm_sec  = int(second);
    
    date  = MJD(utcdate);
    date +=  second-int(second); // add fractions of seconds.

    break;
 
   
  default:
    cerr << "Unknown mode - " << mode << endl;
    
  }
  
  //  cerr << "SEEK_CUR: " << lseek(fd,0,SEEK_CUR);
  //  lseek(fd,next_sync-8*channels,SEEK_SET);  // position of decoded time.
  //  cerr << "\t" << lseek(fd,0,SEEK_CUR)/channels << endl; 
  
  lseek(fd,inital_pos,SEEK_SET);  // restored original file pointer
  
  return date;
  
}
Exemplo n.º 21
0
void dsp::ASCIIObservation::unload (char* header)
{
  if (header == NULL)
    throw Error (InvalidState, "ASCIIObservation::unload", "no header!");


  // //////////////////////////////////////////////////////////////////////
  //
  // HDR_VERSION
  //
  float version = 1.0;
  if (ascii_header_set (header, hdr_version.c_str(), "%f", version) < 0)
    cerr << "ASCIIObservation: failed unload " << hdr_version << endl;


  // //////////////////////////////////////////////////////////////////////
  //
  // TELESCOPE
  //
  if (ascii_header_set (header, "TELESCOPE", "%s", 
			get_telescope().c_str() ) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload TELESCOPE");


  // //////////////////////////////////////////////////////////////////////
  //
  // RECEIVER
  //
  if (ascii_header_set (header, "RECEIVER", "%s", get_receiver().c_str()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload RECEIVER");


  // //////////////////////////////////////////////////////////////////////
  //
  // SOURCE
  //
  if (ascii_header_set (header, "SOURCE", "%s", get_source().c_str()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload SOURCE");


  // //////////////////////////////////////////////////////////////////////
  //
  // MODE
  //
  string mode;
  switch (get_type())
  {
  case Signal::Pulsar: mode = "PSR"; break;
  case Signal::PolnCal: mode = "CAL"; break;
  default: mode = "UNKNOWN"; break;
  }
  ascii_header_set (header, "MODE", "%s", mode.c_str());
    

  if (get_type() == Signal::PolnCal
      && ascii_header_set (header, "CALFREQ", "%lf", get_calfreq()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload FREQ");


  // //////////////////////////////////////////////////////////////////////
  //
  // FREQ
  //
  if (ascii_header_set (header, "FREQ", "%lf", get_centre_frequency()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload FREQ");


  // //////////////////////////////////////////////////////////////////////
  //
  // BW
  //
  if (ascii_header_set (header, "BW", "%lf", get_bandwidth()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload BW");


  // //////////////////////////////////////////////////////////////////////
  //
  // NCHAN
  //
  if (ascii_header_set (header, "NCHAN", "%d", get_nchan()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload NCHAN");


  // //////////////////////////////////////////////////////////////////////
  //
  // NPOL
  //
  if (ascii_header_set (header, "NPOL", "%d", get_npol()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload NPOL");


  // //////////////////////////////////////////////////////////////////////
  //
  // NBIT
  //
  if (ascii_header_set (header, "NBIT", "%d", get_nbit()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload NBIT");


  // //////////////////////////////////////////////////////////////////////
  //
  // NDIM
  //
  if (ascii_header_set (header, "NDIM", "%d", get_ndim()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload NDIM");


  // //////////////////////////////////////////////////////////////////////
  //
  // STATE
  //
  std::string state = Signal::State2string( get_state() );
  if (ascii_header_set (header, "STATE", "%s", state.c_str()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload STATE");

  // //////////////////////////////////////////////////////////////////////
  //
  // TSAMP
  //
  /* IMPORTANT: TSAMP is the sampling period in microseconds */

  double sampling_interval = 1e6 / get_rate();
  if (ascii_header_set (header, "TSAMP", "%lf", sampling_interval)<0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload TSAMP");


  // //////////////////////////////////////////////////////////////////////
  //
  // UTC_START
  //
  MJD epoch = get_start_time();
  MJD integer_second ( epoch.intday(), epoch.get_secs(), 0.0 );

  char datestr [64];
  integer_second.datestr( datestr, 64, "%Y-%m-%d-%H:%M:%S" );

  if (ascii_header_set (header, "UTC_START", "%s", datestr) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload UTC_START");

  // //////////////////////////////////////////////////////////////////////
  //
  // OBS_OFFSET
  //
  double offset_samples = epoch.get_fracsec() * get_rate();
  uint64_t offset_bytes = get_nbytes( (uint64_t)offset_samples );

  if (ascii_header_set (header, "OBS_OFFSET", UI64, offset_bytes) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload OBS_OFFSET");


  // //////////////////////////////////////////////////////////////////////
  //
  // INSTRUMENT
  //
  if (ascii_header_set (header, "INSTRUMENT", "%s", get_machine().c_str()) < 0)
    throw Error (InvalidState, "ASCIIObservation", "failed unload INSTRUMENT");

}
Exemplo n.º 22
0
double second (const MJD& mjd)
{
  return  mjd.get_secs() + mjd.get_fracsec();
}
Exemplo n.º 23
0
void Calibration::SignalPath::disengage_time_variations (const MJD& epoch) 
try
{
#ifdef _DEBUG
  cerr << "DISENGAGE epoch=" << epoch.printdays(16) << endl;
#endif

  if (!time_variations_engaged)
    return;

  time_variations_engaged = false;

  BackendFeed* physical = dynamic_cast<BackendFeed*>( response.get() );
  if (!physical)
    return;

  time.set_value (epoch);

  Univariate<Scalar>* zero = 0;

#ifdef _DEBUG
  cerr << "before disengage nparam = " << physical->get_nparam() << endl;
#endif

  if (gain)
  {
#ifdef _DEBUG
    cerr << "disengage gain" << endl;
#endif

    if (!constant_pulsar_gain)
    {
      physical->set_gain( zero );
      physical->set_gain( gain->estimate() );
    }
    else if (pcal_gain_chain)
    {
      pcal_gain_chain->set_constraint( 0, zero );
      pcal_gain->set_gain( gain->estimate() );
    }

  }

  if (pcal_gain)
    physical->set_gain( pcal_gain->get_gain() );

  if (diff_gain)
  {
#ifdef _DEBUG
    cerr << "disengage diff_gain value=" << diff_gain->estimate() << endl;
#endif
    physical->set_diff_gain( zero );
    physical->set_diff_gain( diff_gain->estimate() );
  }

  if (diff_phase)
  {
#ifdef _DEBUG
    cerr << "disengage diff_phase value=" << diff_phase->estimate() << endl;
#endif
    physical->set_diff_phase( zero );
    physical->set_diff_phase( diff_phase->estimate() );
  }

#ifdef _DEBUG
  cerr << "after disengage nparam = " << physical->get_nparam() << endl;
#endif

}
catch (Error& error)
{
  throw error += "Calibration::SignalPath::disengage_time_variations";
}