예제 #1
0
    def __init__(self, freqbands=[[0, 'inf']]):
        """Read TEMPO results (resid2.tmp, tempo.lis, timfile and parfiles)
            freqbands is a list of frequency pairs to display.
        """
        # Open tempo.lis. Parse it and find input .tim and .par files. Also find output .par file.
        inputfiles_re = re.compile(r"Input data from (.*\.tim.*),  Parameters from (.*\.par.*)")
        outputfile_re = re.compile(r"Assumed parameters -- PSR (.*)$")
        tempolisfile = open("tempo.lis")
        intimfn, inparfn, outparfn = None, None, None
        for line in tempolisfile:
            match = inputfiles_re.search(line)
            if match:
                intimfn = match.group(1).strip()
                inparfn = match.group(2).strip()
            else:
                match = outputfile_re.search(line)
                if match:
                    outparfn = "%s.par" % match.group(1).strip()
            if (intimfn != None) and (inparfn != None) and (outparfn != None):
                # Found what we're looking for no need to continue parsing the file
                break
        tempolisfile.close()

        # Record filename
        self.inparfn = inparfn
        self.outparfn = outparfn
        self.intimfn = intimfn

        # Read parfiles
        self.inpar = par.psr_par(inparfn)
        self.outpar = par.psr_par(outparfn)

        # Read residuals
        # Need to check if on 32-bit or 64-bit computer
        #(the following is a hack to find out if we're on a borg or borgii node)
#PATRICKS QUICK FIX 10/14   -   3/39/11 read_residuals_64bit does not work on nimrod or my machine, but 32bit does...
        #print os.uname()[4]
        if True: #os.uname()[4]=='i686':
            # 32-bit computer
            r = residuals.read_residuals()
        else:
            # 64-bit computer
            r = residuals.read_residuals_64bit()

        self.max_TOA = r.bary_TOA.max()
        self.min_TOA = r.bary_TOA.min()
        self.freqbands = freqbands
        self.residuals = {}
        for lo,hi in self.freqbands:
            indices = (r.bary_freq>=lo) & (r.bary_freq<hi)
            self.residuals[get_freq_label(lo, hi)] = \
                 Resids(r.bary_TOA[indices], r.bary_freq[indices], \
                        np.arange(r.numTOAs)[indices], r.orbit_phs[indices], \
                        r.postfit_phs[indices], r.postfit_sec[indices], \
                        r.prefit_phs[indices], r.prefit_sec[indices], \
                        r.uncertainty[indices], r.weight[indices], \
                        self.inpar, self.outpar)
예제 #2
0
    def __init__(self, freqbands):
        """Read TEMPO results (resid2.tmp, tempo.lis, timfile and parfiles)
            freqbands is a list of frequency pairs to display.
        """
        # Open tempo.lis. Parse it and find input .tim and .par files. Also find output .par file.
        inputfiles_re = re.compile(
            r"Input data from (.*\.tim.*),  Parameters from (.*\.par.*)")
        outputfile_re = re.compile(r"Assumed parameters -- PSR (.*)$")
        tempolisfile = open("tempo.lis")
        intimfn, inparfn, outparfn = None, None, None
        for line in tempolisfile:
            if line[:15] == "Input data from":
                sline = line.split()
                intimfn = sline[3][:-1]  # strip the comma
                intimbase = os.path.splitext(intimfn)[0]
                inparfn = intimbase + ".par" if sline[6] == 'def' else sline[6]
                if inparfn[-1] == ".": inparfn = inparfn[:-1]
            elif line[:15] == "Assumed paramet":
                outparfn = line.split()[-1] + ".par"
            if (intimfn != None) and (inparfn != None) and (outparfn != None):
                # Found what we're looking for no need to continue parsing the file
                break
        tempolisfile.close()

        # Record filename
        self.inparfn = inparfn
        self.outparfn = outparfn
        self.intimfn = intimfn

        # Read parfiles
        self.inpar = par.psr_par(inparfn)
        self.outpar = par.psr_par(outparfn)

        # Read residuals
        r = residuals.read_residuals()

        self.max_TOA = r.bary_TOA.max()
        self.min_TOA = r.bary_TOA.min()

        if freqbands is None:
            self.freqbands = find_freq_clusters(r.bary_freq)
        else:
            self.freqbands = freqbands
        self.residuals = {}
        for lo, hi in self.freqbands:
            indices = (r.bary_freq >= lo) & (r.bary_freq < hi)
            self.residuals[get_freq_label(lo, hi)] = \
                 Resids(r.bary_TOA[indices], r.bary_freq[indices], \
                        np.arange(r.numTOAs)[indices], r.orbit_phs[indices], \
                        r.postfit_phs[indices], r.postfit_sec[indices], \
                        r.prefit_phs[indices], r.prefit_sec[indices], \
                        r.uncertainty[indices], r.weight[indices], \
                        self.inpar, self.outpar)
