Пример #1
0
def par_diff(params_new, folder):
  ar = glob(os.path.join(folder, "*.ar"))[-1]
  load_archive = psrchive.Archive_load(ar)
  par = load_archive.get_ephemeris()
  psr = par.get_value('PSR')
  if psr == "": psr = par.get_value('PSRJ')
  print "PSR ", psr
  print "P0 diff: {:.2e} s".format(params_new['P0'] - float(par.get_value('P0')))
  print "DM diff: {:.2e} pc/cc".format(params_new['DM'] - float(par.get_value('DM')))
  
  dist = 60. * np.rad2deg(np.sqrt( (ra_to_rad(par.get_value('RAJ'))-ra_to_rad(params_new['RAJ']))**2 + (dec_to_rad(par.get_value('DECJ'))-dec_to_rad(params_new['DECJ']))**2 ))
  print "Distance: {:.3f}'".format(dist)
  print ""
  return
Пример #2
0
def main():
    pfdfn = sys.argv[1]

    pfd = prepfold.pfd(pfdfn)

    cand = candidate.Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                        psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                        psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                        pfdfn)

    print "Loaded %s" % cand.pfdfn
    print "    Best topo period (s): %f" % cand.topo_period
    print "    Best bary period (s): %f" % cand.bary_period
    print "    Best DM (cm^-3/pc): %f" % cand.dm
    print "    RA (J2000 - deg): %f" % cand.raj_deg
    print "    Dec (J2000 - deg): %f" % cand.decj_deg

    print "-"*10
    pprint.pprint(cand.__dict__)
    print "-"*10

    gauss.add_data(cand)

    print "Added gaussian fit to cand"
    pprint.pprint(cand.__dict__)
    print "-"*10
    fit_and_plot(cand)
Пример #3
0
def main():
  parser = OptionParser(usage)

  (opts, args) = parser.parse_args()			
	
  # Scan files
  db = Database(db="local-SBON512")
  DBconn = db.conn
  DBcursor = db.cursor

  QUERY = "SELECT header_id, right_ascension, declination FROM headers"
  #QUERY = "SHOW tables"
  DBcursor.execute(QUERY)
  result_query = [list(row) for row in DBcursor.fetchall()]
  print result_query

  for header in result_query:

      # Convert in degrees
      ra_deg = psr_utils.ra_to_rad(header[1]) * RADTODEG
      dec_deg = psr_utils.dec_to_rad(header[2]) * RADTODEG

      # Convert in galactic coord
      galactic_longitude, galactic_latitude = coordconv.eqdeg_to_galdeg(ra_deg, dec_deg)

      QUERY = "UPDATE headers SET n_bits=4, galactic_longitude=%f, galactic_latitude=%f, ra_deg=%f, dec_deg=%f WHERE header_id=%d;\n"%(galactic_longitude, galactic_latitude, ra_deg, dec_deg, header[0])
      print QUERY
      DBcursor.execute(QUERY)

  
  DBconn.close()
Пример #4
0
    def show_known_psrs(self, cand):
	txt = []

	# Convert RA and DEC of the candidate in rad
	print "known_psrs::show_known_psrs> Cand Positions: ", cand.ra , cand.dec
	cand_RA = psr_utils.ra_to_rad(cand.ra) 
	cand_DEC = psr_utils.dec_to_rad(cand.dec) 

	for i in range(len(self.psr_list)):
	    #print "cand RA = %s   psr RA = %s"%(cand.ra, self.psr_list[i].ra)
	    if abs(cand_RA - self.psr_list[i].ra) < 0.006 and abs(cand_DEC - self.psr_list[i].dec) < 0.006:
		doc = "%s\n  RA : %s\n  DEC : %s\n  Period : %s\n  Ratio : %.4f\n  DM : %s\n  Survey %s"% \
			(self.psr_list[i].psrname, self.psr_list[i].ra_str, \
			self.psr_list[i].dec_str, self.psr_list[i].period, \
			float(self.psr_list[i].period)/ cand.period, \
			 self.psr_list[i].dm, self.psr_list[i].survey)
		txt.append(doc)

	txt = "\n\n".join(txt)

	# create a new scrolled window.
	scrolled_window = gtk.ScrolledWindow()
	scrolled_window.set_border_width(10)
	scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)

	if txt:
	    label = gtk.Label(txt)
	    scrolled_window.add_with_viewport(label)

	return scrolled_window    
Пример #5
0
def read_pfd_file(pfdfn):
    """Return a Candidate object for the pfd given.
        Input:
            pfdfn: PRESTO *.pfd file name.
        Output:
            cand: Candidate object constructed from the given pfd
                file name.
    """
    pfd = prepfold.pfd(pfdfn)
    cand = Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                    psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                    psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                    pfdfn)
    return cand
Пример #6
0
def read_pfd_file(pfdfn):
    """Return a Candidate object for the pfd given.

        Input:
            pfdfn: PRESTO *.pfd file name.

        Output:
            cand: Candidate object constructed from the given pfd
                file name.
    """
    pfd = prepfold.pfd(pfdfn)
    cand = Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                    psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                    psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                    pfdfn)
    return cand
Пример #7
0
def main():
    pfdfn = sys.argv[1]

    pfd = myprepfold.pfd(pfdfn)

    cand = candidate.Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                        psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                        psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                        pfdfn)

    print "Loaded %s" % cand.pfdfn
    print "    Best topo period (s): %f" % cand.topo_period
    print "    Best bary period (s): %f" % cand.bary_period
    print "    Best DM (cm^-3/pc): %f" % cand.dm
    print "    RA (J2000 - deg): %f" % cand.raj_deg
    print "    Dec (J2000 - deg): %f" % cand.decj_deg

    print "-"*10
    pprint.pprint(cand.__dict__)
    print "-"*10

    from rating_classes import time_vs_phase
    time_vs_phase.TimeVsPhaseClass().add_data(cand)
    tvph = cand.time_vs_phase

    print "Added time vs phase data to cand"
    pprint.pprint(cand.__dict__)
    print "-"*10

    pprint.pprint(cand.time_vs_phase.__dict__)

    print "DEBUG: tvph.pdelays_bins", tvph.pdelays_bins
    print "DEBUG: pfd.pdelays_bins", pfd.pdelays_bins
    
    pfd.dedisperse(doppler=1)
    print "DEBUG: tvph.dm, pfd.currdm", tvph.dm, pfd.currdm
    
    if pfd.fold_pow == 1.0:
        bestp = pfd.bary_p1
        bestpd = pfd.bary_p2
        bestpdd = pfd.bary_p3
    else:
        bestp = pfd.topo_p1
        bestpd = pfd.topo_p2
        bestpdd = pfd.topo_p3

    pfd.adjust_period()
    tvph.adjust_period(bestp, bestpd, bestpdd)
    mypfd_tvph = pfd.time_vs_phase()
    print test_img(tvph.data, mypfd_tvph, 1e-6)
    plt.figure()
    plt.plot(tvph.data.sum(axis=0), label='TvPh')
    plt.plot(mypfd_tvph.sum(axis=0), label='PFD')
    plt.title("P=%g s, Pd=%g s/s, Pdd=%g s/s^2" % (bestp, bestpd, bestpdd))
    plt.legend(loc='best')
    for ii in range(10):
        frac_p = 1+(np.random.rand(1)*2-1)/100.0
        frac_pd = 1+(np.random.rand(1)*2-1)/100.0
        frac_pdd = 1+(np.random.rand(1)*2-1)/100.0
        p = frac_p*bestp
        pd = frac_pd*bestpd
        pdd = frac_pdd*bestpdd
        print "Shuffling for the %dth time" % ii
        print "frac_p, frac_pd, frac_pdd", frac_p, frac_pd, frac_pdd

        tvph.adjust_period(p, pd, pdd)
        mypfd_tvph = pfd.time_vs_phase(p, pd, pdd)
        print test_img(tvph.data, mypfd_tvph, 1e-9)

        plt.figure()
        plt.plot(tvph.data.sum(axis=0), label='TvPh')
        plt.plot(mypfd_tvph.sum(axis=0), label='PFD')
        plt.title("P=%g s, Pd=%g s/s, Pdd=%g s/s^2" % (p, pd, pdd))
        plt.legend(loc='best')
    plt.show()
    sys.exit(1)

    print "Check if time_vs_phase rotates out and back to same array"
    orig = cand.time_vs_phase.data.copy()
    orig_p = cand.time_vs_phase.curr_p
    orig_pd = cand.time_vs_phase.curr_pd
    orig_pdd = cand.time_vs_phase.curr_pdd
    cand.time_vs_phase.adjust_period(p=orig_p-0.00123, pd=0, pdd=0)
    mod = cand.time_vs_phase.data.copy()
    cand.time_vs_phase.adjust_period(p=orig_p, pd=orig_pd, pdd=orig_pdd)
    new = cand.time_vs_phase.data.copy()

    print "Compare orig/mod"
    print (orig == mod).all()
    print "Compare mod/new"
    print (mod == new).all()
    print "Compare orig/new"
    print (orig == new).all()

    print "Compare with best prof"
    # Create best prof file
    print "show_pfd -noxwin %s" % cand.info['pfdfn']
    subprocess.call("show_pfd -noxwin %s" % cand.info['pfdfn'], shell=True, stdout=open(os.devnull))
    prof = np.loadtxt(os.path.split(cand.pfd.pfd_filename+".bestprof")[-1], usecols=(1,))

    pfd = cand.pfd
    if pfd.fold_pow == 1.0:
        bestp = pfd.bary_p1
        bestpd = pfd.bary_p2
        bestpdd = pfd.bary_p3
    else:
        bestp = pfd.topo_p1
        bestpd = pfd.topo_p2
        bestpdd = pfd.topo_p3
    cand.time_vs_phase.adjust_period(bestp, bestpd, bestpdd)
    tvph = pfd.time_vs_phase()
    print test_img(cand.time_vs_phase.data, tvph, 1e-6)
    plt.plot(cand.time_vs_phase.get_profile())
    plt.plot(tvph.sum(axis=0).squeeze())
    plt.show()
