def __init__(self, header_id, cand_num, pfd , snr, \
                        coherent_power, incoherent_power, \
                        num_hits, num_harmonics, versionnum, sigma):
        self.header_id = header_id # Header ID from database
        self.cand_num = cand_num # Unique identifier of candidate within beam's 
                                 # list of candidates; Candidate's position in
                                 # a list of all candidates produced in beam
                                 # ordered by decreasing sigma (where largest
                                 # sigma has cand_num=1).
        self.topo_freq, self.topo_f_dot, fdd = \
                psr_utils.p_to_f(pfd.topo_p1, pfd.topo_p2, pfd.topo_p3)
        self.bary_freq, self.bary_f_dot, baryfdd = \
                psr_utils.p_to_f(pfd.bary_p1, pfd.bary_p2, pfd.bary_p3)
        self.dm = pfd.bestdm # Dispersion measure
        self.snr = snr # signal-to-noise ratio
        self.coherent_power = coherent_power # Coherent power
        self.incoherent_power = incoherent_power # Incoherent power
        self.num_hits = num_hits # Number of dedispersed timeseries candidate was found in
        self.num_harmonics = num_harmonics # Number of harmonics candidate was 
                                           # most significant with
        self.versionnum = versionnum # Version number; a combination of PRESTO's githash
                                     # and pipeline's githash
        self.sigma = sigma # PRESTO's sigma value

        # Calculate a few more values
        self.topo_period = 1.0/self.topo_freq
        self.bary_period = 1.0/self.bary_freq
Esempio n. 2
0
    def __init__(self, header_id, cand_num, pfd , snr, \
                        coherent_power, incoherent_power, \
                        num_hits, num_harmonics, versionnum, sigma):
        self.header_id = header_id  # Header ID from database
        self.cand_num = cand_num  # Unique identifier of candidate within beam's
        # list of candidates; Candidate's position in
        # a list of all candidates produced in beam
        # ordered by decreasing sigma (where largest
        # sigma has cand_num=1).
        self.topo_freq, self.topo_f_dot, fdd = \
                psr_utils.p_to_f(pfd.topo_p1, pfd.topo_p2, pfd.topo_p3)
        self.bary_freq, self.bary_f_dot, baryfdd = \
                psr_utils.p_to_f(pfd.bary_p1, pfd.bary_p2, pfd.bary_p3)
        self.dm = pfd.bestdm  # Dispersion measure
        self.snr = snr  # signal-to-noise ratio
        self.coherent_power = coherent_power  # Coherent power
        self.incoherent_power = incoherent_power  # Incoherent power
        self.num_hits = num_hits  # Number of dedispersed timeseries candidate was found in
        self.num_harmonics = num_harmonics  # Number of harmonics candidate was
        # most significant with
        self.versionnum = versionnum  # Version number; a combination of PRESTO's githash
        # and pipeline's githash
        self.sigma = sigma  # PRESTO's sigma value

        # Calculate a few more values
        self.topo_period = 1.0 / self.topo_freq
        self.bary_period = 1.0 / self.bary_freq
Esempio n. 3
0
    def __init__(self, cand_num, pfd , snr, coherent_power, \
                        incoherent_power, num_hits, num_harmonics, \
                        versionnum, sigma, header_id=None):
        self.header_id = header_id  # Header ID from database
        self.cand_num = cand_num  # Unique identifier of candidate within beam's
        # list of candidates; Candidate's position in
        # a list of all candidates produced in beam
        # ordered by decreasing sigma (where largest
        # sigma has cand_num=1).
        self.topo_freq, self.topo_f_dot, fdd = \
                psr_utils.p_to_f(pfd.topo_p1, pfd.topo_p2, pfd.topo_p3)
        self.bary_freq, self.bary_f_dot, baryfdd = \
                psr_utils.p_to_f(pfd.bary_p1, pfd.bary_p2, pfd.bary_p3)
        self.dm = pfd.bestdm  # Dispersion measure
        self.snr = snr  # signal-to-noise ratio
        self.coherent_power = coherent_power  # Coherent power
        self.incoherent_power = incoherent_power  # Incoherent power
        self.num_hits = num_hits  # Number of dedispersed timeseries candidate was found in
        self.num_harmonics = num_harmonics  # Number of harmonics candidate was
        # most significant with
        self.versionnum = versionnum  # Version number; a combination of PRESTO's githash
        # and pipeline's githash
        self.sigma = sigma  # PRESTO's sigma value

        # Store a few configurations so the upload can be checked
        self.pipeline = config.basic.pipeline
        self.institution = config.basic.institution

        # Calculate a few more values
        self.topo_period = 1.0 / self.topo_freq
        self.bary_period = 1.0 / self.bary_freq

        # List of dependents (ie other uploadables that require
        # the pdm_cand_id from this candidate)
        self.dependents = []
Esempio n. 4
0
    def __init__(self, cand_num, pfd , snr, coherent_power, \
                        incoherent_power, num_hits, num_harmonics, \
                        versionnum, sigma, header_id=None):
        self.header_id = header_id # Header ID from database
        self.cand_num = cand_num # Unique identifier of candidate within beam's 
                                 # list of candidates; Candidate's position in
                                 # a list of all candidates produced in beam
                                 # ordered by decreasing sigma (where largest
                                 # sigma has cand_num=1).
        self.topo_freq, self.topo_f_dot, fdd = \
                psr_utils.p_to_f(pfd.topo_p1, pfd.topo_p2, pfd.topo_p3)
        self.bary_freq, self.bary_f_dot, baryfdd = \
                psr_utils.p_to_f(pfd.bary_p1, pfd.bary_p2, pfd.bary_p3)
        self.dm = pfd.bestdm # Dispersion measure
        self.snr = snr # signal-to-noise ratio
        self.coherent_power = coherent_power # Coherent power
        self.incoherent_power = incoherent_power # Incoherent power
        self.num_hits = num_hits # Number of dedispersed timeseries candidate was found in
        self.num_harmonics = num_harmonics # Number of harmonics candidate was 
                                           # most significant with
        self.versionnum = versionnum # Version number; a combination of PRESTO's githash
                                     # and pipeline's githash
        self.sigma = sigma # PRESTO's sigma value

        # Store a few configurations so the upload can be checked
        self.pipeline = config.basic.pipeline
        self.institution = config.basic.institution
    
        # Calculate a few more values
        self.topo_period = 1.0/self.topo_freq
        self.bary_period = 1.0/self.bary_freq

        # List of dependents (ie other uploadables that require 
        # the pdm_cand_id from this candidate)
        self.dependents = []