예제 #3
0
    def __init__(self, freqbands):
        """Read TEMPO results (resid2.tmp, tempo.lis, timfile and parfiles)
            freqbands is a list of frequency pairs to display.
        """
        # Open tempo.lis. Parse it and find input .tim and .par files. Also find output .par file.
        inputfiles_re = re.compile(
            r"Input data from (.*\.tim.*),  Parameters from (.*\.par.*)")
        outputfile_re = re.compile(r"Assumed parameters -- PSR (.*)$")
        tempolisfile = open("tempo.lis")
        intimfn, inparfn, outparfn = None, None, None
        for line in tempolisfile:
            match = inputfiles_re.search(line)
            if match:
                intimfn = match.group(1).strip()
                inparfn = match.group(2).strip()
            else:
                match = outputfile_re.search(line)
                if match:
                    outparfn = "%s.par" % match.group(1).strip()
            if (intimfn != None) and (inparfn != None) and (outparfn != None):
                # Found what we're looking for no need to continue parsing the file
                break
        tempolisfile.close()

        # Record filename
        self.inparfn = inparfn
        self.outparfn = outparfn
        self.intimfn = intimfn

        # Read parfiles
        self.inpar = par.psr_par(inparfn)
        self.outpar = par.psr_par(outparfn)

        # Read residuals
        r = residuals.read_residuals()

        self.max_TOA = r.bary_TOA.max()
        self.min_TOA = r.bary_TOA.min()

        if freqbands is None:
            self.freqbands = find_freq_clusters(r.bary_freq)
        else:
            self.freqbands = freqbands
        self.residuals = {}
        for lo, hi in self.freqbands:
            indices = (r.bary_freq >= lo) & (r.bary_freq < hi)
            self.residuals[get_freq_label(lo, hi)] = \
                 Resids(r.bary_TOA[indices], r.bary_freq[indices], \
                        np.arange(r.numTOAs)[indices], r.orbit_phs[indices], \
                        r.postfit_phs[indices], r.postfit_sec[indices], \
                        r.prefit_phs[indices], r.prefit_sec[indices], \
                        r.uncertainty[indices], r.weight[indices], \
                        self.inpar, self.outpar)
예제 #4
0
    def __init__(self, freqbands):
        """Read TEMPO results (resid2.tmp, tempo.lis, timfile and parfiles)
            freqbands is a list of frequency pairs to display.
        """
        # Open tempo.lis. Parse it and find input .tim and .par files. Also find output .par file.
        inputfiles_re = re.compile(r"Input data from (.*\.tim.*),  Parameters from (.*\.par.*)")
        outputfile_re = re.compile(r"Assumed parameters -- PSR (.*)$")
        tempolisfile = open("tempo.lis")
        intimfn, inparfn, outparfn = None, None, None
        for line in tempolisfile:
            if line[:15]=="Input data from":
                sline = line.split()
                intimfn = sline[3][:-1] # strip the comma
                intimbase = os.path.splitext(intimfn)[0]
                inparfn = intimbase+".par" if sline[6]=='def' else sline[6]
                if inparfn[-1]==".": inparfn = inparfn[:-1]
            elif line[:15]=="Assumed paramet":
                outparfn = line.split()[-1]+".par"
            if (intimfn != None) and (inparfn != None) and (outparfn != None):
                # Found what we're looking for no need to continue parsing the file
                break
        tempolisfile.close()

        # Record filename
        self.inparfn = inparfn
        self.outparfn = outparfn
        self.intimfn = intimfn

        # Read parfiles
        self.inpar = par.psr_par(inparfn)
        self.outpar = par.psr_par(outparfn)

        # Read residuals
        r = residuals.read_residuals()

        self.max_TOA = r.bary_TOA.max()
        self.min_TOA = r.bary_TOA.min()

        if freqbands is None:
            self.freqbands = find_freq_clusters(r.bary_freq)
        else:
            self.freqbands = freqbands
        self.residuals = {}
        for lo,hi in self.freqbands:
            indices = (r.bary_freq>=lo) & (r.bary_freq<hi)
            self.residuals[get_freq_label(lo, hi)] = \
                 Resids(r.bary_TOA[indices], r.bary_freq[indices], \
                        np.arange(r.numTOAs)[indices], r.orbit_phs[indices], \
                        r.postfit_phs[indices], r.postfit_sec[indices], \
                        r.prefit_phs[indices], r.prefit_sec[indices], \
                        r.uncertainty[indices], r.weight[indices], \
                        self.inpar, self.outpar)
예제 #5
0
    def __init__(self, freqbands):
        """Read TEMPO results (resid2.tmp, tempo.lis, timfile and parfiles)
            freqbands is a list of frequency pairs to display.
        """
        # Open tempo.lis. Parse it and find input .tim and .par files. Also find output .par file.
        inputfiles_re = re.compile(r"Input data from (.*\.tim.*),  Parameters from (.*\.par.*)")
        outputfile_re = re.compile(r"Assumed parameters -- PSR (.*)$")
        tempolisfile = open("tempo.lis")
        intimfn, inparfn, outparfn = None, None, None
        for line in tempolisfile:
            match = inputfiles_re.search(line)
            if match:
                intimfn = match.group(1).strip()
                inparfn = match.group(2).strip()
            else:
                match = outputfile_re.search(line)
                if match:
                    outparfn = "%s.par" % match.group(1).strip()
            if (intimfn != None) and (inparfn != None) and (outparfn != None):
                # Found what we're looking for no need to continue parsing the file
                break
        tempolisfile.close()

        # Record filename
        self.inparfn = inparfn
        self.outparfn = outparfn
        self.intimfn = intimfn

        # Read parfiles
        self.inpar = par.psr_par(inparfn)
        self.outpar = par.psr_par(outparfn)

        # Read residuals
        r = residuals.read_residuals()

        self.max_TOA = r.bary_TOA.max()
        self.min_TOA = r.bary_TOA.min()

        if freqbands is None:
            self.freqbands = find_freq_clusters(r.bary_freq)
        else:
            self.freqbands = freqbands
        self.residuals = {}
        for lo,hi in self.freqbands:
            indices = (r.bary_freq>=lo) & (r.bary_freq<hi)
            self.residuals[get_freq_label(lo, hi)] = \
                 Resids(r.bary_TOA[indices], r.bary_freq[indices], \
                        np.arange(r.numTOAs)[indices], r.orbit_phs[indices], \
                        r.postfit_phs[indices], r.postfit_sec[indices], \
                        r.prefit_phs[indices], r.prefit_sec[indices], \
                        r.uncertainty[indices], r.weight[indices], \
                        self.inpar, self.outpar)
