Example #1
0
def skyradec_to_det(ra, dec, teldeffile, alignfile, attfile, time):
    """
    Runs and captures the output from pointxform to work out the
      detector and sky pixel coord for the given RA, Dec

      Returns a tuple of (detx, dety, skyx, skyy)
    """

    cmd = 'pointxform fromworld=yes from=\'SKY\' to=\'DET\''
    cmd += ' x=' + str(ra)
    cmd += ' y=' + str(dec)
    cmd += ' teldeffile=' + teldeffile
    cmd += ' alignfile=' + alignfile
    cmd += ' attfile= ' + attfile
    cmd += ' time=' + str(time)

    output = execute_cmd(cmd, stdout=subprocess.PIPE)[0]

    det_result = re.compile("DET.*\[", re.M).search(output)
    sky_result = re.compile("SKY.*\[", re.M).search(output)

    if det_result and sky_result:

        det_str = (det_result.group())[3:-1].split(',')
        sky_str = (sky_result.group())[3:-1].split(',')

        detx, dety = float(det_str[0]), float(det_str[1])
        skyx, skyy = float(sky_str[0]), float(sky_str[1])

        return (detx, dety, skyx, skyy)

    else:
        return (None, None, None, None)
Example #2
0
def barycentre(infile,
               outfile,
               orbitfile,
               RA=None,
               Dec=None,
               clockfile='CALDB'):
    """
    Barycentre the observation. If not provided a RA and Dec, the RA and Dec from
      the fits header will be used.
    """
    print "Barycentreing observation...\n"

    if RA and Dec:
        cmd = 'barycorr infile=%s outfile=%s orbitfiles=%s ra=%s dec=%s clobber=yes clockfile=%s' %\
              (infile, outfile, orbitfile, RA, Dec, clockfile)
    else:
        print "No RA and Dec given. Using RA and Dec of target in fits header..."
        cmd = 'barycorr infile=%s outfile=%s orbitfiles=%s clobber=yes clockfile=%s' %\
              (infile, outfile, orbitfile, clockfile)

    execute_cmd(cmd)
Example #3
0
def add_spectra(spec_list, outroot, grouping=None):
    """
    Add pha files together. Reimplements addspec ftool.
    """

    back_tmp_spec = []
    src_tmp_spec = []
    tmp_arfs = []
    weights = []

    tstarts = []
    tstops = []
    i = 0

    for spec in spec_list:
        fits = pyfits.open(spec)
        back_fn = fits[1].header['BACKFILE']
        ancr_fn = fits[1].header['ANCRFILE']
        resp_fn = fits[1].header['RESPFILE']
        exposure = fits[1].header['EXPOSURE']
        tstarts.append(fits[1].header['TSTART'])
        tstops.append(fits[1].header['TSTOP'])
        fits.close()

        i += 1
        temp_root = 'temp_spec' + str(i)

        # copy source spectra to cwd
        tmp_spec = temp_root + '.pha'
        shutil.copy(spec, tmp_spec)
        src_tmp_spec.append(tmp_spec)

        # copy back spectra to cwd
        tmp_spec = temp_root + '.bak'
        shutil.copy(back_fn, tmp_spec)
        back_tmp_spec.append(tmp_spec)

        # copy arf file to cwd
        tmp_arf = temp_root + '.arf'
        shutil.copy(ancr_fn, tmp_arf)
        tmp_arfs.append(tmp_arf)

        weights.append(exposure)

    src_math_expr = '+'.join(src_tmp_spec)
    back_math_expr = '+'.join(back_tmp_spec)

    weights = weights / np.sum(
        weights)  # response files weighted by exposure time

    f = open('tmp_arfs.list', 'w')
    for tmp_arf, weight in zip(tmp_arfs, weights):
        print(tmp_arf, weight)
        f.write(tmp_arf + ' ' + str(weight) + '\n')
    f.close()

    cmd = "addarf @tmp_arfs.list out_ARF=%s clobber=yes" % (outroot + '.arf')
    execute_cmd(cmd)

    cmd = "mathpha expr=%s units=C outfil=temp_final_spec.bak exposure=CALC areascal='%%' backscal='%%' ncomment=0 clobber=yes" % (
        back_math_expr)
    execute_cmd(cmd)

    cmd = "mathpha expr=%s units=C outfil=temp_final_spec.pha exposure=CALC areascal='%%' backscal='%%' ncomment=0 clobber=yes" % (
        src_math_expr)
    execute_cmd(cmd)

    #Run grppha to change the auxfile keys and to do grouping if needed
    grppha_comm = "chkey backfile %s.bak & chkey ancrfile %s.arf & chkey respfile %s"%\
                  (outroot, outroot, resp_fn)
    if grouping:
        grppha_comm += " & group min %d" % grouping
    grppha_comm += " & exit"

    cmd = "grppha infile=temp_final_spec.pha outfile=%s.pha clobber=yes comm=\"%s\""%\
          (outroot, grppha_comm)
    execute_cmd(cmd)

    shutil.copy('temp_final_spec.bak', outroot + '.bak')

    # put TSTART and TSTOP keywords into final spectrum
    out_spec_fits = pyfits.open(outroot + '.pha', mode='update')
    out_spec_fits[0].header['TSTART'] = (np.min(tstarts), 'time start')
    out_spec_fits[0].header['TSTOP'] = (np.max(tstops), 'time stop')
    out_spec_fits.close()

    for temp_fn in src_tmp_spec + back_tmp_spec + tmp_arfs:
        os.remove(temp_fn)

    os.remove('temp_final_spec.bak')
    os.remove('temp_final_spec.pha')
    os.remove('tmp_arfs.list')