Пример #8
0
 def __init__(self, parfilenm):
     self.FILE = parfilenm
     pf = open(parfilenm)
     for line in pf.readlines():
         # Skip comments
         if line[0] == "#":
             continue
         # Convert any 'D-' or 'D+' to 'E-' or 'E+'
         line = line.replace("D-", "E-")
         line = line.replace("D+", "E+")
         splitline = line.split()
         # Skip blank lines
         if len(splitline) == 0:
             continue
         key = splitline[0]
         if key in str_keys:
             setattr(self, key, splitline[1])
         elif key in float_keys:
             try:
                 setattr(self, key, float(splitline[1]))
             except ValueError:
                 pass
         if len(splitline) == 3:  # Some parfiles don't have flags, but do have errors
             if splitline[2] not in ["0", "1"]:
                 setattr(self, key + "_ERR", float(splitline[2]))
         if len(splitline) == 4:
             setattr(self, key + "_ERR", float(splitline[3]))
     # Deal with Ecliptic coords
     if hasattr(self, "BETA") and hasattr(self, "LAMBDA"):
         setattr(self, "ELAT", self.BETA)
         setattr(self, "ELONG", self.LAMBDA)
     if slalib and hasattr(self, "ELAT") and hasattr(self, "ELONG"):
         if hasattr(self, "POSEPOCH"):
             epoch = self.POSEPOCH
         else:
             epoch = self.PEPOCH
         ra_rad, dec_rad = sla_ecleq(self.ELONG * pu.DEGTORAD, self.ELAT * pu.DEGTORAD, epoch)
         rstr = pu.coord_to_string(*pu.rad_to_hms(ra_rad))
         dstr = pu.coord_to_string(*pu.rad_to_dms(dec_rad))
         setattr(self, "RAJ", rstr)
         setattr(self, "DECJ", dstr)
     if hasattr(self, "RAJ"):
         setattr(self, "RA_RAD", pu.ra_to_rad(self.RAJ))
     if hasattr(self, "DECJ"):
         setattr(self, "DEC_RAD", pu.dec_to_rad(self.DECJ))
     # Compute the Galactic coords
     if slalib and hasattr(self, "RA_RAD") and hasattr(self, "DEC_RAD"):
         l, b = sla_eqgal(self.RA_RAD, self.DEC_RAD)
         setattr(self, "GLONG", l * pu.RADTODEG)
         setattr(self, "GLAT", b * pu.RADTODEG)
     # Compute the Ecliptic coords
     if slalib and hasattr(self, "RA_RAD") and hasattr(self, "DEC_RAD"):
         if hasattr(self, "POSEPOCH"):
             epoch = self.POSEPOCH
         else:
             epoch = self.PEPOCH
         elon, elat = sla_eqecl(self.RA_RAD, self.DEC_RAD, epoch)
         setattr(self, "ELONG", elon * pu.RADTODEG)
         setattr(self, "ELAT", elat * pu.RADTODEG)
     if hasattr(self, "P"):
         setattr(self, "P0", self.P)
     if hasattr(self, "P0"):
         setattr(self, "F0", 1.0 / self.P0)
     if hasattr(self, "F0"):
         setattr(self, "P0", 1.0 / self.F0)
     if hasattr(self, "FB0"):
         setattr(self, "PB", (1.0 / self.FB0) / 86400.0)
     if hasattr(self, "P0_ERR"):
         if hasattr(self, "P1_ERR"):
             f, ferr, fd, fderr = pu.pferrs(self.P0, self.P0_ERR, self.P1, self.P1_ERR)
             setattr(self, "F0_ERR", ferr)
             setattr(self, "F1", fd)
             setattr(self, "F1_ERR", fderr)
         else:
             f, fd, = pu.p_to_f(self.P0, self.P1)
             setattr(self, "F0_ERR", self.P0_ERR / (self.P0 * self.P0))
             setattr(self, "F1", fd)
     if hasattr(self, "F0_ERR"):
         if hasattr(self, "F1_ERR"):
             p, perr, pd, pderr = pu.pferrs(self.F0, self.F0_ERR, self.F1, self.F1_ERR)
             setattr(self, "P0_ERR", perr)
             setattr(self, "P1", pd)
             setattr(self, "P1_ERR", pderr)
         else:
             p, pd, = pu.p_to_f(self.F0, self.F1)
             setattr(self, "P0_ERR", self.F0_ERR / (self.F0 * self.F0))
             setattr(self, "P1", pd)
     if hasattr(self, "EPS1") and hasattr(self, "EPS2"):
         ecc = math.sqrt(self.EPS1 * self.EPS1 + self.EPS2 * self.EPS2)
         omega = math.atan2(self.EPS1, self.EPS2)
         setattr(self, "E", ecc)
         setattr(self, "OM", omega * pu.RADTODEG)
         setattr(self, "T0", self.TASC + self.PB * omega / pu.TWOPI)
     if hasattr(self, "PB") and hasattr(self, "A1") and not (hasattr(self, "E") or hasattr(self, "ECC")):
         setattr(self, "E", 0.0)
     if hasattr(self, "T0") and not hasattr(self, "TASC"):
         setattr(self, "TASC", self.T0 - self.PB * self.OM / 360.0)
     pf.close()
Пример #9
0
    def read(self, parfilenm):
        self.FILE = parfilenm
        #print parfilenm
        pf = open(parfilenm)
        for line in pf.readlines():
            # Convert any 'D-' or 'D+' to 'E-' or 'E+'
            line = line.replace("D-", "E-")
            line = line.replace("D+", "E+")
            try:
                splitline = line.split()
                key = splitline[0]
                if key in str_keys:
                    setattr(self, key, splitline[1])
                elif key in float_keys:
                    try:
                        setattr(self, key, float(splitline[1]))
                    except ValueError:
                        pass
                if len(
                        splitline
                ) == 3:  # Some parfiles don't have flags, but do have errors
                    if splitline[2] not in ['0', '1']:
                        setattr(self, key + '_ERR', float(splitline[2]))
                if len(splitline) == 4:
                    setattr(self, key + '_ERR', float(splitline[3]))
            except:
                if line.strip():
                    print ' ', line
# Read PSR name
        if hasattr(self, 'PSR'):
            setattr(self, 'PSR', self.PSR)
        if hasattr(self, 'PSRJ'):
            setattr(self, 'PSRJ', self.PSRJ)
        # Deal with Ecliptic coords
        if (hasattr(self, 'BETA') and hasattr(self, 'LAMBDA')):
            self.use_eclip = True
            setattr(self, 'ELAT', self.BETA)
            setattr(self, 'ELONG', self.LAMBDA)
        if (slalib and hasattr(self, 'ELAT') and hasattr(self, 'ELONG')):
            self.use_eclip = True
            if hasattr(self, 'POSEPOCH'):
                epoch = self.POSEPOCH
            else:
                epoch = self.PEPOCH
            ra_rad, dec_rad = sla_ecleq(self.ELONG * pu.DEGTORAD,
                                        self.ELAT * pu.DEGTORAD, epoch)
            rstr = pu.coord_to_string(*pu.rad_to_hms(ra_rad))
            dstr = pu.coord_to_string(*pu.rad_to_dms(dec_rad))
            setattr(self, 'RAJ', rstr)
            setattr(self, 'DECJ', dstr)
        if (slalib and hasattr(self, 'ELAT') and hasattr(self, 'ELONG')):
            setattr(self, 'PMELONG', self.PMELONG)
            setattr(self, 'PMELAT', self.PMELAT)
        if hasattr(self, 'RAJ'):
            setattr(self, 'RA_RAD', pu.ra_to_rad(self.RAJ))
        if hasattr(self, 'DECJ'):
            setattr(self, 'DEC_RAD', pu.dec_to_rad(self.DECJ))
        # Compute the Galactic coords
        if (slalib and hasattr(self, 'RA_RAD') and hasattr(self, 'DEC_RAD')):
            l, b = sla_eqgal(self.RA_RAD, self.DEC_RAD)
            setattr(self, 'GLONG', l * pu.RADTODEG)
            setattr(self, 'GLAT', b * pu.RADTODEG)
        # Compute the Ecliptic coords
        if (slalib and hasattr(self, 'RA_RAD') and hasattr(self, 'DEC_RAD')):
            if hasattr(self, 'POSEPOCH'):
                epoch = self.POSEPOCH
            else:
                epoch = self.PEPOCH
            elon, elat = sla_eqecl(self.RA_RAD, self.DEC_RAD, epoch)
            setattr(self, 'ELONG', elon * pu.RADTODEG)
            setattr(self, 'ELAT', elat * pu.RADTODEG)
        if hasattr(self, 'P'):
            setattr(self, 'P0', self.P)
        if hasattr(self, 'P0'):
            setattr(self, 'F0', 1.0 / self.P0)
        if hasattr(self, 'F0'):
            setattr(self, 'P0', 1.0 / self.F0)
        if hasattr(self, 'F1'):
            setattr(self, 'P1', -self.F1 / (self.F0 * self.F0))
        if hasattr(self, 'FB0'):
            setattr(self, 'PB', (1.0 / self.FB0) / 86400.0)
        if hasattr(self, 'P0_ERR'):
            if hasattr(self, 'P1_ERR'):
                f, ferr, fd, fderr = pu.pferrs(self.P0, self.P0_ERR, self.P1,
                                               self.P1_ERR)
                setattr(self, 'F0_ERR', ferr)
                setattr(self, 'F1', fd)
                setattr(self, 'F1_ERR', fderr)
            else:
                f, fd, = pu.p_to_f(self.P0, self.P1)
                setattr(self, 'F0_ERR', self.P0_ERR / (self.P0 * self.P0))
                setattr(self, 'F1', fd)
        if hasattr(self, 'F0_ERR'):
            if hasattr(self, 'F1_ERR'):
                p, perr, pd, pderr = pu.pferrs(self.F0, self.F0_ERR, self.F1,
                                               self.F1_ERR)
                setattr(self, 'P0_ERR', perr)
                setattr(self, 'P1', pd)
                setattr(self, 'P1_ERR', pderr)
            else:
                p, pd, = pu.p_to_f(self.F0, self.F1)
                setattr(self, 'P0_ERR', self.F0_ERR / (self.F0 * self.F0))
                setattr(self, 'P1', pd)
        if hasattr(self, 'DM'):
            setattr(self, 'DM', self.DM)
        if hasattr(self, 'DM1'):
            setattr(self, 'DM1', self.DM1)
        if hasattr(self, 'DM2'):
            setattr(self, 'DM2', self.DM2)
        if hasattr(self, 'EPS1') and hasattr(self, 'EPS2'):
            self.use_ell = True
            ecc = math.sqrt(self.EPS1 * self.EPS1 + self.EPS2 * self.EPS2)
            omega = math.atan2(self.EPS1, self.EPS2)
            if self.EPS1 == 0.0 and self.EPS2 == 0.0:
                ecc_err = pow(
                    pow(self.EPS1_ERR, 2) + pow(self.EPS2_ERR, 2), .5)
            else:
                ecc_err = pow(
                    pow(self.EPS1 * self.EPS1_ERR, 2) +
                    pow(self.EPS2 * self.EPS2_ERR, 2), 0.5) / ecc
            setattr(self, 'ECC', ecc)
            setattr(self, 'ECC_ERR', ecc_err)
            setattr(self, 'OM', omega)
        if hasattr(self, 'PB') and hasattr(self,
                                           'A1') and not hasattr(self, 'ECC'):
            setattr(self, 'ECC', 0.0)
        if hasattr(self, 'BINARY'):
            setattr(self, 'BINARY', self.BINARY)
        if hasattr(self, 'KIN'):
            setattr(self, 'SINI', math.sin(self.KIN * np.pi / 180.))
            setattr(
                self, 'SINI_ERR',
                math.sin(self.KIN * np.pi / 180.) -
                math.sin(self.KIN * np.pi / 180. -
                         self.KIN_ERR * np.pi / 180.))
        pf.close()