예제 #6
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)
예제 #7
0
 def __init__(self, parfilenm):
     self.par = parfile.psr_par(parfilenm)
     if not hasattr(self.par, 'BINARY'):
         print("'%s' doesn't contain parameters for a binary pulsar!")
         return None
     self.PBsec = self.par.PB * SECPERDAY
     self.T0 = self.par.T0
예제 #8
0
def read_par(pfname,f1errmax=999.0):
    pf = parfile.psr_par(pfname)
    f0 = pf.F0
    p0 = pf.P0
    try:
        f0err = pf.F0_ERR
    except:
        f0err = 2.0e-5
    if not isfinite(f0err):
        f0err = 3.0e-5
    f1 = pf.F1
    try:
        p1 = pf.P1
    except:
        p1 = 0.0
    try:
        f1err = pf.F1_ERR
    except:
        f1err = 10.0e-8
    mjd = pf.PEPOCH
    if (verbose):
#        print "%6s: %.4f F0 %10.9g +/- %8.03g   F1 %10.5g +/- %8.03g" % (pfname,mjd,f0,f0err,f1,f1err)
        print "%.4f %10.9g %8.3g  %10.5g %8.3g" % (mjd,f0,f0err,f1,f1err),
        if (f1err > f1errmax):
            print " * Ignored *"
        else:
            print
#        print "          P0 = %g,    P1 = %g" % (p0,p1)

        print "----- ",pfname
        print "PEPOCH ",mjd
        print "F0 ", f0
        print "F1 ", f1

    return mjd,f0,f0err,f1,f1err
예제 #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
예제 #10
0
파일: polycos.py 프로젝트: pscholz/presto
def create_polycos(parfn, telescope_id, center_freq, start_mjd, end_mjd, \
                    max_hour_angle=None, span=SPAN_DEFAULT, \
                    numcoeffs=NUMCOEFFS_DEFAULT, keep_file=False):
    """Create polycos object from a parfile.
        Inputs:
            parfn: parfile's filename, or a parfile object.
            telescope_id: The TEMPO 1-character telescope identifier.
            center_freq: The observation's center frequencies in MHz.
            start_mjd: MJD on which the polycos should start.
            end_mjd: MJD until the polycos should extend.
            max_hour_angle: The maximum hour angle as expected by tempo.
                (Default: Use default value chosen for given telescope).
            span: Span of each set of polycos in min.
                (Default: 60 min).
            numcoeffs: Number of coefficients to use.
                (Default: 12).
            keep_file: If true do not delete polyco.dat file.
                (Default: delete polyco.dat file).

        Output:
            new_polycos: a polycos object.
    """
    if type(parfn)==types.StringType:
        # assume parfn is a filename
        par = parfile.psr_par(parfn)
    else:
        # assume par is already a parfile.psr_par object
        par = parfn
   
    if max_hour_angle is None:
        telescope_name = id_to_telescope[telescope_id]
        max_hour_angle = telescope_to_maxha[telescope_name]
    
    tzfile = open("tz.in", "w")
    # Default parameters for prediction mode
    tzfile.write("%s %d %d %d %0.5f\n" % (telescope_id, max_hour_angle, \
                            SPAN_DEFAULT, NUMCOEFFS_DEFAULT, center_freq))
    # TEMPO ignores lines 2 and 3 in tz.in file
    tzfile.write("\n\n")
    if hasattr(par, "PSR"):
        psrname = par.PSR
    else:
        psrname = par.PSRJ
    tzfile.write("%s %d %d %d %0.5f\n" % (psrname, SPAN_DEFAULT, \
                        NUMCOEFFS_DEFAULT, max_hour_angle, center_freq)) 
    tzfile.close()
    tempo = subprocess.Popen("tempo -z -f %s" % par.FILE, shell=True, \
                        stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
                        stderr=subprocess.PIPE)
    (out, err) = tempo.communicate("%d %d\n" % (start_mjd, end_mjd))
    if err:
        raise TempoError("The following error message was encountered " \
                        "when running TEMPO to generate polycos from " \
                        "the input parfile (%s):\n\n%s\n" % (parfn, err))
    new_polycos = polycos(psrname, filenm='polyco.dat')
    # Remove files created by us and by TEMPO
    os.remove("tz.in")
    if not keep_file:
        os.remove("polyco.dat")
    return new_polycos
예제 #11
0
 def __init__(self, parfilenm):
     self.par = parfile.psr_par(parfilenm)
     if not hasattr(self.par, 'BINARY'):
         print "'%s' doesn't contain parameters for a binary pulsar!"
         return None
     self.PBsec = self.par.PB*SECPERDAY
     self.T0 = self.par.T0