Esempio n. 5
0
    def adjust_period(self, p=None, pd=None, pdd=None):
        """
        adjust_period(p=*currp*, pd=*currpd*, pdd=*currpdd*):
            Rotate (internally) the profiles so that they are adjusted
                the given period and period derivatives
        """
        if p is None:
            p = self.curr_p
        if pd is None:
            pd = self.curr_pd
        if pdd is None:
            pdd = self.curr_pdd
        
        # Cast to single precision and back to double precision to
        # emulate prepfold_plot.c, where parttimes is of type "float"
        # but values are upcast to "double" during computations.
        # (surprisingly, it affects the resulting profile occasionally.)
        parttimes = self.start_secs.astype('float32').astype('float64')

        # Get delays
        ref_p, ref_pd, ref_pdd = psr_utils.p_to_f(self.ref_f, \
                                                  self.ref_fd, \
                                                  self.ref_fdd)
        
        #print "DEBUG: in dataproducts.py -- ref_p, ref_pd, pdd", ref_p, ref_pd, pdd
        fdd = psr_utils.p_to_f(ref_p, ref_pd, pdd)[2]
        fd = psr_utils.p_to_f(ref_p, pd)[1]
        f = 1.0/p
        
        f_diff = f - self.ref_f
        fd_diff = fd - self.ref_fd
        if pdd != 0.0:
            fdd_diff = fdd - self.ref_fdd
        else:
            fdd_diff = 0.0
        #print "DEBUG: in dataproducts.py -- self.ref_f, self.ref_fd, self.ref_fdd", self.ref_f, self.ref_fd, self.ref_fdd
        #print "DEBUG: in dataproducts.py -- f, fd, fdd", f, fd, fdd
        #print "DEBUG: in dataproducts.py -- f_diff, fd_diff, fdd_diff", f_diff, fd_diff, fdd_diff
        #print "DEBUG: in dataproducts.py -- parttimes", parttimes
        delays = psr_utils.delay_from_foffsets(f_diff, fd_diff, fdd_diff, \
                                                parttimes)

        # Convert from delays in phase to delays in bins
        bin_delays = np.fmod(delays * self.nbin, self.nbin) - self.pdelays_bins
        new_pdelays_bins = np.floor(bin_delays+0.5)

        # Rotate subintegrations
        for ii in range(self.nsubint):
            tmp_prof = self.data[ii,:]
            # Negative sign in num bins to shift because we calculated delays
            # Assuming +ve is shift-to-right, psr_utils.rotate assumes +ve
            # is shift-to-left
            self.data[ii,:] = psr_utils.rotate(tmp_prof, \
                                            -new_pdelays_bins[ii])
        
        # Save new p, pd, pdd
        self.curr_p, self.curr_pd, self.curr_pdd = p, pd, pdd
        self.pdelays_bins += new_pdelays_bins
Esempio n. 6
0
    def adjust_period(self, p=None, pd=None, pdd=None):
        """
        adjust_period(p=*currp*, pd=*currpd*, pdd=*currpdd*):
            Rotate (internally) the profiles so that they are adjusted
                the given period and period derivatives
        """
        if p is None:
            p = self.curr_p
        if pd is None:
            pd = self.curr_pd
        if pdd is None:
            pdd = self.curr_pdd

        # Cast to single precision and back to double precision to
        # emulate prepfold_plot.c, where parttimes is of type "float"
        # but values are upcast to "double" during computations.
        # (surprisingly, it affects the resulting profile occasionally.)
        parttimes = self.start_secs.astype('float32').astype('float64')

        # Get delays
        ref_p, ref_pd, ref_pdd = psr_utils.p_to_f(self.ref_f, \
                                                  self.ref_fd, \
                                                  self.ref_fdd)

        #print "DEBUG: in dataproducts.py -- ref_p, ref_pd, pdd", ref_p, ref_pd, pdd
        fdd = psr_utils.p_to_f(ref_p, ref_pd, pdd)[2]
        fd = psr_utils.p_to_f(ref_p, pd)[1]
        f = 1.0 / p

        f_diff = f - self.ref_f
        fd_diff = fd - self.ref_fd
        if pdd != 0.0:
            fdd_diff = fdd - self.ref_fdd
        else:
            fdd_diff = 0.0
        #print "DEBUG: in dataproducts.py -- self.ref_f, self.ref_fd, self.ref_fdd", self.ref_f, self.ref_fd, self.ref_fdd
        #print "DEBUG: in dataproducts.py -- f, fd, fdd", f, fd, fdd
        #print "DEBUG: in dataproducts.py -- f_diff, fd_diff, fdd_diff", f_diff, fd_diff, fdd_diff
        #print "DEBUG: in dataproducts.py -- parttimes", parttimes
        delays = psr_utils.delay_from_foffsets(f_diff, fd_diff, fdd_diff, \
                                                parttimes)

        # Convert from delays in phase to delays in bins
        bin_delays = np.fmod(delays * self.nbin, self.nbin) - self.pdelays_bins
        new_pdelays_bins = np.floor(bin_delays + 0.5)

        # Rotate subintegrations
        for ii in range(self.nsubint):
            tmp_prof = self.data[ii, :]
            # Negative sign in num bins to shift because we calculated delays
            # Assuming +ve is shift-to-right, psr_utils.rotate assumes +ve
            # is shift-to-left
            self.data[ii,:] = psr_utils.rotate(tmp_prof, \
                                            -new_pdelays_bins[ii])

        # Save new p, pd, pdd
        self.curr_p, self.curr_pd, self.curr_pdd = p, pd, pdd
        self.pdelays_bins += new_pdelays_bins
Esempio n. 7
0
    def freq_offsets(self, p=None, pd=None, pdd=None):
        """
        freq_offsets(p=*bestp*, pd=*bestpd*, pdd=*bestpdd*):
            Return the offsets between given frequencies
            and fold frequencies.

            If p, pd or pdd are None use the best values.

            A 3-tuple is returned.
        """
        if self.fold_pow == 1.0:
            bestp = self.bary_p1
            bestpd = self.bary_p2
            bestpdd = self.bary_p3
        else:
            if self.topo_p1 == 0.0:
                bestp = self.fold_p1
                bestpd = self.fold_p2
                bestpdd = self.fold_p3
            else:
                bestp = self.topo_p1
                bestpd = self.topo_p2
                bestpdd = self.topo_p3
        if p is not None:
            bestp = p
        if pd is not None:
            bestpd = pd
        if pdd is not None:
            bestpdd = pdd

        # self.fold_p[123] are actually frequencies, convert to periods
        foldf, foldfd, foldfdd = self.fold_p1, self.fold_p2, self.fold_p3
        foldp, foldpd, foldpdd = psr_utils.p_to_f(self.fold_p1, \
                                        self.fold_p2, self.fold_p3)

        # Get best f, fd, fdd
        # Use folding values to be consistent with prepfold_plot.c
        bestfdd = psr_utils.p_to_f(foldp, foldpd, bestpdd)[2]
        bestfd = psr_utils.p_to_f(foldp, bestpd)[1]
        bestf = 1.0/bestp

        # Get frequency and frequency derivative offsets
        f_diff = bestf - foldf
        fd_diff = bestfd - foldfd

        # bestpdd=0.0 only if there was no searching over pdd
        if bestpdd != 0.0:
            fdd_diff = bestfdd - foldfdd
        else:
            fdd_diff = 0.0

        return (f_diff, fd_diff, fdd_diff)