Пример #10
0
 def __init__(self, parfilenm):
     self.FILE = parfilenm
     pf = open(parfilenm)
     for line in pf.readlines():
         # Convert any 'D-' or 'D+' to 'E-' or 'E+'
         line = line.replace("D-", "E-")
         line = line.replace("D+", "E+")
         splitline = line.split()
         key = splitline[0]
         if key in str_keys:
             setattr(self, key, splitline[1])
         elif key in float_keys:
             try:
                 setattr(self, key, float(splitline[1]))
             except ValueError:
                 pass
         if len(splitline)==3:  # Some parfiles don't have flags, but do have errors
             if splitline[2] not in ['0', '1']:
                 setattr(self, key+'_ERR', float(splitline[2]))
         if len(splitline)==4:
             setattr(self, key+'_ERR', float(splitline[3]))
     # Deal with Ecliptic coords
     if (hasattr(self, 'BETA') and hasattr(self, 'LAMBDA')):
         setattr(self, 'ELAT', self.BETA)
         setattr(self, 'ELONG', self.LAMBDA)
     if (slalib and hasattr(self, 'ELAT') and hasattr(self, 'ELONG')):
         if hasattr(self, 'POSEPOCH'):
             epoch = self.POSEPOCH
         else:
             epoch = self.PEPOCH
         ra_rad, dec_rad = sla_ecleq(self.ELONG*pu.DEGTORAD,
                                     self.ELAT*pu.DEGTORAD, epoch)
         rstr = pu.coord_to_string(*pu.rad_to_hms(ra_rad))
         dstr = pu.coord_to_string(*pu.rad_to_dms(dec_rad))
         setattr(self, 'RAJ', rstr)
         setattr(self, 'DECJ', dstr)
     if hasattr(self, 'RAJ'):
         setattr(self, 'RA_RAD', pu.ra_to_rad(self.RAJ))
     if hasattr(self, 'DECJ'):
         setattr(self, 'DEC_RAD', pu.dec_to_rad(self.DECJ))
     # Compute the Galactic coords
     if (slalib and hasattr(self, 'RA_RAD') and hasattr(self, 'DEC_RAD')):
         l, b = sla_eqgal(self.RA_RAD, self.DEC_RAD)
         setattr(self, 'GLONG', l*pu.RADTODEG)
         setattr(self, 'GLAT', b*pu.RADTODEG)
     # Compute the Ecliptic coords
     if (slalib and hasattr(self, 'RA_RAD') and hasattr(self, 'DEC_RAD')):
         if hasattr(self, 'POSEPOCH'):
             epoch = self.POSEPOCH
         else:
             epoch = self.PEPOCH
         elon, elat = sla_eqecl(self.RA_RAD, self.DEC_RAD, epoch)
         setattr(self, 'ELONG', elon*pu.RADTODEG)
         setattr(self, 'ELAT', elat*pu.RADTODEG)
     if hasattr(self, 'P'):
         setattr(self, 'P0', self.P)
     if hasattr(self, 'P0'):
         setattr(self, 'F0', 1.0/self.P0)
     if hasattr(self, 'F0'):
         setattr(self, 'P0', 1.0/self.F0)
     if hasattr(self, 'FB0'):
         setattr(self, 'PB', (1.0/self.FB0)/86400.0)
     if hasattr(self, 'P0_ERR'):
         if hasattr(self, 'P1_ERR'):
             f, ferr, fd, fderr = pu.pferrs(self.P0, self.P0_ERR,
                                            self.P1, self.P1_ERR)
             setattr(self, 'F0_ERR', ferr) 
             setattr(self, 'F1', fd) 
             setattr(self, 'F1_ERR', fderr) 
         else:
             f, fd, = pu.p_to_f(self.P0, self.P1)
             setattr(self, 'F0_ERR', self.P0_ERR/(self.P0*self.P0))
             setattr(self, 'F1', fd) 
     if hasattr(self, 'F0_ERR'):
         if hasattr(self, 'F1_ERR'):
             p, perr, pd, pderr = pu.pferrs(self.F0, self.F0_ERR,
                                            self.F1, self.F1_ERR)
             setattr(self, 'P0_ERR', perr) 
             setattr(self, 'P1', pd) 
             setattr(self, 'P1_ERR', pderr) 
         else:
             p, pd, = pu.p_to_f(self.F0, self.F1)
             setattr(self, 'P0_ERR', self.F0_ERR/(self.F0*self.F0))
             setattr(self, 'P1', pd) 
     if hasattr(self, 'EPS1') and hasattr(self, 'EPS2'):
         ecc = math.sqrt(self.EPS1 * self.EPS1 + self.EPS2 * self.EPS2)
         omega = math.atan2(self.EPS1, self.EPS2)
         setattr(self, 'E', ecc)
         setattr(self, 'OM', omega * pu.RADTODEG)
         setattr(self, 'T0', self.TASC + self.PB * omega/pu.TWOPI)
     if hasattr(self, 'PB') and hasattr(self, 'A1') and not \
            (hasattr(self, 'E') or hasattr(self, 'ECC')):
         setattr(self, 'E', 0.0)
     if hasattr(self, 'T0') and hasattr(self, 'PB') and hasattr(self, 'OM')  and not hasattr(self, 'TASC'):
         setattr(self, 'TASC', self.T0 - self.PB * self.OM/360.0)
     pf.close()
Пример #11
0
def main():
    pfdfn = sys.argv[1]

    pfd = prepfold.pfd(pfdfn)

    cand = candidate.Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                        psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                        psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                        pfdfn)

    print "Loaded %s" % cand.pfdfn
    print "    Best topo period (s): %f" % cand.topo_period
    print "    Best bary period (s): %f" % cand.bary_period
    print "    Best DM (cm^-3/pc): %f" % cand.dm
    print "    RA (J2000 - deg): %f" % cand.raj_deg
    print "    Dec (J2000 - deg): %f" % cand.decj_deg

    print "-"*10
    pprint.pprint(cand.__dict__)
    print "-"*10

    from rating_classes import freq_vs_phase
    fvph = freq_vs_phase.FreqVsPhaseClass()
    fvph.add_data(cand)

    print "Added freq vs phase data to cand"
    pprint.pprint(cand.__dict__)
    print "-"*10

    pprint.pprint(cand.freq_vs_phase.__dict__)

    print "Check if freq_vs_phase rotates out and back to same array"
    orig = cand.freq_vs_phase.data.copy()
    orig_dm = cand.freq_vs_phase.curr_dm
    cand.freq_vs_phase.dedisperse(0)
    mod = cand.freq_vs_phase.data.copy()
    cand.freq_vs_phase.dedisperse(orig_dm)
    new = cand.freq_vs_phase.data.copy()

    print "Compare orig/mod"
    print (orig == mod).all()
    print "Compare mod/new"
    print (mod == new).all()
    print "Compare orig/new"
    print (orig == new).all()

    print "Compare with best prof"
    # Create best prof file
    print "show_pfd -noxwin %s" % cand.info['pfdfn']
    subprocess.call("show_pfd -noxwin %s" % cand.info['pfdfn'], shell=True, stdout=open(os.devnull))
    pfd_bestprof = np.loadtxt(os.path.split(cand.pfd.pfd_filename+".bestprof")[-1], usecols=(1,))

    cand.freq_vs_phase.dedisperse(cand.pfd.bestdm)
    fvph_prof = cand.freq_vs_phase.data.sum(axis=0).squeeze()
    print test_profiles(pfd_bestprof, fvph_prof, 1e-6)
    
    print "Testing dedispersion"
    for dm in np.random.randint(0, 1000, size=10):
        print "DM: %g" % dm,
        cand.freq_vs_phase.dedisperse(dm)
        fvph_prof = cand.freq_vs_phase.get_profile()

        cand.pfd.dedisperse(dm, doppler=1)
        cand.pfd.adjust_period()
        pfd_prof = cand.pfd.time_vs_phase().sum(axis=0).squeeze()
        print test_profiles(fvph_prof, pfd_prof, 1e-6)
        plt.figure(dm)
        plt.plot(fvph_prof, label="FvsPh")
        plt.plot(pfd_prof, label="PFD")
        plt.title("DM: %g" % dm)
        plt.legend(loc='best')
    plt.show()