예제 #12
0
def create_polycos(parfn, telescope_id, center_freq, start_mjd, end_mjd, \
                    max_hour_angle=None, span=SPAN_DEFAULT, \
                    numcoeffs=NUMCOEFFS_DEFAULT, keep_file=False):
    """Create polycos object from a parfile.
        Inputs:
            parfn: parfile's filename, or a parfile object.
            telescope_id: The TEMPO 1-character telescope identifier.
            center_freq: The observation's center frequencies in MHz.
            start_mjd: MJD on which the polycos should start.
            end_mjd: MJD until the polycos should extend.
            max_hour_angle: The maximum hour angle as expected by tempo.
                (Default: Use default value chosen for given telescope).
            span: Span of each set of polycos in min.
                (Default: 60 min).
            numcoeffs: Number of coefficients to use.
                (Default: 12).
            keep_file: If true do not delete polyco.dat file.
                (Default: delete polyco.dat file).

        Output:
            new_polycos: a polycos object.
    """
    if type(parfn) == types.StringType:
        # assume parfn is a filename
        par = parfile.psr_par(parfn)
    else:
        # assume par is already a parfile.psr_par object
        par = parfn

    if max_hour_angle is None:
        telescope_name = id_to_telescope[telescope_id]
        max_hour_angle = telescope_to_maxha[telescope_name]

    tzfile = open("tz.in", "w")
    # Default parameters for prediction mode
    tzfile.write("%s %d %d %d %0.5f\n" % (telescope_id, max_hour_angle, \
                            SPAN_DEFAULT, NUMCOEFFS_DEFAULT, center_freq))
    # TEMPO ignores lines 2 and 3 in tz.in file
    tzfile.write("\n\n")
    if hasattr(par, "PSR"):
        psrname = par.PSR
    else:
        psrname = par.PSRJ
    tzfile.write("%s %d %d %d %0.5f\n" % (psrname, SPAN_DEFAULT, \
                        NUMCOEFFS_DEFAULT, max_hour_angle, center_freq))
    tzfile.close()
    tempo = subprocess.Popen("tempo -z -f %s" % par.FILE, shell=True, \
                        stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
                        stderr=subprocess.PIPE)
    (out, err) = tempo.communicate("%d %d\n" % (start_mjd, end_mjd))
    if err:
        raise TempoError("The following error message was encountered " \
                        "when running TEMPO to generate polycos from " \
                        "the input parfile (%s):\n\n%s\n" % (parfn, err))
    new_polycos = polycos(psrname, filenm='polyco.dat')
    # Remove files created by us and by TEMPO
    os.remove("tz.in")
    if not keep_file:
        os.remove("polyco.dat")
    return new_polycos
예제 #13
0
 def __init__(self, parfilenm, leap=True):
     self.par = parfile.psr_par(parfilenm)
     if not hasattr(self.par, 'BINARY'):
         print "'%s' doesn't contain parameters for a binary pulsar!"
         return None
     self.PBsec = self.par.PB * SECPERDAY
     self.T0 = self.par.T0
     self.leap = leap
     self.leap_MJDs = np.r_[41499., 41683., 42048., 42413., 42778., 43144.,
                            43509., 43874., 44239., 44786., 45151., 45516.,
                            46247., 47161., 47892., 48257., 48804., 49169.,
                            49534., 50083., 50630., 51179., 53736., 54832.,
                            56109., 57204.]
예제 #14
0
파일: fitorb.py 프로젝트: JiangDong/presto
def read_par(pfname, f1errmax=999.0):
    pf = parfile.psr_par(pfname)
    # Try to see how many freq derivs we have
    fs = [pf.F0]
    for ii in range(1, 20):  # hopefully 20 is an upper limit!
        attrib = "F%d" % ii
        if hasattr(pf, attrib):
            fs.append(getattr(pf, attrib))
        else:
            break
    epoch = pf.PEPOCH
    Tobs = (pf.FINISH - pf.START) * 86400.0
    return epoch, Tobs, fs
예제 #15
0
파일: fitorb.py 프로젝트: zpleunis/presto
def read_par(pfname, f1errmax=999.0):
    pf = parfile.psr_par(pfname)
    # Try to see how many freq derivs we have
    fs = [pf.F0]
    for ii in range(1, 20):  # hopefully 20 is an upper limit!
        attrib = "F%d" % ii
        if hasattr(pf, attrib):
            fs.append(getattr(pf, attrib))
        else:
            break
    epoch = pf.PEPOCH
    Tobs = (pf.FINISH - pf.START) * 86400.0
    return epoch, Tobs, fs
예제 #16
0
def read_par(pfname, f1errmax=999.0):
    pf = parfile.psr_par(pfname)
    f0 = pf.F0
    p0 = pf.P0
    try:
        f0err = pf.F0_ERR
    except:
        f0err = 2.0e-5
    if not isfinite(f0err):
        f0err = 3.0e-5
    f1 = pf.F1
    try:
        p1 = pf.P1
    except:
        p1 = 0.0
    try:
        f1err = pf.F1_ERR
    except:
        f1err = 10.0e-8
    mjd = pf.PEPOCH
    if (verbose):
        #        print "%6s: %.4f F0 %10.9g +/- %8.03g   F1 %10.5g +/- %8.03g" % (pfname,mjd,f0,f0err,f1,f1err)
        print("%.4f %10.9g %8.3g  %10.5g %8.3g" % (mjd, f0, f0err, f1, f1err),
              end=' ')
        if (f1err > f1errmax):
            print(" * Ignored *")
        else:
            print()


#        print "          P0 = %g,    P1 = %g" % (p0,p1)

        print("----- ", pfname)
        print("PEPOCH ", mjd)
        print("F0 ", f0)
        print("F1 ", f1)

    return mjd, f0, f0err, f1, f1err