Esempio n. 8
0
    def freq_offsets(self, p=None, pd=None, pdd=None):
        """
        freq_offsets(p=*bestp*, pd=*bestpd*, pdd=*bestpdd*):
            Return the offsets between given frequencies
            and fold frequencies.
    
            If p, pd or pdd are None use the best values.

            A 3-tuple is returned.
        """
        if self.fold_pow == 1.0:
            bestp = self.bary_p1
            bestpd = self.bary_p2
            bestpdd = self.bary_p3
        else:
            if self.topo_p1 == 0.0:
                bestp = self.fold_p1
                bestpd = self.fold_p2
                bestpdd = self.fold_p3
            else:
                bestp = self.topo_p1
                bestpd = self.topo_p2
                bestpdd = self.topo_p3
        if p is not None:
            bestp = p
        if pd is not None:
            bestpd = pd
        if pdd is not None:
            bestpdd = pdd

        # self.fold_p[123] are actually frequencies, convert to periods
        foldf, foldfd, foldfdd = self.fold_p1, self.fold_p2, self.fold_p3
        foldp, foldpd, foldpdd = psr_utils.p_to_f(self.fold_p1, \
                                        self.fold_p2, self.fold_p3)

        # Get best f, fd, fdd
        # Use folding values to be consistent with prepfold_plot.c
        bestfdd = psr_utils.p_to_f(foldp, foldpd, bestpdd)[2]
        bestfd = psr_utils.p_to_f(foldp, bestpd)[1]
        bestf = 1.0/bestp

        # Get frequency and frequency derivative offsets
        f_diff = bestf - foldf
        fd_diff = bestfd - foldfd

        # bestpdd=0.0 only if there was no searching over pdd
        if bestpdd != 0.0:
            fdd_diff = bestfdd - foldfdd
        else:
            fdd_diff = 0.0

        return (f_diff, fd_diff, fdd_diff)
Esempio n. 9
0
def parse_eph(filenm):
    global period, time
    suffix = filenm.split(".")[-1]
    if suffix == "bestprof":
        x = bestprof.bestprof(filenm)
        fs = pu.p_to_f(x.p0_bary, x.p1_bary, x.p2_bary)
        epoch = x.epochi_bary + x.epochf_bary
        T = x.T
    elif suffix == "par":
        x = parfile.psr_par(filenm)
        # Try to see how many freq derivs we have
        fs = [x.F0]
        for ii in range(1, 20):  # hopefully 20 is an upper limit!
            attrib = "F%d" % ii
            if hasattr(x, attrib):
                fs.append(getattr(x, attrib))
            else:
                break
        epoch = x.PEPOCH
        T = (x.FINISH - x.START) * 86400.0
    else:
        print "I don't recognize the file type for", filenm
        sys.exit()
    newts = epoch + num.arange(int(T / 10.0 + 0.5), dtype=num.float) / 8640.0
    time = num.concatenate((time, newts))
    newps = 1.0 / pu.calc_freq(newts, epoch, *fs)
    period = num.concatenate((period, newps))
    print "%13.7f (%0.1f sec): " % (epoch, T), fs
Esempio n. 10
0
def parse_eph(filenm):
    global period, time
    suffix = filenm.split(".")[-1]
    if suffix=="bestprof":
        x = bestprof.bestprof(filenm)
        fs = pu.p_to_f(x.p0_bary, x.p1_bary, x.p2_bary)
        epoch = x.epochi_bary + x.epochf_bary
        T = x.T
    elif suffix=="par":
        x = parfile.psr_par(filenm)
        # Try to see how many freq derivs we have
        fs = [x.F0]
        for ii in range(1, 20):  # hopefully 20 is an upper limit!
            attrib = "F%d"%ii
            if hasattr(x, attrib):
                fs.append(getattr(x, attrib))
            else:
                break
        epoch = x.PEPOCH
        T = (x.FINISH - x.START) * 86400.0
    else:
        print("I don't recognize the file type for", filenm)
        sys.exit()
    newts = epoch + num.arange(int(T/10.0+0.5), dtype=num.float)/8640.0
    time = num.concatenate((time, newts))
    newps = 1.0 / pu.calc_freq(newts, epoch, *fs)
    period = num.concatenate((period, newps))
    print("%13.7f (%0.1f sec): " % (epoch, T), fs)
Esempio n. 11
0
def params_from_ppdot(p, pdot):
    """Return B-field, age and Edot in a tuple given p and pdot.
        If either P or Pdot is None, return tuple of Nones
    """
    if p is None or pdot is None:
        bfield = None
        age = None
        edot = None
    else:
        f, fdot = psr_utils.p_to_f(p, pdot)
        bfield = psr_utils.pulsar_B(f, fdot)
        age = psr_utils.pulsar_age(f, fdot)
        edot = psr_utils.pulsar_edot(f, fdot)
    return (bfield, age, edot)
Esempio n. 12
0
def params_from_ppdot(p, pdot):
    """Return B-field, age and Edot in a tuple given p and pdot.
        If either P or Pdot is None, return tuple of Nones
    """
    if p is None or pdot is None:
        bfield = None
        age = None
        edot = None
    else:
        f, fdot = psr_utils.p_to_f(p, pdot)
        bfield = psr_utils.pulsar_B(f, fdot)
        age = psr_utils.pulsar_age(f, fdot)
        edot = psr_utils.pulsar_edot(f, fdot)
    return (bfield, age, edot)
Esempio n. 13
0
        try: obs = scopes[fold_pfd.telescope.split()[0]]
        except KeyError:  print "Unknown telescope!!!"

    # Read the polyco file (if required)
    if (fold.psr and fold.topo):
        if (fold_pfd.__dict__.has_key("polycos") and
            not fold_pfd.polycos==0):
            pcs = fold_pfd.polycos
        else:
            pcs = polycos(fold.psr, sys.argv[-1]+".polycos")
        (fold.phs0, fold.f0) = pcs.get_phs_and_freq(fold.epochi, fold.epochf)
        fold.f1 = fold.f2 = 0.0
    else:
        pcs = None
        fold.phs0 = 0.0
        (fold.f0, fold.f1, fold.f2) = psr_utils.p_to_f(fold.p0, fold.p1, fold.p2)

    #
    # Calculate the TOAs
    #

    for ii in range(numtoas):

        # The .pfd file was generated using -nosearch and a specified
        # folding period, p-dot, and p-dotdot (or f, f-dot, and f-dotdot).
        if (pcs is None):
            # Time at the middle of the interval in question
            midtime = fold.epoch + (ii+0.5)*timestep_day
            p = 1.0/psr_utils.calc_freq(midtime, fold.epoch, fold.f0, fold.f1, fold.f2)
            t0 = psr_utils.calc_t0(midtime, fold.epoch, fold.f0, fold.f1, fold.f2)
            t0i= int(t0 + 1e-9)