Пример #12
0
def main():
    pfdfn = sys.argv[1]

    pfd = prepfold.pfd(pfdfn)

    cand = candidate.Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                        psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                        psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                        pfdfn)

    print "Loaded %s" % cand.pfdfn
    print "    Best topo period (s): %f" % cand.topo_period
    print "    Best bary period (s): %f" % cand.bary_period
    print "    Best DM (cm^-3/pc): %f" % cand.dm
    print "    RA (J2000 - deg): %f" % cand.raj_deg
    print "    Dec (J2000 - deg): %f" % cand.decj_deg

    print "-" * 10
    pprint.pprint(cand.__dict__)
    print "-" * 10

    from rating_classes import freq_vs_phase
    fvph = freq_vs_phase.FreqVsPhaseClass()
    fvph.add_data(cand)

    print "Added freq vs phase data to cand"
    pprint.pprint(cand.__dict__)
    print "-" * 10

    pprint.pprint(cand.freq_vs_phase.__dict__)

    print "Check if freq_vs_phase rotates out and back to same array"
    orig = cand.freq_vs_phase.data.copy()
    orig_dm = cand.freq_vs_phase.curr_dm
    cand.freq_vs_phase.dedisperse(0)
    mod = cand.freq_vs_phase.data.copy()
    cand.freq_vs_phase.dedisperse(orig_dm)
    new = cand.freq_vs_phase.data.copy()

    print "Compare orig/mod"
    print(orig == mod).all()
    print "Compare mod/new"
    print(mod == new).all()
    print "Compare orig/new"
    print(orig == new).all()

    print "Compare with best prof"
    # Create best prof file
    print "show_pfd -noxwin %s" % cand.info['pfdfn']
    subprocess.call("show_pfd -noxwin %s" % cand.info['pfdfn'],
                    shell=True,
                    stdout=open(os.devnull))
    pfd_bestprof = np.loadtxt(os.path.split(cand.pfd.pfd_filename +
                                            ".bestprof")[-1],
                              usecols=(1, ))

    cand.freq_vs_phase.dedisperse(cand.pfd.bestdm)
    fvph_prof = cand.freq_vs_phase.data.sum(axis=0).squeeze()
    print test_profiles(pfd_bestprof, fvph_prof, 1e-6)

    print "Testing dedispersion"
    for dm in np.random.randint(0, 1000, size=10):
        print "DM: %g" % dm,
        cand.freq_vs_phase.dedisperse(dm)
        fvph_prof = cand.freq_vs_phase.get_profile()

        cand.pfd.dedisperse(dm, doppler=1)
        cand.pfd.adjust_period()
        pfd_prof = cand.pfd.time_vs_phase().sum(axis=0).squeeze()
        print test_profiles(fvph_prof, pfd_prof, 1e-6)
        plt.figure(dm)
        plt.plot(fvph_prof, label="FvsPh")
        plt.plot(pfd_prof, label="PFD")
        plt.title("DM: %g" % dm)
        plt.legend(loc='best')
    plt.show()
Пример #13
0
def Known_Pulsar_Rating(pfd):
    """
    Calculate the probability that a candidate is a known pulsar or a harmonic
    of a known pulsar.

    Parameters
    ----------
    pfd : class
        An instance of the prepfold.pfd class

    Returns
    -------
    names : list
        A list of ratings names
    ratings : list
        A list of ratings values
    """
    # The rating name
    name1 = "Known_Pulsar_Rating"
    # A fudge factor for error calculations
    factor = 0.3*pfd.proflen

    # Get the candidate RA and DEC (in radians)
    cand_ra  = PU.ra_to_rad(pfd.rastr)
    cand_dec = PU.dec_to_rad(pfd.decstr)

    # Get the period and folding epoch from bestprof, if it exists
    if hasattr(pfd.bestprof, "p0"):
        cand_p     = pfd.bestprof.p0
        cand_epoch = pfd.bestprof.epochi + pfd.bestprof.epochf
        # Get the candidate period error from bestprof, if it exists
        if hasattr(pfd.bestprof, "p0err"):
            cand_p_err = factor*pfd.bestprof.p0err
        # Otherwise, try to estimate it
        else:
            cand_p_err = factor*cand_p**2/(pfd.proflen*pfd.T)
    # Otherwise, use the barycentric or topocentric values
    elif pfd.bary_p1 != 0.0:
        cand_p     = pfd.bary_p1
        cand_epoch = pfd.bepoch
        cand_p_err = factor*cand_p**2/(pfd.proflen*pfd.T)
    elif pfd.topo_p1 != 0.0:
        cand_p     = pfd.topo_p1
        cand_epoch = pfd.tepoch
        cand_p_err = factor*cand_p**2/(pfd.proflen*pfd.T)
    # Get the min and max frequencies for this observation
    f_min       = pfd.subfreqs.min()
    f_max       = pfd.subfreqs.max()
    # Get the candidate's best DM
    cand_dm     = pfd.bestdm
    # Try to estimate the DM error
    cand_dm_err = factor*cand_p*f_max**2*f_min**2/ \
                  (4.15e3*pfd.proflen*(f_max**2 - f_min**2))

    # Now loop through the catalog of known pulsars and find any that are
    # close to the candidate
    nearby_psrs = [psr for psr in PSRCAT.psrs \
                   if (hasattr(psr, "ra") and hasattr(psr, "dec") and \
                   sla_dsep(cand_ra,cand_dec,psr.ra,psr.dec)<1.3*BEAM_FWHM)]

    # If there were no pulsars nearby, return a rating of 0.0 and exit
    if len(nearby_psrs) == 0:
        rating1 = 0.0
        return [name1],[rating1]
    # Otherwise, try to estimate the probability that the candidate is a
    # known pulsar or its harmonic.  This is done by calculting the difference
    # between the candidates period and DM and those any nearby known pulsars,
    # normalized by the error in the candidate values (i.e., difference in
    # "sigmas").  Calculate the probability assuming Gaussian statistics.
    else:
        # Start off assuming zero probability that the candidate is known
        max_prob     = 0.0
        for psr in nearby_psrs:
            # If possible, calculate the known pulsar period at the observing
            # epoch
            if hasattr(psr,"pepoch"):
                delta_t = (cand_epoch - psr.pepoch)*86400.0 # seconds
                if hasattr(psr,"pd") and hasattr(psr,"pdd"):
                    psr_p = psr.p + psr.pd*delta_t + 0.5*psr.pdd*delta_t**2
                elif hasattr(psr,"pd"):
                    psr_p = psr.p + psr.pd*delta_t
            else:
                psr_p = psr.p
                
            p_prob  = 0.0 # The probability that the periods are the same
            # Try all harmonic ratios with up to 16 harmonics
            for a in xrange(16):
                a += 1.0 # Since xrange starts with 0
                for b in xrange(16):
                    b += 1.0 # Since xrange starts with 0
                    # Difference between candidate and known pulsar harmonic
                    delta_p = abs(a/b*cand_p - psr_p)
                    # Calculate the equivalent Gaussian probability
                    tmp_prob  = \
                         S.special.erfc(delta_p/((a/b)**2*cand_p_err)/ \
                                        N.sqrt(2))
                    # If this is the highest probability so far, store it
                    if tmp_prob > p_prob: p_prob       = tmp_prob

            # Update the total probability
            prob      = p_prob
            # Get the difference in DM
            delta_dm  = abs(cand_dm - psr.dm)
            # Multiply the total probability by the DM probability
            prob     *= S.special.erfc(delta_dm/cand_dm_err/N.sqrt(2))
            # Update max_prob if necessary
            if prob > max_prob: max_prob = prob

        # Store the rating
        rating1 = max_prob

        return [name1],[rating1]