예제 #17
0
파일: tem.py 프로젝트: smearedink/tempy
    def __init__(self, freqbands):
        """Read TEMPO results (resid2.tmp, tempo.lis, timfile and parfiles)
            freqbands is a list of frequency pairs to display.
        """
        # Open tempo.lis. Parse it and find input .tim and .par files.
        # Also find output .par file.
        inputfiles_re = re.compile(
            r"Input data from (.*\.tim.*),  Parameters from (.*\.par.*)")
        outputfile_re = re.compile(r"Assumed parameters -- PSR (.*)$")
        tempolisfile = open("tempo.lis")
        intimfn, inparfn, outparfn = None, None, None
        for line in tempolisfile:
            match = inputfiles_re.search(line)
            if match:
                intimfn = match.group(1).strip()
                inparfn = match.group(2).strip()
            else:
                match = outputfile_re.search(line)
                if match:
                    outparfn = "%s.par" % match.group(1).strip()
            if (intimfn != None) and (inparfn != None) and (outparfn != None):
                # Found what we're looking for no need to continue parsing the file
                break
        tempolisfile.close()

        self.phase_wraps = {}
        #self.jump_ranges = []

        tim = tempy_io.TOAfile.from_tim_file(intimfn)
        #tim_ordered_index = np.argsort(tim.TOAs)

        # if there are phase wraps in the tim file, we want to include those
        # in the intial plot
        for tim_wrap_pos in tim.phase_wraps:
            #wrap_index = tim_ordered_index[tim_wrap_index]
            wrap_index = tim.get_nTOAs(tim_wrap_pos[0]) + tim_wrap_pos[1]
            self.phase_wraps[wrap_index] = \
              tim.phase_wraps[tim_wrap_pos]

        # if there are jumps in the tim file, we want to include those in the
        # initial plot
        self.jump_ranges = tim.get_jump_ranges()
        #self.ordered_jump_ranges = tim.get_jump_ranges(chronological=True)

        # Record filename
        self.inparfn = inparfn
        self.outparfn = outparfn
        self.intimfn = intimfn

        # Read parfiles
        self.inpar = par.psr_par(inparfn)
        self.outpar = par.psr_par(outparfn)

        # Read residuals
        r = residuals.read_residuals()

        self.max_TOA = r.bary_TOA.max()
        self.min_TOA = r.bary_TOA.min()

        self.ordered_index = np.argsort(r.bary_TOA)
        self.ordered_MJDs = r.bary_TOA[self.ordered_index]
        timfile_index = np.arange(r.numTOAs)

        if freqbands is None:
            self.freqbands = find_freq_clusters(r.bary_freq)
        else:
            self.freqbands = freqbands
        self.residuals = {}
        for lo, hi in self.freqbands:
            indices = (r.bary_freq >= lo) & (r.bary_freq < hi)
            self.residuals[get_freq_label(lo, hi)] = \
                 Resids(r.bary_TOA[indices], r.bary_freq[indices],
                        np.arange(r.numTOAs)[indices],
                        #ordered_index[indices],
                        r.orbit_phs[indices],
                        r.postfit_phs[indices], r.postfit_sec[indices],
                        r.prefit_phs[indices], r.prefit_sec[indices],
                        r.uncertainty[indices], r.weight[indices],
                        self.inpar, self.outpar)
예제 #18
0
                    help="choose subintegration number",
                    default='5')
args = parser.parse_args()

# Open pfds.

pfdtype = '*.pfd'
pfds = glob.glob(pfdtype)
pfds.sort()

# Basic Labeling

pulsar = args.name
timingfolder = '/opt/pulsar/puma/config/timing/'
timingpar = timingfolder + '{}.par'.format(pulsar)
pulsarpar = parfile.psr_par(timingpar)
scoord = pulsarpar.RAJ + pulsarpar.DECJ

for pfd in pfds:
    subprocess.call([
        'psredit', '-c', 'coord=' + scoord, '-c', 'name=' + pulsar, '-m', pfd
    ])
    subprocess.call([
        'psredit', '-c', 'obs:projid=PuMA', '-c', 'be:name=Ettus-SDR', '-m',
        pfd
    ])

# Choose a given template named 'pulsar.pfd.std'
usingtemplate = timingfolder + '{}.pfd.std'.format(pulsar)

예제 #19
0
from astropy import log

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description="Use PINT to compute H-test and plot Phaseogram from a Fermi FT1 event file.")
    parser.add_argument("eventfile",help="Fermi event FITS file name.  Should be GEOCENTERED.")
    parser.add_argument("parfile",help="par file to construct model from")
    parser.add_argument("weightcol",help="Column name for event weights (or 'CALC' to compute them)")
    parser.add_argument("--maxMJD",help="Maximum MJD to include in analysis", default=None)
    parser.add_argument("--outfile",help="Output figure file name (default=None)", default=None)
    parser.add_argument("--planets",help="Use planetary Shapiro delay in calculations (default=False)", default=False, action="store_true")
    parser.add_argument("--ephem",help="Planetary ephemeris to use (default=DE421)", default="DE421")
    args = parser.parse_args()

    pf = psr_par(args.parfile)

    # Read event file and return list of TOA objects
    tl  = load_Fermi_TOAs(args.eventfile, weightcolumn=args.weightcol,
                          targetcoord=SkyCoord(pf.RAJ,pf.DECJ,unit=(u.hourangle,u.degree),frame='icrs'))

    # Discard events outside of MJD range    
    if args.maxMJD is not None:
        tlnew = []
        print("pre len : ",len(tl))
        maxT = Time(float(args.maxMJD),format='mjd')
        print("maxT : ",maxT)
        for tt in tl:
            if tt.mjd < maxT:
                tlnew.append(tt)
        tl=tlnew