Esempio n. 14
0
        except KeyError:
            sys.stderr.write("Unknown telescope!!! : " + fold_pfd.telescope)

    # Read the polyco file (if required)
    if (fold.psr and fold.topo):
        if (fold_pfd.__dict__.has_key("polycos")
                and not fold_pfd.polycos == 0):
            pcs = fold_pfd.polycos
        else:
            pcs = polycos(fold.psr, sys.argv[-1] + ".polycos")
        (fold.phs0, fold.f0) = pcs.get_phs_and_freq(fold.epochi, fold.epochf)
        fold.f1 = fold.f2 = 0.0
    else:
        pcs = None
        fold.phs0 = 0.0
        (fold.f0, fold.f1, fold.f2) = psr_utils.p_to_f(fold.p0, fold.p1,
                                                       fold.p2)

    #
    # Calculate the TOAs
    #

    if t2format:
        print "FORMAT 1"

    for ii in range(numtoas):

        # The .pfd file was generated using -nosearch and a specified
        # folding period, p-dot, and p-dotdot (or f, f-dot, and f-dotdot).
        if (pcs is None):
            # Time at the middle of the interval in question
            midtime = fold.epoch + (ii + 0.5) * timestep_day
Esempio n. 15
0
    def __init__(self, cand_num, pfd , snr, coherent_power, \
                        incoherent_power, num_hits, num_harmonics, \
                        versionnum, sigma, sifting_period, sifting_dm, \
                        cand_attribs, header_id=None):
        self.header_id = header_id # Header ID from database
        self.cand_num = cand_num # Unique identifier of candidate within beam's 
                                 # list of candidates; Candidate's position in
                                 # a list of all candidates produced in beam
                                 # ordered by decreasing sigma (where largest
                                 # sigma has cand_num=1).
        self.topo_freq, self.topo_f_dot, fdd = \
                psr_utils.p_to_f(pfd.topo_p1, pfd.topo_p2, pfd.topo_p3)
        self.bary_freq, self.bary_f_dot, baryfdd = \
                psr_utils.p_to_f(pfd.bary_p1, pfd.bary_p2, pfd.bary_p3)
        self.dm = pfd.bestdm # Dispersion measure
        self.snr = snr # signal-to-noise ratio
        self.coherent_power = coherent_power # Coherent power
        self.incoherent_power = incoherent_power # Incoherent power
        self.num_hits = num_hits # Number of dedispersed timeseries candidate was found in
        self.num_harmonics = num_harmonics # Number of harmonics candidate was 
                                           # most significant with
        self.versionnum = versionnum # Version number; a combination of PRESTO's githash
                                     # and pipeline's githash
        self.sigma = sigma # PRESTO's sigma value

        #red_chi2 = pfd.bestprof.chi_sqr #prepfold reduced chi-squared
        #dof = pfd.proflen - 1 # degrees of freedom
        ##prepfold sigma
        #self.prepfold_sigma = \
        #        scipy.special.ndtri(scipy.special.chdtr(dof,dof*red_chi2)) 
        #off_red_chi2 = pfd.estimate_offsignal_redchi2()
        #chi2_scale = 1.0/off_red_chi2
        #new_red_chi2 = chi2_scale * red_chi2
        ## prepfold sigma rescaled to deal with chi-squared suppression
        ## a problem when strong rfi is present
        #self.rescaled_prepfold_sigma = \
        #        scipy.special.ndtri(scipy.special.chdtr(dof,dof*new_red_chi2))

        self.prepfold_sigma = float(cand_attribs['prepfold_sigma'])
        self.rescaled_prepfold_sigma = float(cand_attribs['rescaled_prepfold_sigma'])

        if np.isinf(self.prepfold_sigma):
            self.prepfold_sigma = 9999.0
        if np.isinf(self.rescaled_prepfold_sigma):
            self.rescaled_prepfold_sigma = 9999.0

        self.sifting_period = sifting_period # the period returned by accelsearch
                                             # (not optimized by prepfold)
        self.sifting_dm = sifting_dm # the DM returned by accelsearch
                                     # (not optimized by prepfold)


        # Store a few configurations so the upload can be checked
        self.pipeline = config.basic.pipeline
        self.institution = config.basic.institution
    
        # Calculate a few more values
        self.topo_period = 1.0/self.topo_freq
        self.bary_period = 1.0/self.bary_freq

        # List of dependents (ie other uploadables that require 
        # the pdm_cand_id from this candidate)
        self.dependents = []
Esempio n. 16
0
psrs = pulsars.values()
psrs.sort()

# Now create a new dictionary of pulsars with aliases
psr_aliases = {}
for psr in psrs:
    if psr.alias:
        psr_aliases[psr.alias] = psr

# Add a couple important pulsars
for psr in psrs:
    if psr.jname=="1614-23":
        psr.jname=="1614-2318"
        psr.f = 29.8475387364133766
        psr.fd = -4.683105034721e-17
        psr.p, psr.pd = psr_utils.p_to_f(psr.f, psr.fd)
        psr.x  = 1.327490
        psr.e  = 0.0
        psr.To = 52819.878171
        psr.pb = 3.15238573
        psr.w  = 0.0
        psr.dm = 52.43
        psr.l  = 351.91856
        psr.b  = 19.74496
        psr.dist = 1.80

# If calling this as a main program, then write out the new pulsars.cat file
if __name__ == '__main__' :
    presto_path = os.getenv("PRESTO")
    outfilename = os.path.join(presto_path, "lib", "pulsars.cat")
    outfile = open(outfilename, "w")