Пример #14
0
def Known_Pulsar_Rating(pfd):
    """
    Calculate the probability that a candidate is a known pulsar or a harmonic
    of a known pulsar.

    Parameters
    ----------
    pfd : class
        An instance of the prepfold.pfd class

    Returns
    -------
    names : list
        A list of ratings names
    ratings : list
        A list of ratings values
    """
    # The rating name
    name1 = "Known_Pulsar_Rating"
    # A fudge factor for error calculations
    factor = 0.3 * pfd.proflen

    # Get the candidate RA and DEC (in radians)
    cand_ra = PU.ra_to_rad(pfd.rastr)
    cand_dec = PU.dec_to_rad(pfd.decstr)

    # Get the period and folding epoch from bestprof, if it exists
    if hasattr(pfd.bestprof, "p0"):
        cand_p = pfd.bestprof.p0
        cand_epoch = pfd.bestprof.epochi + pfd.bestprof.epochf
        # Get the candidate period error from bestprof, if it exists
        if hasattr(pfd.bestprof, "p0err"):
            cand_p_err = factor * pfd.bestprof.p0err
        # Otherwise, try to estimate it
        else:
            cand_p_err = factor * cand_p**2 / (pfd.proflen * pfd.T)
    # Otherwise, use the barycentric or topocentric values
    elif pfd.bary_p1 != 0.0:
        cand_p = pfd.bary_p1
        cand_epoch = pfd.bepoch
        cand_p_err = factor * cand_p**2 / (pfd.proflen * pfd.T)
    elif pfd.topo_p1 != 0.0:
        cand_p = pfd.topo_p1
        cand_epoch = pfd.tepoch
        cand_p_err = factor * cand_p**2 / (pfd.proflen * pfd.T)
    # Get the min and max frequencies for this observation
    f_min = pfd.subfreqs.min()
    f_max = pfd.subfreqs.max()
    # Get the candidate's best DM
    cand_dm = pfd.bestdm
    # Try to estimate the DM error
    cand_dm_err = factor*cand_p*f_max**2*f_min**2/ \
                  (4.15e3*pfd.proflen*(f_max**2 - f_min**2))

    # Now loop through the catalog of known pulsars and find any that are
    # close to the candidate
    nearby_psrs = [psr for psr in PSRCAT.psrs \
                   if (hasattr(psr, "ra") and hasattr(psr, "dec") and \
                   sla_dsep(cand_ra,cand_dec,psr.ra,psr.dec)<1.3*BEAM_FWHM)]

    # If there were no pulsars nearby, return a rating of 0.0 and exit
    if len(nearby_psrs) == 0:
        rating1 = 0.0
        return [name1], [rating1]
    # Otherwise, try to estimate the probability that the candidate is a
    # known pulsar or its harmonic.  This is done by calculting the difference
    # between the candidates period and DM and those any nearby known pulsars,
    # normalized by the error in the candidate values (i.e., difference in
    # "sigmas").  Calculate the probability assuming Gaussian statistics.
    else:
        # Start off assuming zero probability that the candidate is known
        max_prob = 0.0
        for psr in nearby_psrs:
            # If possible, calculate the known pulsar period at the observing
            # epoch
            if hasattr(psr, "pepoch"):
                delta_t = (cand_epoch - psr.pepoch) * 86400.0  # seconds
                if hasattr(psr, "pd") and hasattr(psr, "pdd"):
                    psr_p = psr.p + psr.pd * delta_t + 0.5 * psr.pdd * delta_t**2
                elif hasattr(psr, "pd"):
                    psr_p = psr.p + psr.pd * delta_t
            else:
                psr_p = psr.p

            p_prob = 0.0  # The probability that the periods are the same
            # Try all harmonic ratios with up to 16 harmonics
            for a in xrange(16):
                a += 1.0  # Since xrange starts with 0
                for b in xrange(16):
                    b += 1.0  # Since xrange starts with 0
                    # Difference between candidate and known pulsar harmonic
                    delta_p = abs(a / b * cand_p - psr_p)
                    # Calculate the equivalent Gaussian probability
                    tmp_prob  = \
                         S.special.erfc(delta_p/((a/b)**2*cand_p_err)/ \
                                        N.sqrt(2))
                    # If this is the highest probability so far, store it
                    if tmp_prob > p_prob: p_prob = tmp_prob

            # Update the total probability
            prob = p_prob
            # Get the difference in DM
            delta_dm = abs(cand_dm - psr.dm)
            # Multiply the total probability by the DM probability
            prob *= S.special.erfc(delta_dm / cand_dm_err / N.sqrt(2))
            # Update max_prob if necessary
            if prob > max_prob: max_prob = prob

        # Store the rating
        rating1 = max_prob

        return [name1], [rating1]
Пример #15
0
def main():
    pfdfn = sys.argv[1]

    pfd = myprepfold.pfd(pfdfn)

    cand = candidate.Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                        psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                        psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                        pfdfn)

    print "Loaded %s" % cand.pfdfn
    print "    Best topo period (s): %f" % cand.topo_period
    print "    Best bary period (s): %f" % cand.bary_period
    print "    Best DM (cm^-3/pc): %f" % cand.dm
    print "    RA (J2000 - deg): %f" % cand.raj_deg
    print "    Dec (J2000 - deg): %f" % cand.decj_deg

    print "-" * 10
    pprint.pprint(cand.__dict__)
    print "-" * 10

    from rating_classes import time_vs_phase
    time_vs_phase.TimeVsPhaseClass().add_data(cand)
    tvph = cand.time_vs_phase

    print "Added time vs phase data to cand"
    pprint.pprint(cand.__dict__)
    print "-" * 10

    pprint.pprint(cand.time_vs_phase.__dict__)

    print "DEBUG: tvph.pdelays_bins", tvph.pdelays_bins
    print "DEBUG: pfd.pdelays_bins", pfd.pdelays_bins

    pfd.dedisperse(doppler=1)
    print "DEBUG: tvph.dm, pfd.currdm", tvph.dm, pfd.currdm

    if pfd.fold_pow == 1.0:
        bestp = pfd.bary_p1
        bestpd = pfd.bary_p2
        bestpdd = pfd.bary_p3
    else:
        bestp = pfd.topo_p1
        bestpd = pfd.topo_p2
        bestpdd = pfd.topo_p3

    pfd.adjust_period()
    tvph.adjust_period(bestp, bestpd, bestpdd)
    mypfd_tvph = pfd.time_vs_phase()
    print test_img(tvph.data, mypfd_tvph, 1e-6)
    plt.figure()
    plt.plot(tvph.data.sum(axis=0), label='TvPh')
    plt.plot(mypfd_tvph.sum(axis=0), label='PFD')
    plt.title("P=%g s, Pd=%g s/s, Pdd=%g s/s^2" % (bestp, bestpd, bestpdd))
    plt.legend(loc='best')
    for ii in range(10):
        frac_p = 1 + (np.random.rand(1) * 2 - 1) / 100.0
        frac_pd = 1 + (np.random.rand(1) * 2 - 1) / 100.0
        frac_pdd = 1 + (np.random.rand(1) * 2 - 1) / 100.0
        p = frac_p * bestp
        pd = frac_pd * bestpd
        pdd = frac_pdd * bestpdd
        print "Shuffling for the %dth time" % ii
        print "frac_p, frac_pd, frac_pdd", frac_p, frac_pd, frac_pdd

        tvph.adjust_period(p, pd, pdd)
        mypfd_tvph = pfd.time_vs_phase(p, pd, pdd)
        print test_img(tvph.data, mypfd_tvph, 1e-9)

        plt.figure()
        plt.plot(tvph.data.sum(axis=0), label='TvPh')
        plt.plot(mypfd_tvph.sum(axis=0), label='PFD')
        plt.title("P=%g s, Pd=%g s/s, Pdd=%g s/s^2" % (p, pd, pdd))
        plt.legend(loc='best')
    plt.show()
    sys.exit(1)

    print "Check if time_vs_phase rotates out and back to same array"
    orig = cand.time_vs_phase.data.copy()
    orig_p = cand.time_vs_phase.curr_p
    orig_pd = cand.time_vs_phase.curr_pd
    orig_pdd = cand.time_vs_phase.curr_pdd
    cand.time_vs_phase.adjust_period(p=orig_p - 0.00123, pd=0, pdd=0)
    mod = cand.time_vs_phase.data.copy()
    cand.time_vs_phase.adjust_period(p=orig_p, pd=orig_pd, pdd=orig_pdd)
    new = cand.time_vs_phase.data.copy()

    print "Compare orig/mod"
    print(orig == mod).all()
    print "Compare mod/new"
    print(mod == new).all()
    print "Compare orig/new"
    print(orig == new).all()

    print "Compare with best prof"
    # Create best prof file
    print "show_pfd -noxwin %s" % cand.info['pfdfn']
    subprocess.call("show_pfd -noxwin %s" % cand.info['pfdfn'],
                    shell=True,
                    stdout=open(os.devnull))
    prof = np.loadtxt(os.path.split(cand.pfd.pfd_filename + ".bestprof")[-1],
                      usecols=(1, ))

    pfd = cand.pfd
    if pfd.fold_pow == 1.0:
        bestp = pfd.bary_p1
        bestpd = pfd.bary_p2
        bestpdd = pfd.bary_p3
    else:
        bestp = pfd.topo_p1
        bestpd = pfd.topo_p2
        bestpdd = pfd.topo_p3
    cand.time_vs_phase.adjust_period(bestp, bestpd, bestpdd)
    tvph = pfd.time_vs_phase()
    print test_img(cand.time_vs_phase.data, tvph, 1e-6)
    plt.plot(cand.time_vs_phase.get_profile())
    plt.plot(tvph.sum(axis=0).squeeze())
    plt.show()
Пример #16
0
def main():
    pfdfn = sys.argv[1]

    pfd = prepfold.pfd(pfdfn)

    cand = candidate.Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                        psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                        psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                        pfdfn)

    print "Loaded %s" % cand.pfdfn
    print "    Best topo period (s): %f" % cand.topo_period
    print "    Best bary period (s): %f" % cand.bary_period
    print "    Best DM (cm^-3/pc): %f" % cand.dm
    print "    RA (J2000 - deg): %f" % cand.raj_deg
    print "    Dec (J2000 - deg): %f" % cand.decj_deg

    print "-"*10
    pprint.pprint(cand.__dict__)
    print "-"*10

    intstats.add_data(cand)

    print "Added subint stats to cand"
    pprint.pprint(cand.__dict__)
    print "-"*10

    print "Subint stats object:"
    pprint.pprint(cand.subint_stats.__dict__)
    print "-"*10

    print "Sub-int Stats:"
    print "On-fraction (area): %g" % cand.subint_stats.get_on_frac()
    print "On-fraction (peak): %g" % cand.subint_stats.get_peak_on_frac()
    print "Area SNR stddev: %g" % cand.subint_stats.get_snr_stddev()
    print "Peak SNR stddev: %g" % cand.subint_stats.get_peak_snr_stddev()
    print "Avg correlation coefficient: %g" % cand.subint_stats.get_avg_corrcoef()
    
    mgauss = cand.multigaussfit
    tvph = cand.time_vs_phase
    onpulse_region = mgauss.get_onpulse_region(tvph.nbin)
    offpulse_region = np.bitwise_not(onpulse_region)
    m = np.ma.masked_array(onpulse_region, mask=offpulse_region)
    onpulse_ranges = np.ma.notmasked_contiguous(m)
    print onpulse_ranges
    prof = utils.get_scaled_profile(cand.profile, cand.pfd.varprof)
    imax = plt.axes([0.1,0.1,0.5,0.7])
    plt.imshow(scale2d(tvph.data), interpolation='nearest', \
            aspect='auto', origin='lower', cmap=matplotlib.cm.gist_yarg)
    for opr in onpulse_ranges:
        onpulse_bin = (opr.start, opr.stop)
        if onpulse_bin[0] < onpulse_bin[1]:
            plt.axvspan(onpulse_bin[0], onpulse_bin[1]+1, fc='g', alpha=0.2, lw=0)
        else:
            plt.axvspan(onpulse_bin[0], tvph.nbin, fc='g', alpha=0.2, lw=0)
            plt.axvspan(-0.5, onpulse_bin[1]+1, fc='g', alpha=0.2, lw=0)
        

    plt.axes([0.1,0.8,0.5,0.15], sharex=imax)
    plt.plot(prof, 'k-', label='Profile')
    plt.plot(mgauss.make_gaussians(len(prof)), 'r--', label='Fit')
    for ii, opr in enumerate(onpulse_ranges):
        onpulse_bin = (opr.start, opr.stop)
        if ii == 0:
            lbl = 'On-pulse'
        else:
            lbl = '_nolabel_'
        if onpulse_bin[0] < onpulse_bin[1]:
            plt.axvspan(onpulse_bin[0], onpulse_bin[1]+1, fc='g', alpha=0.2, lw=0, label=lbl)
        else:
            plt.axvspan(onpulse_bin[0], tvph.nbin, fc='g', alpha=0.2, lw=0, label=lbl)
            plt.axvspan(-0.5, onpulse_bin[1]+1, fc='g', alpha=0.2, lw=0, label='_nolabel_')
    plt.legend(loc='best', prop=dict(size='xx-small'))
    
    plt.axes([0.6,0.1,0.15,0.7], sharey=imax)
    snrs = cand.subint_stats.snrs
    plt.plot(snrs, np.arange(len(snrs)), 'mo', label='SNR (area)')
    plt.axvline(5.0, c='m', ls='--', lw=2)
    peaksnrs = cand.subint_stats.peak_snrs
    plt.plot(peaksnrs, np.arange(len(peaksnrs)), 'cD', label='SNR (peak)')
    plt.axvline(3.0, c='c', ls='--', lw=2)
    plt.legend(loc='best', prop=dict(size='xx-small'))
   
    plt.axes([0.75,0.1,0.15,0.7], sharey=imax)
    corrcoefs = cand.subint_stats.corr_coefs
    plt.plot(corrcoefs, np.arange(len(corrcoefs)), 'k.')
    imax.set_xlim(-0.5,tvph.nbin-0.5)
    imax.set_ylim(-0.5,tvph.nsubint-0.5)
    plt.show()