Example #4
0
def extract_spectrum(outroot,infile,chan_low=None,chan_high=None,energy_low=None,energy_high=None,\
                     grouping=20,grade=None,expmap=None,source_region=None,back_region=None, \
                     offaxis_angle=None):
    """
    Extract a spectrum.
      If both the PHA channel limits and energy limits are None will extract entire band.

      Arguments:
        - outroot: root of the output files. Will attach extension depending on
                   type of output (.img, .evt, etc.)
        - infile: Input file to extract from.

      Optional Arguments:
        - chan_low, chan_high: limits of PHA channels to extract.
                               Default = None. 
        - energy_low, energy_high: energy limits in keV to extract. 
                                   Will be superceded by chan_low and chan_high.
                                   Default=None.
        - grouping: the minimum counts per bin for the spectrum.
                    Default=20
        - expmap: exposure map file to use in xrtmkarf.
                    Default=None
        - source_region: region file to use to extract source spectrum.
                    Default=None
        - back_region: region file to use to extract background spectrum.
                    Default=None
        - offaxis_angle: offaxis angle (in arcmin) of source to feed to xrtmkarf for 
                    the vignetting correction.
                    Default is to let xrtmkarf do its own calculation.

    """
    print("Extracting spectrum...\n")

    if chan_high == None or chan_low == None:
        if energy_low == None or energy_high == None:
            chan_low = 0
            chan_high = 1023
        else:
            chan_low = int(energy_low * 100.0)
            chan_high = int(energy_high * 100.0)

    if offaxis_angle:
        x, y = '-1', '-1'
    else:
        x, y = find_centroid(infile)

    if grade != None:
        outroot += '_g%s' % grade

    extract("temp_source",infile=infile, events=False, pha=True,\
                   region=source_region, chanlow=chan_low, chanhigh=chan_high,grade=grade)
    extract(outroot + "_back",infile=infile, events=False, pha=True,\
                   region=back_region, chanlow=chan_low, chanhigh=chan_high,grade=grade)

    cmd = "xrtmkarf outfile=%s_source.arf phafile=temp_source.pha psfflag=yes srcx=%s srcy=%s clobber=yes"%\
          (outroot, x, y)
    if expmap:
        cmd += " expofile=%s" % (expmap)
    if offaxis_angle:
        cmd += " offaxis=%f" % (offaxis_angle)

    xrtmkarf_out = execute_cmd(cmd, stdout=subprocess.PIPE)[0]
    print(xrtmkarf_out)

    rmf_re = re.compile("Processing \'(?P<rmf>.*)\.rmf\' CALDB file\.")
    rmf_search = rmf_re.search(xrtmkarf_out)
    if rmf_search:
        rmf = rmf_search.groupdict()['rmf'] + '.rmf'
    else:
        print("ERROR: No rmf filename found from xrtmkarf output.")

    if grade and grade != '0':
        print(
            "Grade selection not 0 or default, rmf in 'respfile' keyword may be wrong."
        )

    grppha_comm = "chkey backfile %s_back.pha & chkey ancrfile %s_source.arf & chkey respfile %s"%\
                  (outroot, outroot, rmf)
    if grouping:
        grppha_comm += " & group min %d" % grouping
    grppha_comm += " & exit"

    cmd = "grppha infile=temp_source.pha outfile=%s_source.pha clobber=yes comm=\"%s\""%\
          (outroot, grppha_comm)
    execute_cmd(cmd)

    os.remove('temp_source.pha')