Esempio n. 17
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()
Esempio n. 18
0
 def __init__(self, filename):
     self.pfd_filename = filename
     infile = open(filename, "rb")
     # See if the .bestprof file is around
     try:
         self.bestprof = bestprof(filename+".bestprof")
     except IOError:
         self.bestprof = 0
     swapchar = '<' # this is little-endian
     data = infile.read(5*4)
     testswap = struct.unpack(swapchar+"i"*5, data)
     # This is a hack to try and test the endianness of the data.
     # None of the 5 values should be a large positive number.
     if (Num.fabs(Num.asarray(testswap))).max() > 100000:
         swapchar = '>' # this is big-endian
     (self.numdms, self.numperiods, self.numpdots, self.nsub, self.npart) = \
                   struct.unpack(swapchar+"i"*5, data)
     (self.proflen, self.numchan, self.pstep, self.pdstep, self.dmstep, \
      self.ndmfact, self.npfact) = struct.unpack(swapchar+"i"*7, infile.read(7*4))
     self.filenm = infile.read(struct.unpack(swapchar+"i", infile.read(4))[0])
     self.candnm = infile.read(struct.unpack(swapchar+"i", infile.read(4))[0])
     self.telescope = infile.read(struct.unpack(swapchar+"i", infile.read(4))[0])
     self.pgdev = infile.read(struct.unpack(swapchar+"i", infile.read(4))[0])
     test = infile.read(16)
     has_posn = 1
     for ii in range(16):
         if test[ii] not in '0123456789:.-\0':
             has_posn = 0
             break
     if has_posn:
         self.rastr = test[:test.find('\0')]
         test = infile.read(16)
         self.decstr = test[:test.find('\0')]
         (self.dt, self.startT) = struct.unpack(swapchar+"dd", infile.read(2*8))
     else:
         self.rastr = "Unknown"
         self.decstr = "Unknown"
         (self.dt, self.startT) = struct.unpack(swapchar+"dd", test)
     (self.endT, self.tepoch, self.bepoch, self.avgvoverc, self.lofreq, \
      self.chan_wid, self.bestdm) = struct.unpack(swapchar+"d"*7, infile.read(7*8))
     # The following "fixes" (we think) the observing frequency of the Spigot
     # based on tests done by Ingrid on 0737 (comparing it to GASP)
     # The same sorts of corrections should be made to WAPP data as well...
     # The tepoch corrections are empirically determined timing corrections
     # Note that epoch is only double precision and so the floating
     # point accuracy is ~1 us!
     if self.telescope=='GBT':
         if (Num.fabs(Num.fmod(self.dt, 8.192e-05) < 1e-12) and \
             ("spigot" in filename.lower() or "guppi" not in filename.lower()) and \
             (self.tepoch < 54832.0)):
             sys.stderr.write("Assuming SPIGOT data...\n")
             if self.chan_wid==800.0/1024: # Spigot 800 MHz mode 2
                 self.lofreq -= 0.5 * self.chan_wid
                 # original values
                 #if self.tepoch > 0.0: self.tepoch += 0.039334/86400.0
                 #if self.bestprof: self.bestprof.epochf += 0.039334/86400.0
                 # values measured with 1713+0747 wrt BCPM2 on 13 Sept 2007
                 if self.tepoch > 0.0: self.tepoch += 0.039365/86400.0
                 if self.bestprof: self.bestprof.epochf += 0.039365/86400.0
             elif self.chan_wid==800.0/2048:
                 self.lofreq -= 0.5 * self.chan_wid 
                 if self.tepoch < 53700.0:  # Spigot 800 MHz mode 16 (downsampled)
                     if self.tepoch > 0.0: self.tepoch += 0.039352/86400.0
                     if self.bestprof: self.bestprof.epochf += 0.039352/86400.0
                 else:  # Spigot 800 MHz mode 14 
                     # values measured with 1713+0747 wrt BCPM2 on 13 Sept 2007
                     if self.tepoch > 0.0: self.tepoch += 0.039365/86400.0
                     if self.bestprof: self.bestprof.epochf += 0.039365/86400.0
             elif self.chan_wid==50.0/1024 or self.chan_wid==50.0/2048: # Spigot 50 MHz modes
                 self.lofreq += 0.5 * self.chan_wid
                 # Note: the offset has _not_ been measured for the 2048-lag mode
                 if self.tepoch > 0.0: self.tepoch += 0.039450/86400.0
                 if self.bestprof: self.bestprof.epochf += 0.039450/86400.0
     (self.topo_pow, tmp) = struct.unpack(swapchar+"f"*2, infile.read(2*4))
     (self.topo_p1, self.topo_p2, self.topo_p3) = struct.unpack(swapchar+"d"*3, \
                                                                infile.read(3*8))
     (self.bary_pow, tmp) = struct.unpack(swapchar+"f"*2, infile.read(2*4))
     (self.bary_p1, self.bary_p2, self.bary_p3) = struct.unpack(swapchar+"d"*3, \
                                                                infile.read(3*8))
     (self.fold_pow, tmp) = struct.unpack(swapchar+"f"*2, infile.read(2*4))
     (self.fold_p1, self.fold_p2, self.fold_p3) = struct.unpack(swapchar+"d"*3, \
                                                                infile.read(3*8))
     # Save current p, pd, pdd
     # NOTE: Fold values are actually frequencies!
     self.curr_p1, self.curr_p2, self.curr_p3 = \
             psr_utils.p_to_f(self.fold_p1, self.fold_p2, self.fold_p3)
     self.pdelays_bins = Num.zeros(self.npart, dtype='d')
     (self.orb_p, self.orb_e, self.orb_x, self.orb_w, self.orb_t, self.orb_pd, \
      self.orb_wd) = struct.unpack(swapchar+"d"*7, infile.read(7*8))
     self.dms = Num.asarray(struct.unpack(swapchar+"d"*self.numdms, \
                                          infile.read(self.numdms*8)))
     if self.numdms==1:
         self.dms = self.dms[0]
     self.periods = Num.asarray(struct.unpack(swapchar+"d"*self.numperiods, \
                                              infile.read(self.numperiods*8)))
     self.pdots = Num.asarray(struct.unpack(swapchar+"d"*self.numpdots, \
                                            infile.read(self.numpdots*8)))
     self.numprofs = self.nsub*self.npart
     if (swapchar=='<'):  # little endian
         self.profs = Num.zeros((self.npart, self.nsub, self.proflen), dtype='d')
         for ii in range(self.npart):
             for jj in range(self.nsub):
                 self.profs[ii,jj,:] = Num.fromfile(infile, Num.float64, self.proflen)
     else:
         self.profs = Num.asarray(struct.unpack(swapchar+"d"*self.numprofs*self.proflen, \
                                                infile.read(self.numprofs*self.proflen*8)))
         self.profs = Num.reshape(self.profs, (self.npart, self.nsub, self.proflen))
     if (self.numchan==1):
         try:
             idata = infodata.infodata(self.filenm[:self.filenm.rfind('.')]+".inf")
             if idata.waveband=="Radio":
                 self.bestdm = idata.DM
                 self.numchan = idata.numchan
             else: # i.e. for events
                 self.bestdm = 0.0
                 self.numchan = 1
         except IOError:
             print "Warning!  Can't open the .inf file for "+filename+"!"
     self.binspersec = self.fold_p1*self.proflen
     self.chanpersub = self.numchan/self.nsub
     self.subdeltafreq = self.chan_wid*self.chanpersub
     self.hifreq = self.lofreq + (self.numchan-1)*self.chan_wid
     self.losubfreq = self.lofreq + self.subdeltafreq - self.chan_wid
     self.subfreqs = Num.arange(self.nsub, dtype='d')*self.subdeltafreq + \
                     self.losubfreq
     self.subdelays_bins = Num.zeros(self.nsub, dtype='d')
     # Save current DM
     self.currdm = 0
     self.killed_subbands = []
     self.killed_intervals = []
     self.pts_per_fold = []
     # Note: a foldstats struct is read in as a group of 7 doubles
     # the correspond to, in order: 
     #    numdata, data_avg, data_var, numprof, prof_avg, prof_var, redchi
     self.stats = Num.zeros((self.npart, self.nsub, 7), dtype='d')
     for ii in range(self.npart):
         currentstats = self.stats[ii]
         for jj in range(self.nsub):
             if (swapchar=='<'):  # little endian
                 currentstats[jj] = Num.fromfile(infile, Num.float64, 7)
             else:
                 currentstats[jj] = Num.asarray(struct.unpack(swapchar+"d"*7, \
                                                              infile.read(7*8)))
         self.pts_per_fold.append(self.stats[ii][0][0])  # numdata from foldstats
     self.start_secs = Num.add.accumulate([0]+self.pts_per_fold[:-1])*self.dt
     self.pts_per_fold = Num.asarray(self.pts_per_fold)
     self.mid_secs = self.start_secs + 0.5*self.dt*self.pts_per_fold
     if (not self.tepoch==0.0):
         self.start_topo_MJDs = self.start_secs/86400.0 + self.tepoch
         self.mid_topo_MJDs = self.mid_secs/86400.0 + self.tepoch
     if (not self.bepoch==0.0):
         self.start_bary_MJDs = self.start_secs/86400.0 + self.bepoch
         self.mid_bary_MJDs = self.mid_secs/86400.0 + self.bepoch
     self.Nfolded = Num.add.reduce(self.pts_per_fold)
     self.T = self.Nfolded*self.dt
     self.avgprof = (self.profs/self.proflen).sum()
     self.varprof = self.calc_varprof()
     infile.close()
     self.barysubfreqs = None
     if self.avgvoverc==0:
         if self.candnm.startswith("PSR_"):
             # If this doesn't work, we should try to use the barycentering calcs
             # in the presto module.
             try:
                 self.polycos = polycos.polycos(self.candnm[4:],
                                                filenm=self.pfd_filename+".polycos")
                 midMJD = self.tepoch + 0.5*self.T/86400.0
                 self.avgvoverc = self.polycos.get_voverc(int(midMJD), midMJD-int(midMJD))
                 #sys.stderr.write("Approximate Doppler velocity (in c) is:  %.4g\n"%self.avgvoverc)
                 # Make the Doppler correction
                 self.barysubfreqs = self.subfreqs*(1.0+self.avgvoverc)
             except IOError:
                 self.polycos = 0
     if self.barysubfreqs is None:
         self.barysubfreqs = self.subfreqs