Пример #17
0
    def read_parfiles(self):
        """
        Read in all parfiles and store relevant fields.
        """

        ### Useful cluster parameters. This should be updated to reflect individual clusters being examined.
        cluster = {"Ter5": ["Terzan5", "17:48:04.85", "-24:46:44.6", 5.9, 7.9/60.0, 0.83, 13.27, 7.60, 8.97, 20.33, 5.06, 3.8, 1.7, 17.0, 21.72, 5.0], \
                   "M28": ['M28', "18:24:32.89", "-24:52:11.4", 7.0, 7.9/60.0, 0.83, 13.27, 7.60, 8.97, 20.33, 5.06, 8.14, -6.18, 17.0, 21.72, 5.0], \
                   "47TUC": ['47TUC', "00:24:5.29", "-72:04:52.3", 7.0, 7.9/60.0, 0.83, 13.27, 7.60, 8.97, 20.33, 5.06, 305.89, -44.88, 17.0, 21.72, 5.0]}

        ### Create an easy to use dictionary with simple attributes
        params = self.DataBunch(R=[],ACCEL=[],ACCEL_ERR=[],P0=[],P0_ERR=[],P1=[],P1_ERR=[],P2=[],P2_ERR=[],P3=[],P3_ERR=[],A1=[],A1_ERR=[], \
                                PB=[],PB_ERR=[],PBDOT=[],PBDOT_ERR=[],ACCEL_BINARY=[],ACCEL_BINARY_ERR=[],FNAME=[],PSRNAME=[],ACCEL_CLUSTER=[],ACCEL_CLUSTER_ERR=[], \
                                RA_OFFSET=[],DEC_OFFSET=[],DM=[])

	for ipar in self.files:
            psr         = psr_par(ipar,unit_flag=True)
            psr.cluster = self.cluster

            ### Calculate the Surface Density and its Error
            psr.D                = cluster[psr.cluster][3]
            psr.l                = (cluster[psr.cluster][11]*units.deg).to(units.rad)
            psr.b                = (cluster[psr.cluster][12]*units.deg).to(units.rad)
            psr.cluster_RA       = ra_to_rad(cluster[psr.cluster][1])*units.rad
            psr.cluster_DEC      = dec_to_rad(cluster[psr.cluster][2])*units.rad
            psr.core_ang_asec    = (sphere_ang_diff(psr.RA_RAD.value, psr.DEC_RAD.value, psr.cluster_RA.value, psr.cluster_DEC.value)*units.rad).to(units.arcsec)+self.r_c_offset_error
            R0                   = (8.34*units.kpc).to(units.m)
            R0_error             = (.16*units.kpc).to(units.m)
            Omega0               = (240.0*units.km/units.s).to(units.m/units.s)
            Omega0_error         = (8.0*units.km/units.s).to(units.m/units.s)
            d                    = (5.9*units.kpc).to(units.m)
            d_error              = (.5*units.kpc).to(units.m)
            beta                 = (d/R0)*np.cos(psr.b)-np.cos(psr.l)
            beta_error           = np.sqrt(((d_error/R0)*np.cos(psr.b))**2.+((R0_error*d/R0**2.)*np.cos(psr.b))**2.)
            psr.abyc_gal         = (-np.cos(psr.b)*((Omega0**2.)/R0)*(np.cos(psr.l)+beta/(np.sin(psr.l)**2.+beta**2.)))/constants.c
            psr.abyc_gal_error   = np.sqrt((((-np.cos(psr.b)*((Omega0**2.)/R0))/constants.c)*((np.sin(psr.l)**2.-beta**2.)/(np.sin(psr.l)**2.+beta**2.)**2.)*beta_error)**2.
                                  +((-np.cos(psr.b)*((Omega0_error*Omega0)/R0)*(np.cos(psr.l)+beta/(np.sin(psr.l)**2.+beta**2.)))/constants.c)**2.
                                  +((-np.cos(psr.b)*((R0_error*Omega0**2.)/R0**2.)*(np.cos(psr.l)+beta/(np.sin(psr.l)**2.+beta**2.)))/constants.c)**2.)
            psr.abyc_meas        = psr.P1/psr.P0
            psr.abyc_meas_error  = np.sqrt((psr.P1_ERR/psr.P0)**2.+(psr.P0_ERR*psr.P1/psr.P0**2.)**2.)
            psr.abyc_clust       = psr.abyc_meas - psr.abyc_gal
            psr.abyc_clust_error = np.sqrt(psr.abyc_meas_error**2.+psr.abyc_gal_error**2.)

            ### Store important attributes to params
            params.R.append((psr.core_ang_asec)*psr.D*1000/206265)
            params.ACCEL.append(psr.abyc_clust*self.c)
            params.ACCEL_ERR.append(psr.abyc_clust_error*self.c)
            params.P0.append(psr.P0)
            params.P0_ERR.append(psr.P0_ERR)
            params.P1.append(psr.P1)
            params.P1_ERR.append(psr.P1_ERR)
            params.FNAME.append(psr.FILE.split('.par')[0])
            params.PSRNAME.append(psr.FILE.split('.par')[0].split('-2446')[-1])
            params.ACCEL_CLUSTER.append(0.*units.m/(units.s**2.))
            params.ACCEL_CLUSTER_ERR.append(0.*units.m/(units.s**2.))
            params.RA_OFFSET.append((psr.RA_RAD-psr.cluster_RA).to(units.arcsec))
            params.DEC_OFFSET.append((psr.DEC_RAD-psr.cluster_DEC).to(units.arcsec))
            params.DM.append(psr.DM)

            if hasattr(psr, 'F2'):
		params.P2.append(-1.0*((psr.F2/psr.F0**2)-2.0*psr.F1**2/psr.F0**3))
        	params.P2_ERR.append(((psr.P0_ERR*(2*psr.P0*psr.F2+2*(psr.P1**2)/(psr.P0**2)))**2+(psr.F2_ERR*psr.P0**2)**2+(4*psr.P1*psr.P1_ERR/psr.P0)**2)**.5)
            else:
                unit = 1./units.s
        	params.P2.append(0*unit)
        	params.P2_ERR.append(0*unit)

            if hasattr(psr, 'F3'):
		dF0 = 2.0*(psr.F3*psr.F0**2+12.0*psr.F1**3-9.0*psr.F0*psr.F1*psr.F2)/psr.F0**5
		dF1 = 6.0*(psr.F0*psr.F2-3.0*psr.F1**2)/psr.F0**4
		dF2 = 6.0*psr.F1/psr.F0**3
		dF3 = -1.0/psr.F0**2
		err = np.sqrt((dF0*psr.F0_ERR)**2+(dF1*psr.F1_ERR)**2+(dF2*psr.F2_ERR)**2+(dF3*psr.F3_ERR)**2)

		params.P3.append(-1.0*(psr.F3*psr.F0**2+6.0*psr.F1**3-6.0*psr.F0*psr.F1*psr.F2)/psr.F0**4)
        	params.P3_ERR.append(err)
            else:
	        unit = 1./units.s**2.
        	params.P3.append(-999*unit)
        	params.P3_ERR.append(-999*unit)

            if hasattr(psr, 'PBDOT'):
        	params.A1.append(psr.A1*self.c)
        	params.A1_ERR.append(psr.A1_ERR*self.c)
        	params.PB.append(psr.PB.to(units.s))
        	params.PB_ERR.append(psr.PB_ERR.to(units.s))
        	params.PBDOT.append(psr.PBDOT*1e-12)
        	params.PBDOT_ERR.append(psr.PBDOT_ERR*1e-12)
        	params.ACCEL_BINARY.append((psr.PBDOT*1e-12/(psr.PB.to(units.s))-psr.abyc_gal)*self.c)
        	params.ACCEL_BINARY_ERR.append(np.sqrt((psr.PBDOT_ERR*1e-12/(psr.PB.to(units.s)))**2+(psr.PBDOT*1e-12*psr.PB_ERR.to(units.s)/(psr.PB.to(units.s))**2)**2)*self.c)
            else:
	        unit = units.m
        	params.A1.append(0*unit)
        	params.A1_ERR.append(0*unit)

                unit = units.s
        	params.PB.append(0*unit)
        	params.PB_ERR.append(0*unit)

                unit = units.s/units.s
        	params.PBDOT.append(0*unit)
        	params.PBDOT_ERR.append(0*unit)
		
                params.ACCEL_BINARY.append(0.*units.m/(units.s**2.))
                params.ACCEL_BINARY_ERR.append(0.*units.m/(units.s**2.))

	# Clean up the units a bit. Not good to have them IN the list.
	for ikey in params.keys():
            try:
                unit = params[ikey][0].unit
	        tmp  = []
	        for ivalue in params[ikey]:
	            tmp.append(ivalue.value)
	        params[ikey] = np.asarray(tmp)*unit
	    except AttributeError:
	        params[ikey] = np.asarray(params[ikey])

	### Return values in params sorted by projected distance from the core. (Returns as numpy array).
	idx = np.argsort(params.R)
	for i in params.keys():
	    params[i] = params[i][idx]

        return params