예제 #20
0
def generateObservingPlan(session,startAt,endAt,minTimePerSource=2200.0, tslew = 600.0):
    lastRise = startAt
    radecs = {}
    riseSet = {}
    riseSetList = []
    parfiles = []
    for source,parfile,band in session:
        if radecs.has_key(parfile):
            continue
        parfiles.append(parfile)
        par = psr_par(parfile)
        try:
            ra = par.RAJ
            dec = par.DECJ
        except:
            try:
                ra = par.RA
                dec = par.DEC
            except:
                raise Exception( "Error reading RA/DEC from parfile.")
            
        rh,rm,rs = map(float,ra.split(':'))
        dd,dm,ds = map(float,dec.split(':'))
        radeg = astro_utils.hms_to_rad(rh,rm,rs)*astro_utils.RADTODEG
        decdeg = dd + dm/60.0 + ds/3600.0
        radecs[parfile] = (radeg,decdeg)
        
        ts = np.arange(lastRise-2*3600,lastRise+5*3600,60.0) 
        zas = np.array([astro_utils.radec_to_azza(radeg,decdeg,epochToMJD(x),scope="ARECIBO")[1] for x in ts])
        #print zas[0],zas[-1]
        upTimes = ts[(zas<zaLimit)]
        keyHole = ts[(zas<2.0)]
        if len(keyHole):
            print "Warning:",parfile,"is in the key hole from",time.ctime(keyHole[0]),"to",time.ctime(keyHole[1])
        riseT,setT = (upTimes[0],upTimes[-1])
        riseSet[parfile] = riseT,setT
        lastRise = upTimes[0]
        riseSetList.append((riseT,setT))
        print "%10s: Rise %s  Set %s Up %.1f min." % (source[:10],time.ctime(riseT),time.ctime(setT), (setT-riseT)/60.)
    first = riseSetList[0]
    if first[0]< startAt:
        first = (startAt,first[1])
        begin = startAt
    else:
        begin = first[0]
    riseSetList[0] = first
    last = riseSetList[-1]
    if last[1]>endAt:
        last = (last[0],endAt)
    riseSetList[-1] = last
    ss,fv = optimizeSchedule(riseSetList, minTimePerSource = minTimePerSource)
    startTimes = ss[::2]
    stopTimes = ss[1::2]
    sourceEndTimes = dict(zip(parfiles,stopTimes))
    sourceStartTimes = dict(zip(parfiles,startTimes))
    nscans = {}
    for source,parfile,band in session:
        if nscans.has_key(parfile):
            nscans[parfile] += 1
        else:
            nscans[parfile] = 1
    
    scanEndTimes = []
    scanStart = begin
    lastpar = None
    
    for source,parfile,band in session:
        sourceEnd = sourceEndTimes[parfile]
        sourceStart = sourceStartTimes[parfile]
        if sourceStart < begin:
            sourceStart = begin
        timePerScan = (sourceEnd-sourceStart-tslew)/nscans[parfile]
        if lastpar == parfile:
            #we're on the same source
            scanEnd = scanStart + timePerScan
        else:
            #switching sources so add extra time for slewing
            scanEnd = sourceStart + timePerScan + tslew
        scanEndTimes.append(scanEnd)
        scanStart = scanEnd
        lastpar = parfile
    return riseSetList,startTimes,stopTimes,scanEndTimes
예제 #21
0
#!/usr/bin/env python

"""
Given a parfile and an epoch compute the frequency and
its uncertainty at a requested epoch.
"""
import sys
import numpy as np
import parfile
import psr_utils

print sys.argv

par = parfile.psr_par(sys.argv[1])

for epoch in sys.argv[2:]:
    epoch = float(epoch)
    interval_seconds = (epoch - par.PEPOCH)*psr_utils.SECPERDAY 
    f = par.F0 + interval_seconds*par.F1
    ferr = np.sqrt(par.F0_ERR**2+interval_seconds**2*par.F1_ERR**2)
    print "MJD: %f\n\tf: %0.10f\n\t+- %0.12f" % (epoch, f, ferr)

예제 #22
0
파일: fitorb.py 프로젝트: zpleunis/presto
def parse_cmd_line(args):
    """
    Parse command line argumentss
    
    Input
    -----
       args - a list of command line aruments and values
       
    Output
    ------
       user-supplied values for the given arguments
    """

    # create a list of valid command line arguments
    valid_args = ["-p", "-pb", "-x", "-T0", "-e", "-w", "-par", "-nofit", "-o"]

    if len(args) == 0:
        print_usage()
        exit(0)

    for arg in args:
        # check to make sure all arguments are valid
        if (arg.startswith("-")) and (arg not in valid_args) and \
               not arg.strip("-").replace(".","").isdigit():
            print "ERROR: Unknown arg %s" % arg
            print_usage()
            exit(0)

    # go through the given arguments and store user-supplied values
    try:
        const_params = args.pop(args.index("-nofit") + 1)
        args.remove("-nofit")
    except ValueError:
        const_params = ""
        pass

    if "-par" in args:
        try:
            par_file_name = args.pop(args.index("-par") + 1)
            args.remove("-par")
            par = parfile.psr_par(par_file_name)
            p = par.P0
            pb_days = par.PB
            x = par.A1
            T0 = par.T0
            e = par.E
            w = par.OM
        except IOError:
            print "ERROR: %s not found\n" % par_file_name
            exit(0)
        except AttributeError:
            print "ERROR: %s does not appear to be a valid binary .par file\n" \
                  %par_file_name
            exit(0)
    else:
        try:
            p = float(args.pop(args.index("-p") + 1))
            args.remove("-p")
        except ValueError:
            print "ERROR: You must specify a spin period\n"
            exit(0)

        try:
            pb_days = float(args.pop(args.index("-pb") + 1))
            args.remove("-pb")
        except ValueError:
            print "ERROR: You must specify an orbital period\n"
            exit(0)

        try:
            x = float(args.pop(args.index("-x") + 1))
            args.remove("-x")
        except ValueError:
            print "ERROR: You must specify a projected semi-major axis\n"
            exit(0)

        try:
            T0 = float(args.pop(args.index("-T0") + 1))
            args.remove("-T0")
        except ValueError:
            print "ERROR: You must specify a time of periastron passage\n"
            exit(0)

        try:
            e = float(args.pop(args.index("-e") + 1))
            args.remove("-e")
        except ValueError:
            print "WARNING: Orbital eccentricity not specified, assuming e = 0\n"
            e = 0.0
            const_params = const_params + ",e"
            pass

        try:
            w = float(args.pop(args.index("-w") + 1))
            args.remove("-w")
        except ValueError:
            print "WARNING: Longitude of periastron not specified, assuming w = 0\n"
            w = 0.0
            const_params = const_params + ",w"
            pass

    try:
        out_file_root = args.pop(args.index("-o") + 1)
        args.remove("-o")
    except ValueError:
        out_file_root = "fitorb"
        pass

    in_files = args

    return p, pb_days, x, T0, e, w, const_params, out_file_root, in_files