Esempio n. 19
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()
Esempio n. 20
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()
Esempio n. 21
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()
Esempio n. 22
0
params_start = [p_start, pb_sec_start, x_start, T0_start, e_start, w_start]

# build the dictionary of parameter information
params_info = get_params_info(params_start, const_params)

period = []
time = []
pepochs = []
p0s = []
p1s = []
# get the observed periods and times from the .bestprof files
for in_file in in_files:
    if in_file.endswith(".par"):
        (epoch, T, fs) = read_par(in_file)
        if fs[1] != 0.0:
            p0tmp, p1tmp = psr_utils.p_to_f(fs[0], fs[1])
            p0s.append(p0tmp)
            p1s.append(p1tmp)
            pepochs.append(epoch)
        for minute in arange(int(T / 60.0 + 0.5)):
            t = epoch + minute / 1440.0
            time.append(t)
            period.append(1.0 / psr_utils.calc_freq(t, epoch, *fs))
    else:
        (epoch, T, p0, p1, p2) = read_bestprof(in_file)
        for minute in arange(int(T / 60.0 + 0.5)):
            t = minute * 60.0
            time.append(epoch + minute / 1440.0)
            period.append(p0 + t * (p1 + 0.5 * t * p2))
            if p1 != 0.0:
                p0s.append(p0)
Esempio n. 23
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()
Esempio n. 24
0
params_start = [p_start, pb_sec_start, x_start, T0_start, e_start, w_start]

# build the dictionary of parameter information
params_info = get_params_info(params_start, const_params)

period = []
time = []
pepochs = []
p0s = []
p1s = []
# get the observed periods and times from the .bestprof files
for in_file in in_files:
    if in_file.endswith('.par'):
        (epoch, T, fs) = read_par(in_file)
        if (fs[1] != 0.0):
            p0tmp, p1tmp = psr_utils.p_to_f(fs[0], fs[1])
            p0s.append(p0tmp)
            p1s.append(p1tmp)
            pepochs.append(epoch)
        for minute in arange(int(T / 60.0 + 0.5)):
            t = epoch + minute / 1440.0
            time.append(t)
            period.append(1.0 / psr_utils.calc_freq(t, epoch, *fs))
    else:
        (epoch, T, p0, p1, p2) = read_bestprof(in_file)
        for minute in arange(int(T / 60.0 + 0.5)):
            t = minute * 60.0
            time.append(epoch + minute / 1440.0)
            period.append(p0 + t * (p1 + 0.5 * t * p2))
            if p1 != 0.0:
                p0s.append(p0)