Пример #18
0
 def __init__(self, parfilenm):
     self.FILE = parfilenm
     pf = open(parfilenm)
     for line in pf.readlines():
         # Skip comments
         if line[0] == '#':
             continue
         # Convert any 'D-' or 'D+' to 'E-' or 'E+'
         line = line.replace("D-", "E-")
         line = line.replace("D+", "E+")
         splitline = line.split()
         # Skip blank lines
         if len(splitline) == 0:
             continue
         key = splitline[0]
         # Regex checks for non-digit chars, followed by digit chars
         m1 = re.search(r'(\D+)(\d+)$', key)
         # This one looks for the DMX[RF][12]_* params
         m2 = re.search(r'(\D+\d+_)(\d+)$', key)
         if key == "JUMP":
             if splitline[3] not in ['0', '1']:
                 setattr(self, key + '_%s' % splitline[2],
                         float(splitline[3]))
             if len(splitline) == 5:
                 if splitline[4] not in ['0', '1']:
                     setattr(self, key + '_%s' % splitline[2] + '_ERR',
                             float(splitline[4]))
             elif len(splitline) == 6:
                 setattr(self, key + '_%s' % splitline[2] + '_ERR',
                         float(splitline[5]))
         if key in str_keys:
             setattr(self, key, splitline[1])
         elif key in float_keys:
             try:
                 setattr(self, key, float(splitline[1]))
             except ValueError:
                 pass
         elif m1 is not None:
             m = m1
             if m2 is not None:
                 m = m2
             if m.group(1) in floatn_keys:
                 try:
                     setattr(self, key, float(splitline[1]))
                 except ValueError:
                     pass
         if len(
                 splitline
         ) == 3:  # Some parfiles don't have flags, but do have errors
             if splitline[2] not in ['0', '1']:
                 setattr(self, key + '_ERR', float(splitline[2]))
         if len(splitline) == 4:
             setattr(self, key + '_ERR', float(splitline[3]))
     # Deal with Ecliptic coords
     if (hasattr(self, 'BETA') and hasattr(self, 'LAMBDA')):
         setattr(self, 'ELAT', self.BETA)
         setattr(self, 'ELONG', self.LAMBDA)
     if (slalib and hasattr(self, 'ELAT') and hasattr(self, 'ELONG')):
         # TEMPO's ecliptic coords are always based on J2000 epoch
         ra_rad, dec_rad = sla_ecleq(self.ELONG * pu.DEGTORAD,
                                     self.ELAT * pu.DEGTORAD, J2000)
         rstr = pu.coord_to_string(*pu.rad_to_hms(ra_rad))
         dstr = pu.coord_to_string(*pu.rad_to_dms(dec_rad))
         setattr(self, 'RAJ', rstr)
         setattr(self, 'DECJ', dstr)
     if hasattr(self, 'RAJ'):
         setattr(self, 'RA_RAD', pu.ra_to_rad(self.RAJ))
     if hasattr(self, 'DECJ'):
         setattr(self, 'DEC_RAD', pu.dec_to_rad(self.DECJ))
     # Compute the Galactic coords
     if (slalib and hasattr(self, 'RA_RAD') and hasattr(self, 'DEC_RAD')):
         l, b = sla_eqgal(self.RA_RAD, self.DEC_RAD)
         setattr(self, 'GLONG', l * pu.RADTODEG)
         setattr(self, 'GLAT', b * pu.RADTODEG)
     # Compute the Ecliptic coords
     if (slalib and hasattr(self, 'RA_RAD') and hasattr(self, 'DEC_RAD')):
         # TEMPO's ecliptic coords are always based on J2000 epoch
         elon, elat = sla_eqecl(self.RA_RAD, self.DEC_RAD, J2000)
         setattr(self, 'ELONG', elon * pu.RADTODEG)
         setattr(self, 'ELAT', elat * pu.RADTODEG)
     if hasattr(self, 'P'):
         setattr(self, 'P0', self.P)
     if hasattr(self, 'P0'):
         setattr(self, 'F0', 1.0 / self.P0)
     if hasattr(self, 'F0'):
         setattr(self, 'P0', 1.0 / self.F0)
     if hasattr(self, 'FB0'):
         setattr(self, 'PB', (1.0 / self.FB0) / 86400.0)
     if hasattr(self, 'P0_ERR'):
         if hasattr(self, 'P1_ERR'):
             f, ferr, fd, fderr = pu.pferrs(self.P0, self.P0_ERR, self.P1,
                                            self.P1_ERR)
             setattr(self, 'F0_ERR', ferr)
             setattr(self, 'F1', fd)
             setattr(self, 'F1_ERR', fderr)
         else:
             f, fd, = pu.p_to_f(self.P0, self.P1)
             setattr(self, 'F0_ERR', self.P0_ERR / (self.P0 * self.P0))
             setattr(self, 'F1', fd)
     else:
         if hasattr(self, 'P1'):
             f, fd, = pu.p_to_f(self.P0, self.P1)
             setattr(self, 'F1', fd)
         elif hasattr(self, 'F1'):
             p, pd, = pu.p_to_f(self.F0, self.F1)
             setattr(self, 'P1', pd)
     if (hasattr(self, 'F0_ERR') and hasattr(self, 'F1_ERR')):
         p, perr, pd, pderr = pu.pferrs(self.F0, self.F0_ERR, self.F1,
                                        self.F1_ERR)
         setattr(self, 'P0_ERR', perr)
         setattr(self, 'P1', pd)
         setattr(self, 'P1_ERR', pderr)
     elif (hasattr(self, 'F0') and hasattr(self, 'F0_ERR')):
         setattr(self, 'P0_ERR', self.F0_ERR / (self.F0 * self.F0))
     if hasattr(self, 'EPS1') and hasattr(self, 'EPS2'):
         ecc = math.sqrt(self.EPS1 * self.EPS1 + self.EPS2 * self.EPS2)
         omega = math.atan2(self.EPS1, self.EPS2)
         setattr(self, 'E', ecc)
         setattr(self, 'OM', omega * pu.RADTODEG)
         setattr(self, 'T0', self.TASC + self.PB * omega / pu.TWOPI)
     if hasattr(self, 'PB') and hasattr(self, 'A1') and not \
            (hasattr(self, 'E') or hasattr(self, 'ECC')):
         setattr(self, 'E', 0.0)
     if hasattr(self, 'T0') and not hasattr(self, 'TASC'):
         setattr(self, 'TASC', self.T0 - self.PB * self.OM / 360.0)
     if hasattr(self, 'E') and not hasattr(self, 'ECC'):
         setattr(self, 'ECC', self.E)
         if not hasattr(self, 'EPS1'):
             setattr(self, 'ECC_ERR', self.E_ERR)
     if hasattr(self, 'ECC') and not hasattr(self, 'E'):
         setattr(self, 'E', self.ECC)
         setattr(self, 'E_ERR', self.ECC_ERR)
     pf.close()