예제 #23
0
파일: fitorb.py 프로젝트: JiangDong/presto
def parse_cmd_line(args):
    """
    Parse command line argumentss
    
    Input
    -----
       args - a list of command line aruments and values
       
    Output
    ------
       user-supplied values for the given arguments
    """

    # create a list of valid command line arguments
    valid_args = ["-p", "-pb", "-x", "-T0", "-e", "-w", "-par", "-nofit", "-o"]

    if len(args) == 0:
        print_usage()
        exit(0)

    for arg in args:
        # check to make sure all arguments are valid
        if (arg.startswith("-")) and (arg not in valid_args) and not arg.strip("-").replace(".", "").isdigit():
            print "ERROR: Unknown arg %s" % arg
            print_usage()
            exit(0)

    # go through the given arguments and store user-supplied values
    try:
        const_params = args.pop(args.index("-nofit") + 1)
        args.remove("-nofit")
    except ValueError:
        const_params = ""
        pass

    if "-par" in args:
        try:
            par_file_name = args.pop(args.index("-par") + 1)
            args.remove("-par")
            par = parfile.psr_par(par_file_name)
            p = par.P0
            pb_days = par.PB
            x = par.A1
            T0 = par.T0
            e = par.E
            w = par.OM
        except IOError:
            print "ERROR: %s not found\n" % par_file_name
            exit(0)
        except AttributeError:
            print "ERROR: %s does not appear to be a valid binary .par file\n" % par_file_name
            exit(0)
    else:
        try:
            p = float(args.pop(args.index("-p") + 1))
            args.remove("-p")
        except ValueError:
            print "ERROR: You must specify a spin period\n"
            exit(0)

        try:
            pb_days = float(args.pop(args.index("-pb") + 1))
            args.remove("-pb")
        except ValueError:
            print "ERROR: You must specify an orbital period\n"
            exit(0)

        try:
            x = float(args.pop(args.index("-x") + 1))
            args.remove("-x")
        except ValueError:
            print "ERROR: You must specify a projected semi-major axis\n"
            exit(0)

        try:
            T0 = float(args.pop(args.index("-T0") + 1))
            args.remove("-T0")
        except ValueError:
            print "ERROR: You must specify a time of periastron passage\n"
            exit(0)

        try:
            e = float(args.pop(args.index("-e") + 1))
            args.remove("-e")
        except ValueError:
            print "WARNING: Orbital eccentricity not specified, assuming e = 0\n"
            e = 0.0
            const_params = const_params + ",e"
            pass

        try:
            w = float(args.pop(args.index("-w") + 1))
            args.remove("-w")
        except ValueError:
            print "WARNING: Longitude of periastron not specified, assuming w = 0\n"
            w = 0.0
            const_params = const_params + ",w"
            pass

    try:
        out_file_root = args.pop(args.index("-o") + 1)
        args.remove("-o")
    except ValueError:
        out_file_root = "fitorb"
        pass

    in_files = args

    return p, pb_days, x, T0, e, w, const_params, out_file_root, in_files
예제 #24
0
                        help="Maximum MJD to include in analysis",
                        default=None)
    parser.add_argument("--outfile",
                        help="Output figure file name (default=None)",
                        default=None)
    parser.add_argument(
        "--planets",
        help="Use planetary Shapiro delay in calculations (default=False)",
        default=False,
        action="store_true")
    parser.add_argument("--ephem",
                        help="Planetary ephemeris to use (default=DE421)",
                        default="DE421")
    args = parser.parse_args()

    pf = psr_par(args.parfile)

    # Read event file and return list of TOA objects
    tl = load_Fermi_TOAs(args.eventfile,
                         weightcolumn=args.weightcol,
                         targetcoord=SkyCoord(pf.RAJ,
                                              pf.DECJ,
                                              unit=(u.hourangle, u.degree),
                                              frame='icrs'))

    # Discard events outside of MJD range
    if args.maxMJD is not None:
        tlnew = []
        print("pre len : ", len(tl))
        maxT = Time(float(args.maxMJD), format='mjd')
        print("maxT : ", maxT)
예제 #25
0
# Relevant filenames
parfile_name = 'fake.par'
outputfile_name = 'fake.fits'

# Create the Archive instance.
# This is kind of a weird hack, if we create a PSRFITS
# Archive directly, some header info does not get filled
# in.  If we instead create an ASP archive, it will automatically
# be (correctly) converted to PSRFITS when it is unloaded...
arch = psrchive.Archive_new_Archive("ASP")
arch.resize(nsub, npol, nchan, nbin)

# Get/set some parameters from the par file.  If you don't have
# Presto parfile package installed, can replace this with hard-coded
# (or whatever) values.
par = parfile.psr_par(parfile_name)
arch.set_source(par.PSR)
arch.set_dispersion_measure(par.DM)
# Dec needs to have a sign for the following sky_coord call
if (par.DECJ[0] != '+' and par.DECJ[0] != '-'):
    par.DECJ = "+" + par.DECJ
arch.set_coordinates(psrchive.sky_coord(par.RAJ + par.DECJ))

# Set some other stuff
arch.set_centre_frequency(freq)
arch.set_bandwidth(bw)
arch.set_telescope('1')
if npol == 4:
    arch.set_state('Coherence')  # Could also do 'Stokes' here

# Fill in some integration attributes
예제 #26
0
# Relevant filenames
parfile_name = 'fake.par'
outputfile_name = 'fake.fits'