Esempio n. 25
0
 def __init__(self, filename):
     self.pfd_filename = filename
     infile = open(filename, "rb")
     # See if the .bestprof file is around
     try:
         self.bestprof = bestprof(filename+".bestprof")
     except IOError:
         self.bestprof = 0
     swapchar = '<' # this is little-endian
     data = infile.read(5*4)
     testswap = struct.unpack(swapchar+"i"*5, data)
     # This is a hack to try and test the endianness of the data.
     # None of the 5 values should be a large positive number.
     if (Num.fabs(Num.asarray(testswap))).max() > 100000:
         swapchar = '>' # this is big-endian
     (self.numdms, self.numperiods, self.numpdots, self.nsub, self.npart) = \
                   struct.unpack(swapchar+"i"*5, data)
     (self.proflen, self.numchan, self.pstep, self.pdstep, self.dmstep, \
      self.ndmfact, self.npfact) = struct.unpack(swapchar+"i"*7, infile.read(7*4))
     self.filenm = infile.read(struct.unpack(swapchar+"i", infile.read(4))[0])
     self.candnm = infile.read(struct.unpack(swapchar+"i", infile.read(4))[0])
     self.telescope = infile.read(struct.unpack(swapchar+"i", infile.read(4))[0])
     self.pgdev = infile.read(struct.unpack(swapchar+"i", infile.read(4))[0])
     test = infile.read(16)
     if not test[:8]=="Unknown":
         self.rastr = test[:test.find('\0')]
         test = infile.read(16)
         self.decstr = test[:test.find('\0')]
     else:
         self.rastr = "Unknown"
         self.decstr = "Unknown"
     (self.dt, self.startT) = struct.unpack(swapchar+"dd", infile.read(2*8))
     (self.endT, self.tepoch, self.bepoch, self.avgvoverc, self.lofreq, \
      self.chan_wid, self.bestdm) = struct.unpack(swapchar+"d"*7, infile.read(7*8))
     # The following "fixes" (we think) the observing frequency of the Spigot
     # based on tests done by Ingrid on 0737 (comparing it to GASP)
     # The same sorts of corrections should be made to WAPP data as well...
     # The tepoch corrections are empirically determined timing corrections
     # Note that epoch is only double precision and so the floating
     # point accuracy is ~1 us!
     if self.telescope=='GBT':
         if (Num.fabs(Num.fmod(self.dt, 8.192e-05) < 1e-12) and \
             ("spigot" in filename.lower() or "guppi" not in filename.lower()) and \
             (self.tepoch < 54832.0)):
             sys.stderr.write("Assuming SPIGOT data...\n")
             if self.chan_wid==800.0/1024: # Spigot 800 MHz mode 2
                 self.lofreq -= 0.5 * self.chan_wid
                 # original values
                 #if self.tepoch > 0.0: self.tepoch += 0.039334/86400.0
                 #if self.bestprof: self.bestprof.epochf += 0.039334/86400.0
                 # values measured with 1713+0747 wrt BCPM2 on 13 Sept 2007
                 if self.tepoch > 0.0: self.tepoch += 0.039365/86400.0
                 if self.bestprof: self.bestprof.epochf += 0.039365/86400.0
             elif self.chan_wid==800.0/2048:
                 self.lofreq -= 0.5 * self.chan_wid
                 if self.tepoch < 53700.0:  # Spigot 800 MHz mode 16 (downsampled)
                     if self.tepoch > 0.0: self.tepoch += 0.039352/86400.0
                     if self.bestprof: self.bestprof.epochf += 0.039352/86400.0
                 else:  # Spigot 800 MHz mode 14
                     # values measured with 1713+0747 wrt BCPM2 on 13 Sept 2007
                     if self.tepoch > 0.0: self.tepoch += 0.039365/86400.0
                     if self.bestprof: self.bestprof.epochf += 0.039365/86400.0
             elif self.chan_wid==50.0/1024 or self.chan_wid==50.0/2048: # Spigot 50 MHz modes
                 self.lofreq += 0.5 * self.chan_wid
                 # Note: the offset has _not_ been measured for the 2048-lag mode
                 if self.tepoch > 0.0: self.tepoch += 0.039450/86400.0
                 if self.bestprof: self.bestprof.epochf += 0.039450/86400.0
     (self.topo_pow, tmp) = struct.unpack(swapchar+"f"*2, infile.read(2*4))
     (self.topo_p1, self.topo_p2, self.topo_p3) = struct.unpack(swapchar+"d"*3, \
                                                                infile.read(3*8))
     (self.bary_pow, tmp) = struct.unpack(swapchar+"f"*2, infile.read(2*4))
     (self.bary_p1, self.bary_p2, self.bary_p3) = struct.unpack(swapchar+"d"*3, \
                                                                infile.read(3*8))
     (self.fold_pow, tmp) = struct.unpack(swapchar+"f"*2, infile.read(2*4))
     (self.fold_p1, self.fold_p2, self.fold_p3) = struct.unpack(swapchar+"d"*3, \
                                                                infile.read(3*8))
     # Save current p, pd, pdd
     # NOTE: Fold values are actually frequencies!
     self.curr_p1, self.curr_p2, self.curr_p3 = \
             psr_utils.p_to_f(self.fold_p1, self.fold_p2, self.fold_p3)
     self.pdelays_bins = Num.zeros(self.npart, dtype='d')
     (self.orb_p, self.orb_e, self.orb_x, self.orb_w, self.orb_t, self.orb_pd, \
      self.orb_wd) = struct.unpack(swapchar+"d"*7, infile.read(7*8))
     self.dms = Num.asarray(struct.unpack(swapchar+"d"*self.numdms, \
                                          infile.read(self.numdms*8)))
     if self.numdms==1:
         self.dms = self.dms[0]
     self.periods = Num.asarray(struct.unpack(swapchar+"d"*self.numperiods, \
                                              infile.read(self.numperiods*8)))
     self.pdots = Num.asarray(struct.unpack(swapchar+"d"*self.numpdots, \
                                            infile.read(self.numpdots*8)))
     self.numprofs = self.nsub*self.npart
     if (swapchar=='<'):  # little endian
         self.profs = Num.zeros((self.npart, self.nsub, self.proflen), dtype='d')
         for ii in range(self.npart):
             for jj in range(self.nsub):
                 self.profs[ii,jj,:] = Num.fromfile(infile, Num.float64, self.proflen)
     else:
         self.profs = Num.asarray(struct.unpack(swapchar+"d"*self.numprofs*self.proflen, \
                                                infile.read(self.numprofs*self.proflen*8)))
         self.profs = Num.reshape(self.profs, (self.npart, self.nsub, self.proflen))
     if (self.numchan==1):
         try:
             idata = infodata.infodata(self.filenm[:self.filenm.rfind('.')]+".inf")
             try:
                 if idata.waveband=="Radio":
                     self.bestdm = idata.DM
                     self.numchan = idata.numchan
             except:
                     self.bestdm = 0.0
                     self.numchan = 1
         except IOError:
             print "Warning!  Can't open the .inf file for "+filename+"!"
     self.binspersec = self.fold_p1*self.proflen
     self.chanpersub = self.numchan/self.nsub
     self.subdeltafreq = self.chan_wid*self.chanpersub
     self.hifreq = self.lofreq + (self.numchan-1)*self.chan_wid
     self.losubfreq = self.lofreq + self.subdeltafreq - self.chan_wid
     self.subfreqs = Num.arange(self.nsub, dtype='d')*self.subdeltafreq + \
                     self.losubfreq
     self.subdelays_bins = Num.zeros(self.nsub, dtype='d')
     # Save current DM
     self.currdm = 0
     self.killed_subbands = []
     self.killed_intervals = []
     self.pts_per_fold = []
     # Note: a foldstats struct is read in as a group of 7 doubles
     # the correspond to, in order:
     #    numdata, data_avg, data_var, numprof, prof_avg, prof_var, redchi
     self.stats = Num.zeros((self.npart, self.nsub, 7), dtype='d')
     for ii in range(self.npart):
         currentstats = self.stats[ii]
         for jj in range(self.nsub):
             if (swapchar=='<'):  # little endian
                 currentstats[jj] = Num.fromfile(infile, Num.float64, 7)
             else:
                 currentstats[jj] = Num.asarray(struct.unpack(swapchar+"d"*7, \
                                                              infile.read(7*8)))
         self.pts_per_fold.append(self.stats[ii][0][0])  # numdata from foldstats
     self.start_secs = Num.add.accumulate([0]+self.pts_per_fold[:-1])*self.dt
     self.pts_per_fold = Num.asarray(self.pts_per_fold)
     self.mid_secs = self.start_secs + 0.5*self.dt*self.pts_per_fold
     if (not self.tepoch==0.0):
         self.start_topo_MJDs = self.start_secs/86400.0 + self.tepoch
         self.mid_topo_MJDs = self.mid_secs/86400.0 + self.tepoch
     if (not self.bepoch==0.0):
         self.start_bary_MJDs = self.start_secs/86400.0 + self.bepoch
         self.mid_bary_MJDs = self.mid_secs/86400.0 + self.bepoch
     self.Nfolded = Num.add.reduce(self.pts_per_fold)
     self.T = self.Nfolded*self.dt
     self.avgprof = (self.profs/self.proflen).sum()
     self.varprof = self.calc_varprof()
     # nominal number of degrees of freedom for reduced chi^2 calculation
     self.DOFnom = float(self.proflen) - 1.0
     # corrected number of degrees of freedom due to inter-bin correlations
     self.dt_per_bin = self.curr_p1 / self.proflen / self.dt
     self.DOFcor = self.DOFnom * self.DOF_corr()
     infile.close()
     self.barysubfreqs = None
     if self.avgvoverc==0:
         if self.candnm.startswith("PSR_"):
             # If this doesn't work, we should try to use the barycentering calcs
             # in the presto module.
             try:
                 self.polycos = polycos.polycos(self.candnm[4:],
                                                filenm=self.pfd_filename+".polycos")
                 midMJD = self.tepoch + 0.5*self.T/86400.0
                 self.avgvoverc = self.polycos.get_voverc(int(midMJD), midMJD-int(midMJD))
                 #sys.stderr.write("Approximate Doppler velocity (in c) is:  %.4g\n"%self.avgvoverc)
                 # Make the Doppler correction
                 self.barysubfreqs = self.subfreqs*(1.0+self.avgvoverc)
             except IOError:
                 self.polycos = 0
     if self.barysubfreqs is None:
         self.barysubfreqs = self.subfreqs