Пример #19
0
 def __init__(self, parfilenm):
     self.FILE = parfilenm
     pf = open(parfilenm)
     for line in pf.readlines():
         # Skip comments
         if line[0] == '#':
             continue
         # Convert any 'D-' or 'D+' to 'E-' or 'E+'
         line = line.replace("D-", "E-")
         line = line.replace("D+", "E+")
         splitline = line.split()
         # Skip blank lines
         if len(splitline) == 0:
             continue
         key = splitline[0]
         if key in str_keys:
             setattr(self, key, splitline[1])
         elif key in float_keys:
             try:
                 setattr(self, key, float(splitline[1]))
             except ValueError:
                 pass
         if len(
                 splitline
         ) == 3:  # Some parfiles don't have flags, but do have errors
             if splitline[2] not in ['0', '1']:
                 setattr(self, key + '_ERR', float(splitline[2]))
         if len(splitline) == 4:
             setattr(self, key + '_ERR', float(splitline[3]))
     # Deal with Ecliptic coords
     if (hasattr(self, 'BETA') and hasattr(self, 'LAMBDA')):
         setattr(self, 'ELAT', self.BETA)
         setattr(self, 'ELONG', self.LAMBDA)
     if (slalib and hasattr(self, 'ELAT') and hasattr(self, 'ELONG')):
         if hasattr(self, 'POSEPOCH'):
             epoch = self.POSEPOCH
         else:
             epoch = self.PEPOCH
         ra_rad, dec_rad = sla_ecleq(self.ELONG * pu.DEGTORAD,
                                     self.ELAT * pu.DEGTORAD, epoch)
         rstr = pu.coord_to_string(*pu.rad_to_hms(ra_rad))
         dstr = pu.coord_to_string(*pu.rad_to_dms(dec_rad))
         setattr(self, 'RAJ', rstr)
         setattr(self, 'DECJ', dstr)
     if hasattr(self, 'RAJ'):
         setattr(self, 'RA_RAD', pu.ra_to_rad(self.RAJ))
     if hasattr(self, 'DECJ'):
         setattr(self, 'DEC_RAD', pu.dec_to_rad(self.DECJ))
     # Compute the Galactic coords
     if (slalib and hasattr(self, 'RA_RAD') and hasattr(self, 'DEC_RAD')):
         l, b = sla_eqgal(self.RA_RAD, self.DEC_RAD)
         setattr(self, 'GLONG', l * pu.RADTODEG)
         setattr(self, 'GLAT', b * pu.RADTODEG)
     # Compute the Ecliptic coords
     if (slalib and hasattr(self, 'RA_RAD') and hasattr(self, 'DEC_RAD')):
         if hasattr(self, 'POSEPOCH'):
             epoch = self.POSEPOCH
         else:
             epoch = self.PEPOCH
         elon, elat = sla_eqecl(self.RA_RAD, self.DEC_RAD, epoch)
         setattr(self, 'ELONG', elon * pu.RADTODEG)
         setattr(self, 'ELAT', elat * pu.RADTODEG)
     if hasattr(self, 'P'):
         setattr(self, 'P0', self.P)
     if hasattr(self, 'P0'):
         setattr(self, 'F0', 1.0 / self.P0)
     if hasattr(self, 'F0'):
         setattr(self, 'P0', 1.0 / self.F0)
     if hasattr(self, 'FB0'):
         setattr(self, 'PB', (1.0 / self.FB0) / 86400.0)
     if hasattr(self, 'P0_ERR'):
         if hasattr(self, 'P1_ERR'):
             f, ferr, fd, fderr = pu.pferrs(self.P0, self.P0_ERR, self.P1,
                                            self.P1_ERR)
             setattr(self, 'F0_ERR', ferr)
             setattr(self, 'F1', fd)
             setattr(self, 'F1_ERR', fderr)
         else:
             f, fd, = pu.p_to_f(self.P0, self.P1)
             setattr(self, 'F0_ERR', self.P0_ERR / (self.P0 * self.P0))
             setattr(self, 'F1', fd)
     if (hasattr(self, 'F0_ERR') and hasattr(self, 'F1_ERR')):
         p, perr, pd, pderr = pu.pferrs(self.F0, self.F0_ERR, self.F1,
                                        self.F1_ERR)
         setattr(self, 'P0_ERR', perr)
         setattr(self, 'P1', pd)
         setattr(self, 'P1_ERR', pderr)
     elif (hasattr(self, 'F0') and hasattr(self, 'F0_ERR')):
         setattr(self, 'P0_ERR', self.F0_ERR / (self.F0 * self.F0))
     if hasattr(self, 'EPS1') and hasattr(self, 'EPS2'):
         ecc = math.sqrt(self.EPS1 * self.EPS1 + self.EPS2 * self.EPS2)
         omega = math.atan2(self.EPS1, self.EPS2)
         setattr(self, 'E', ecc)
         setattr(self, 'OM', omega * pu.RADTODEG)
         setattr(self, 'T0', self.TASC + self.PB * omega / pu.TWOPI)
     if hasattr(self, 'PB') and hasattr(self, 'A1') and not \
            (hasattr(self, 'E') or hasattr(self, 'ECC')):
         setattr(self, 'E', 0.0)
     if hasattr(self, 'T0') and not hasattr(self, 'TASC'):
         setattr(self, 'TASC', self.T0 - self.PB * self.OM / 360.0)
     pf.close()
Пример #20
0
 def __init__(self, parfilenm):
     self.FILE = parfilenm
     pf = open(parfilenm)
     for line in pf.readlines():
         # Skip comments
         if line[0]=='#':
             continue
         # Convert any 'D-' or 'D+' to 'E-' or 'E+'
         line = line.replace("D-", "E-")
         line = line.replace("D+", "E+")
         splitline = line.split()
         # Skip blank lines
         if len(splitline)==0:
             continue
         key = splitline[0]
         # Regex checks for non-digit chars, followed by digit chars
         m1 = re.search(r'(\D+)(\d+)$', key)
         # This one looks for the DMX[RF][12]_* params
         m2 = re.search(r'(\D+\d+_)(\d+)$', key)
         if key == "JUMP":
             if splitline[3] not in ['0', '1']:
                 setattr(self, key+'_%s'%splitline[2], float(splitline[3]))
             if len(splitline)==5:
                 if splitline[4] not in ['0', '1']:
                     setattr(self, key+'_%s'%splitline[2]+'_ERR',
                             float(splitline[4]))
             elif len(splitline)==6:
                 setattr(self, key+'_%s'%splitline[2]+'_ERR',
                         float(splitline[5]))
         if key in str_keys:
             setattr(self, key, splitline[1])
         elif key in float_keys:
             try:
                 setattr(self, key, float(splitline[1]))
             except ValueError:
                 pass
         elif m1 is not None:
             m = m1
             if m2 is not None:
                 m = m2
             if m.group(1) in floatn_keys:
                 try:
                     setattr(self, key, float(splitline[1]))
                 except ValueError:
                     pass
         if len(splitline)==3:  # Some parfiles don't have flags, but do have errors
             if splitline[2] not in ['0', '1']:
                 setattr(self, key+'_ERR', float(splitline[2]))
         if len(splitline)==4:
             setattr(self, key+'_ERR', float(splitline[3]))
     # Deal with Ecliptic coords
     if (hasattr(self, 'BETA') and hasattr(self, 'LAMBDA')):
         setattr(self, 'ELAT', self.BETA)
         setattr(self, 'ELONG', self.LAMBDA)
     if (slalib and hasattr(self, 'ELAT') and hasattr(self, 'ELONG')):
         if hasattr(self, 'POSEPOCH'):
             epoch = self.POSEPOCH
         else:
             epoch = self.PEPOCH
         ra_rad, dec_rad = sla_ecleq(self.ELONG*pu.DEGTORAD,
                                     self.ELAT*pu.DEGTORAD, epoch)
         rstr = pu.coord_to_string(*pu.rad_to_hms(ra_rad))
         dstr = pu.coord_to_string(*pu.rad_to_dms(dec_rad))
         setattr(self, 'RAJ', rstr)
         setattr(self, 'DECJ', dstr)
     if hasattr(self, 'RAJ'):
         setattr(self, 'RA_RAD', pu.ra_to_rad(self.RAJ))
     if hasattr(self, 'DECJ'):
         setattr(self, 'DEC_RAD', pu.dec_to_rad(self.DECJ))
     # Compute the Galactic coords
     if (slalib and hasattr(self, 'RA_RAD') and hasattr(self, 'DEC_RAD')):
         l, b = sla_eqgal(self.RA_RAD, self.DEC_RAD)
         setattr(self, 'GLONG', l*pu.RADTODEG)
         setattr(self, 'GLAT', b*pu.RADTODEG)
     # Compute the Ecliptic coords
     if (slalib and hasattr(self, 'RA_RAD') and hasattr(self, 'DEC_RAD')):
         if hasattr(self, 'POSEPOCH'):
             epoch = self.POSEPOCH
         else:
             epoch = self.PEPOCH
         elon, elat = sla_eqecl(self.RA_RAD, self.DEC_RAD, epoch)
         setattr(self, 'ELONG', elon*pu.RADTODEG)
         setattr(self, 'ELAT', elat*pu.RADTODEG)
     if hasattr(self, 'P'):
         setattr(self, 'P0', self.P)
     if hasattr(self, 'P0'):
         setattr(self, 'F0', 1.0/self.P0)
     if hasattr(self, 'F0'):
         setattr(self, 'P0', 1.0/self.F0)
     if hasattr(self, 'FB0'):
         setattr(self, 'PB', (1.0/self.FB0)/86400.0)
     if hasattr(self, 'P0_ERR'):
         if hasattr(self, 'P1_ERR'):
             f, ferr, fd, fderr = pu.pferrs(self.P0, self.P0_ERR,
                                            self.P1, self.P1_ERR)
             setattr(self, 'F0_ERR', ferr) 
             setattr(self, 'F1', fd) 
             setattr(self, 'F1_ERR', fderr) 
         else:
             f, fd, = pu.p_to_f(self.P0, self.P1)
             setattr(self, 'F0_ERR', self.P0_ERR/(self.P0*self.P0))
             setattr(self, 'F1', fd)
     else:
         if hasattr(self, 'P1'):
             f, fd, = pu.p_to_f(self.P0, self.P1)
             setattr(self, 'F1', fd)
         elif hasattr(self, 'F1'):
             p, pd, = pu.p_to_f(self.F0, self.F1)
             setattr(self, 'P1', pd)
     if (hasattr(self, 'F0_ERR') and hasattr(self, 'F1_ERR')):
         p, perr, pd, pderr = pu.pferrs(self.F0, self.F0_ERR, 
                                        self.F1, self.F1_ERR)
         setattr(self, 'P0_ERR', perr) 
         setattr(self, 'P1', pd) 
         setattr(self, 'P1_ERR', pderr) 
     elif (hasattr(self, 'F0') and hasattr(self, 'F0_ERR')):
         setattr(self, 'P0_ERR', self.F0_ERR/(self.F0*self.F0))
     if hasattr(self, 'EPS1') and hasattr(self, 'EPS2'):
         ecc = math.sqrt(self.EPS1 * self.EPS1 + self.EPS2 * self.EPS2)
         omega = math.atan2(self.EPS1, self.EPS2)
         setattr(self, 'E', ecc)
         setattr(self, 'OM', omega * pu.RADTODEG)
         setattr(self, 'T0', self.TASC + self.PB * omega/pu.TWOPI)
     if hasattr(self, 'PB') and hasattr(self, 'A1') and not \
            (hasattr(self, 'E') or hasattr(self, 'ECC')):
         setattr(self, 'E', 0.0)
     if hasattr(self, 'T0') and not hasattr(self, 'TASC'):
         setattr(self, 'TASC', self.T0 - self.PB * self.OM/360.0)
     pf.close()