# Create the Archive instance.
# This is kind of a weird hack, if we create a PSRFITS
# Archive directly, some header info does not get filled
# in.  If we instead create an ASP archive, it will automatically
# be (correctly) converted to PSRFITS when it is unloaded...
arch = psrchive.Archive_new_Archive("ASP")
arch.resize(nsub,npol,nchan,nbin)

# Get/set some parameters from the par file.  If you don't have
# Presto parfile package installed, can replace this with hard-coded 
# (or whatever) values.
par = parfile.psr_par(parfile_name)
arch.set_source(par.PSR)
arch.set_dispersion_measure(par.DM)
# Dec needs to have a sign for the following sky_coord call
if (par.DECJ[0] != '+' and par.DECJ[0] != '-'):
    par.DECJ = "+" + par.DECJ
arch.set_coordinates(psrchive.sky_coord(par.RAJ + par.DECJ))

# Set some other stuff
arch.set_centre_frequency(freq)
arch.set_bandwidth(bw)
arch.set_telescope('1')
if npol==4:
    arch.set_state('Coherence') # Could also do 'Stokes' here

# Fill in some integration attributes
예제 #27
0
#!/usr/bin/env python
"""
Given a parfile and an epoch compute the frequency and
its uncertainty at a requested epoch.
"""
import sys
import numpy as np
import parfile
import psr_utils

print sys.argv

par = parfile.psr_par(sys.argv[1])

for epoch in sys.argv[2:]:
    epoch = float(epoch)
    interval_seconds = (epoch - par.PEPOCH) * psr_utils.SECPERDAY
    f = par.F0 + interval_seconds * par.F1
    ferr = np.sqrt(par.F0_ERR**2 + interval_seconds**2 * par.F1_ERR**2)
    print "MJD: %f\n\tf: %0.10f\n\t+- %0.12f" % (epoch, f, ferr)
예제 #28
0
파일: puma_toa.py 프로젝트: Gui-Gan/puma
import glob
import os
import shutil
import parfile

# Open pfds.

pfdtype = '*.pfd'
pfds = glob.glob(pfdtype)
pfds.sort()

# Basic Labeling

pardest = './../timing/'
greppar = glob.glob(pardest+'*.par')
pulsarpar= parfile.psr_par(greppar[0])
pulsar= pulsarpar.PSRJ
scoord = pulsarpar.RAJ+pulsarpar.DECJ


for pfd in pfds:
    subprocess.check_call(['psredit','-c',
	'coord='+scoord,'-c',
	'name='+pulsar,
	'-m',pfd])
    subprocess.check_call(['psredit','-c',
	'obs:projid=PuMA','-c',
	'be:name=Ettus-SDR',
	'-m',pfd])

# Choose a given template named 'pulsar.pfd.std'
예제 #29
0
파일: tem.py 프로젝트: chitrangpatel/tempy
    def __init__(self, freqbands):
        """Read TEMPO results (resid2.tmp, tempo.lis, timfile and parfiles)
            freqbands is a list of frequency pairs to display.
        """
        # Open tempo.lis. Parse it and find input .tim and .par files.
        # Also find output .par file.
        inputfiles_re = re.compile(r"Input data from (.*\.tim.*),  Parameters from (.*\.par.*)")
        outputfile_re = re.compile(r"Assumed parameters -- PSR (.*)$")
        tempolisfile = open("tempo.lis")
        intimfn, inparfn, outparfn = None, None, None
        for line in tempolisfile:
            match = inputfiles_re.search(line)
            if match:
                intimfn = match.group(1).strip()
                inparfn = match.group(2).strip()
            else:
                match = outputfile_re.search(line)
                if match:
                    outparfn = "%s.par" % match.group(1).strip()
            if (intimfn != None) and (inparfn != None) and (outparfn != None):
                # Found what we're looking for no need to continue parsing the file
                break
        tempolisfile.close()

        self.phase_wraps = {}
        self.jump_ranges = []

        tim = tempy_io.TOAset.from_tim_file(intimfn)
        tim_ordered_index = np.argsort(tim.TOAs)

        # if there are phase wraps in the tim file, we want to include those
        # in the intial plot
        for tim_wrap_index in tim.phase_wraps:
            wrap_index = tim_ordered_index[tim_wrap_index]
            self.phase_wraps[wrap_index] = \
              tim.phase_wraps[tim_wrap_index]

        # if there are jumps in the tim file, we want to include those in the
        # initial plot
        for tim_jstart,tim_jend in tim.jump_ranges:
            jstart = tim_ordered_index[tim_jstart]
            jend = tim_ordered_index[tim_jend]
            self.jump_ranges.append((jstart, jend))

        # Record filename
        self.inparfn = inparfn
        self.outparfn = outparfn
        self.intimfn = intimfn

        # Read parfiles
        self.inpar = par.psr_par(inparfn)
        self.outpar = par.psr_par(outparfn)

        # Read residuals
        r = residuals.read_residuals()

        self.max_TOA = r.bary_TOA.max()
        self.min_TOA = r.bary_TOA.min()

        ordered_index = np.argsort(r.bary_TOA)
        self.ordered_MJDs = r.bary_TOA[ordered_index]

        if freqbands is None:
            self.freqbands = find_freq_clusters(r.bary_freq)
        else:
            self.freqbands = freqbands
        self.residuals = {}
        for lo,hi in self.freqbands:
            indices = (r.bary_freq>=lo) & (r.bary_freq<hi)
            self.residuals[get_freq_label(lo, hi)] = \
                 Resids(r.bary_TOA[indices], r.bary_freq[indices],
                        #np.arange(r.numTOAs)[indices],
                        ordered_index[indices],
                        r.orbit_phs[indices],
                        r.postfit_phs[indices], r.postfit_sec[indices],
                        r.prefit_phs[indices], r.prefit_sec[indices],
                        r.uncertainty[indices], r.weight[indices],
                        self.inpar, self.outpar)