Esempio n. 26
0
psrs = pulsars.values()
psrs.sort()

# Now create a new dictionary of pulsars with aliases
psr_aliases = {}
for psr in psrs:
    if psr.alias:
        psr_aliases[psr.alias] = psr

# Add a couple important pulsars
for psr in psrs:
    if psr.jname == "1614-23":
        psr.jname == "1614-2318"
        psr.f = 29.8475387364133766
        psr.fd = -4.683105034721e-17
        psr.p, psr.pd = psr_utils.p_to_f(psr.f, psr.fd)
        psr.x = 1.327490
        psr.e = 0.0
        psr.To = 52819.878171
        psr.pb = 3.15238573
        psr.w = 0.0
        psr.dm = 52.43
        psr.l = 351.91856
        psr.b = 19.74496
        psr.dist = 1.80

# If calling this as a main program, then write out the new pulsars.cat file
if __name__ == '__main__':
    presto_path = os.getenv("PRESTO")
    outfilename = os.path.join(presto_path, "lib", "pulsars.cat")
    outfile = open(outfilename, "w")
Esempio n. 27
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()
Esempio n. 28
0
    def __init__(self, cand_num, pfd , snr, coherent_power, \
                        incoherent_power, num_hits, num_harmonics, \
                        versionnum, sigma, sifting_period, sifting_dm, \
                        cand_attribs, search_type, header_id=None):
        self.header_id = header_id # Header ID from database
        self.cand_num = cand_num # Unique identifier of candidate within beam's 
                                 # list of candidates; Candidate's position in
                                 # a list of all candidates produced in beam
                                 # ordered by decreasing sigma (where largest
                                 # sigma has cand_num=1).
        self.search_type = search_type
        self.topo_freq, self.topo_f_dot, fdd = \
                psr_utils.p_to_f(pfd.topo_p1, pfd.topo_p2, pfd.topo_p3)
        self.bary_freq, self.bary_f_dot, baryfdd = \
                psr_utils.p_to_f(pfd.bary_p1, pfd.bary_p2, pfd.bary_p3)

        self.dm = pfd.bestdm # Dispersion measure
        self.snr = snr # signal-to-noise ratio
        self.coherent_power = coherent_power # Coherent power
        self.incoherent_power = incoherent_power # Incoherent power
        self.num_hits = num_hits # Number of dedispersed timeseries candidate was found in
        self.num_harmonics = num_harmonics # Number of harmonics candidate was 
                                           # most significant with
        self.versionnum = versionnum # Version number; a combination of PRESTO's githash
                                     # and pipeline's githash
        self.sigma = sigma # PRESTO's sigma value

        #red_chi2 = pfd.bestprof.chi_sqr #prepfold reduced chi-squared
        #dof = pfd.proflen - 1 # degrees of freedom
        ##prepfold sigma
        #self.prepfold_sigma = \
        #        scipy.special.ndtri(scipy.special.chdtr(dof,dof*red_chi2)) 
        #off_red_chi2 = pfd.estimate_offsignal_redchi2()
        #chi2_scale = 1.0/off_red_chi2
        #new_red_chi2 = chi2_scale * red_chi2
        ## prepfold sigma rescaled to deal with chi-squared suppression
        ## a problem when strong rfi is present
        #self.rescaled_prepfold_sigma = \
        #        scipy.special.ndtri(scipy.special.chdtr(dof,dof*new_red_chi2))

        self.prepfold_sigma = float(cand_attribs['prepfold_sigma'])
        self.rescaled_prepfold_sigma = float(cand_attribs['rescaled_prepfold_sigma'])

        if np.isinf(self.prepfold_sigma):
            self.prepfold_sigma = 9999.0
        if np.isinf(self.rescaled_prepfold_sigma):
            self.rescaled_prepfold_sigma = 9999.0

        self.sifting_period = sifting_period # the period returned by accelsearch
                                             # (not optimized by prepfold)
        self.sifting_dm = sifting_dm # the DM returned by accelsearch
                                     # (not optimized by prepfold)


        # Store a few configurations so the upload can be checked
        self.pipeline = config.basic.pipeline
        self.institution = config.basic.institution
    

        # Calculate a few more values
        self.topo_period = 1.0/self.topo_freq
        self.bary_period = 1.0/self.bary_freq
        # List of dependents (ie other uploadables that require 
        # the pdm_cand_id from this candidate)
        self.dependents = []