Beispiel #1
0
    def deneme(self):
        xspec.AllData.clear()
        xspec.Fit.statMethod = str(self.statistic)
        xspec.Fit.query = "yes"

        os.chdir(self.path)

        xspec.AllData("1:1 {} 2:2 {} 3:3 {} 4:4 {}".format(self.spectrum_files["mos1"],
                                                           self.spectrum_files["mos2"],
                                                           self.spectrum_files["pn"],
                                                           self.spectrum_files["rass"]))

        self.spec_mos1 = xspec.AllData(1)
        self.spec_mos1.ignore(self.energy_range["mos1"])

        self.spec_mos2 = xspec.AllData(2)
        self.spec_mos2.ignore(self.energy_range["mos2"])

        xspec.AllModels += "apec+gau+gau"

        MyModel.set_model(xspec.AllModels)
        MyModel.camera["mos1"].show()
        print(MyModel.camera["mos2"].componentNames)
        print(dir(MyModel.camera["mos2"].apec))

        mos1 = Epic("mos1")
def grid_fe_k_flux(base_nH=1, base_fe=1, out=None):
    """Make a grid """

    # Make it shut up
    xs.Xset.chatter = 9

    # Ensure "standard" normalization
    snr = xs.AllModels(1, 'snr_src')
    snr.tbnew_gas.nH = base_nH
    snr.vnei.Fe = base_fe
    snr.vnei.norm = 1

    # Temporarily unshutup to affirm baseline parameters
    xs.Xset.chatter = 10
    snr.show()
    xs.Xset.chatter = 9

    # First compute flux w/ "standard" norm (effectively, fix mass & distance)
    range_Tau = np.logspace(9, 13, 100)  # Spans 1e9 to 1e13
    range_kT  = np.logspace(-1, 1, 100)  # Spans 0.1 to 10 keV

    # Outputs
    erg_fluxes  = np.zeros((len(range_Tau), len(range_kT)))
    phot_fluxes = np.zeros((len(range_Tau), len(range_kT)))

    # Time: ~50 minutes for 100x100 pts (1e9 to 1e13 s cm^{-3}, 0.1 to 10 keV)
    # for only one spectrum (0087940201 MOS merged)
    for i in range(len(range_Tau)):

        print "Tau = {:g}".format(range_Tau[i]), datetime.now()
        snr.vnei.Tau = range_Tau[i]

        for j in range(len(range_kT)):

            if j % 5 == 0:
                print "  kT = {:g} ...".format(range_kT[j])
            snr.vnei.kT = range_kT[j]

            snr.vnei.Fe = 0
            xs.AllModels.calcFlux("6 7")

            continuum_erg  = xs.AllData(1).flux[0]
            continuum_phot = xs.AllData(1).flux[3]

            snr.vnei.Fe = base_fe
            xs.AllModels.calcFlux("6 7")

            erg_fluxes[i,j]  = (xs.AllData(1).flux[0] - continuum_erg) / snr.constant.factor.values[0]
            phot_fluxes[i,j] = (xs.AllData(1).flux[3] - continuum_phot) / snr.constant.factor.values[0]

    # Reset
    xs.Xset.chatter = 10

    if out is None:
        out = "fe-k_flux_data/grid_nH{:g}_fe{:g}.npz".format(base_nH * 1e22, base_fe)

    np.savez(out, Tau=range_Tau, kT=range_kT, erg_fluxes=erg_fluxes,
             phot_fluxes=phot_fluxes)
def Roughfit(obsname,
             Sourcename,
             obs_suffix='xwtw2po_cl_seporb.pha',
             NH=1.0,
             PL=2,
             kT=0.5,
             outfile='Roughfit.spec',
             PLOT=True):
    '''Given the observation number file of an
    observation, the Sourcename, and the name
    of an output file, this will preform a
    rough spectral fit to get a handle on the
    sources flux.'''
    spec = obsname + '/sw' + obsname + obs_suffix
    fits = pyfits.open(spec)
    xspec.AllData(spec)
    xspec.AllData.ignore("bad")
    xspec.AllData.ignore("**-0.5 10.0-**")
    model = xspec.Model("tbabs(po+bb)")
    errorstr = '1.6 2 3 4 5'
    model.TBabs.nH = NH
    model.TBabs.nH.frozen = True
    model.powerlaw.PhoIndex.values = [PL, 0.01, -3.0, -2.0, 9.0, 10.0]
    model.bbody.kT.values = [kT, 0.01, 0.0001, 0.01, 100.0, 200.0]
    xspec.Fit.query = 'yes'
    xspec.Fit.perform()
    xspec.Fit.perform()
    xspec.Plot.xAxis = "keV"
    xspec.Plot.device = "/xw"
    xspec.Plot("data", "resid")
    xspec.Plot()
    xspec.Fit.error(errorstr)
    try:
        xspec.AllModels.calcFlux("0.5 10. err 1000 90")
    except (RuntimeError, TypeError, NameError, 'Flux Command Error'):
        pass
    outf = open(outfile + '.spec', 'w')
    nH = xspec.AllModels(1)(1)
    outf.write('# nH: %f (%f - %f)\tChisq: %f\tDOF: %f\n' %
               (nH.values[0], nH.error[0], nH.error[1], xspec.Fit.statistic,
                xspec.Fit.dof))
    outf.write(
        '# obsid\tflux\tflux_low\tflux_high\tgamma\tgamma_low\tgamma_high\tkT\tkT_low\tkT_high\tPLnorm/kTnorm\n'
    )

    flux = xspec.AllData(1).flux
    output = '%s\t%E\t%E\t%E\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n' %\
             ( spec, flux[0], flux[1], flux[2],xspec.AllModels(1)(2).values[0],
             xspec.AllModels(1)(2).error[0], xspec.AllModels(1)(2).error[1], xspec.AllModels(1)(4).values[0],
             xspec.AllModels(1)(4).error[0], xspec.AllModels(1)(4).error[1],
             xspec.AllModels(1)(3).values[0]/xspec.AllModels(1)(5).values[0] )

    outf.write(output)
    outf.close()
    xspec.AllData.clear()
    xspec.AllModels.clear()
Beispiel #4
0
def fit_dict():
    """Construct serializable dict of current XSPEC fit information

    Hierarchy: fit -> spectrum -> model
    (yes, there will be considerable redundancy where multiple spectra are
    fitted to a single model)

    Input: none
    Output: dict of fit information
        fitted models
    """
    fdict = {}
    fdict['dof'] = xs.Fit.dof
    fdict['method'] = xs.Fit.method  # fitting algorithm

    # Use my own naming for the fit/test statistic methods & values
    fdict[
        'fitStatMethod'] = xs.Fit.statMethod  # "type of fit statistic in use"
    fdict[
        'testStatMethod'] = xs.Fit.statTest  # "type of test statistic in use"
    fdict['fitStat'] = xs.Fit.statistic  # fit statistic value
    fdict['testStat'] = xs.Fit.testStatistic  # test statistic value

    for x in range(xs.AllData.nSpectra):
        idx = x + 1  # Convert to XSPEC's 1-based numbering
        fdict[idx] = spectrum_dict(xs.AllData(idx))

    return fdict
Beispiel #5
0
def load_spec(spec_number, spec_path, background=None, default_dir=None):
    """
    More robust spectrum load (wrapper for PyXSPEC methods)

    Args:
        number: XSPEC spectrum number (1-based)
        spec_path: filename of spectrum
        background: (optional) filename of background spectrum, to be subtracted
        default_dir: (optional) if spectrum PHA arf/rmf/bkg are not found,
            XSPEC will hang, so provide correct directory if needed
    Returns:
        newly created xspec.Spectrum instance
    """
    old_wd = os.getcwd()
    if default_dir is not None:
        os.chdir(default_dir)

    xs.AllData("{n}:{n} {fname}".format(n=spec_number, fname=spec_path))
    spec = xs.AllData(spec_number)
    if background is not None:
        spec.background = background
    os.chdir(old_wd)

    return spec
Beispiel #6
0
def xspec_flux(x):

    Temperature, z_, ind_file, El_, Eh_, Z_ = x

    L_factor, norm, abundance = 1e44, 1.0, Z_
    E_norm = [El_, Eh_]

    xspec.Model("apec")
    m1 = xspec.AllModels(1)
    m1.setPars(Temperature, abundance, z_, norm)

    filename = mydirectory+"/parameter_files/xspec/" + str(ind_file) + ".fak"
    fs1 = xspec.FakeitSettings(response, ancillary, fileName = filename,  \
                                exposure = 100000.0)
    xspec.AllData.fakeit(1,fs1,applyStats=False, noWrite = True)

    spec1 = xspec.AllData(1)
    xspec.AllModels.setEnergies(".01 100. 1000 log")

    xspec.AllModels.calcLumin("%f %f %f" %(E_norm[0],E_norm[1],z_))
    L = spec1.lumin[0]
    xspec.AllModels.calcFlux("%f %f" %(E_norm[0],E_norm[1]))
    F = spec1.flux[0]

    new_norm = L_factor / (L * 1e44)
    m1.setPars({4:new_norm})

    xspec.AllModels.calcLumin("%f %f %f" %(E_norm[0],E_norm[1],z_))
    L_new = spec1.lumin[0]
    xspec.AllModels.calcFlux("%f %f" %(E_norm[0],E_norm[1]))
    F_new = spec1.flux[0]

    spec1.ignore("**-%f %f-**" %(E_norm[0],E_norm[1]))
    rate = spec1.rate[3]

    xspec.AllData.clear()

    return [F_new, rate]
Beispiel #7
0
    def deneme(self):
        xspec.AllData.clear()
        xspec.Fit.statMethod = str(self.statistic)
        xspec.Fit.query = "yes"

        os.chdir(self.path)

        xspec.AllData("1:1 {} 2:2 {} 3:3 {} 4:4 {}".format(
            self.spectrum_files["mos1"], self.spectrum_files["mos2"],
            self.spectrum_files["pn"], self.spectrum_files["rass"]))

        self.spec_mos1 = xspec.AllData(1)
        self.spec_mos1.ignore(self.energy_range["mos1"])

        self.spec_mos2 = xspec.AllData(2)
        self.spec_mos2.ignore(self.energy_range["mos2"])

        xspec.AllModels += "apec+gau+gau"

        self.m1 = xspec.AllModels(1)
        self.m2 = xspec.AllModels(2)
        self.m3 = xspec.AllModels(3)
        self.m4 = xspec.AllModels(4)

        m1_apec1 = Apec(1, 3, 0.3, 0.233)
        m1_gau1 = Gaussian(1, 1.48)
        m1_gau2 = Gaussian(1, 1.74)

        m2_apec1 = Apec(1, 3, 0.3, 0.233)
        m2_gau1 = Gaussian(1, 1.48)
        m2_gau2 = Gaussian(1, 1.74)

        m3_apec1 = Apec(1, 3, 0.3, 0.233)
        m3_gau1 = Gaussian(1, 1.48)
        m3_gau2 = Gaussian(1, 1.74)

        m4_apec1 = Apec(1, 3, 0.3, 0.233)
        m4_gau1 = Gaussian(1, 1.48)
        m4_gau2 = Gaussian(1, 1.74)

        m1_comp1 = self.m1.apec
        m1_comp2 = self.m1.gaussian
        m1_comp3 = self.m1.gaussian_3

        m2_comp1 = self.m2.apec
        m2_comp2 = self.m2.gaussian
        m2_comp3 = self.m2.gaussian_3

        m3_comp1 = self.m3.apec
        m3_comp2 = self.m3.gaussian
        m3_comp3 = self.m3.gaussian_3

        m4_comp1 = self.m4.apec
        m4_comp2 = self.m4.gaussian
        m4_comp3 = self.m4.gaussian_3

        Apec.set_params(m1_comp1, m1_apec1)
        Gaussian.set_params(m1_comp2, m1_gau1)
        Gaussian.set_params(m1_comp3, m1_gau2)

        Apec.set_params(m2_comp1, m2_apec1)
        Gaussian.set_params(m2_comp2, m2_gau1)
        Gaussian.set_params(m2_comp3, m2_gau2)

        Apec.set_params(m3_comp1, m3_apec1)
        Gaussian.set_params(m3_comp2, m3_gau1)
        Gaussian.set_params(m3_comp3, m3_gau2)

        Apec.set_params(m4_comp1, m4_apec1)
        Gaussian.set_params(m4_comp2, m4_gau1)
        Gaussian.set_params(m4_comp3, m4_gau2)

        MyModel.freeze_parameter(m1_comp1.norm)
        MyModel.set_norm_zero(m4_comp1)

        xspec.AllModels.show()
Beispiel #8
0
import sys
import xspec

model = xspec.Model('powerlaw')
ero_settings = xspec.FakeitSettings(
    arf='arf01_100nmAl_200nmPI_sdtq.fits',
    response='rmf01_sdtq.fits',
    exposure=10000,
    background='bkg1000000.fak',
    fileName='test.fak',
)
xspec.AllData.fakeit(1, settings=[ero_settings])

src = xspec.AllData(1)
ilo = 1
ihi = 1024
bkgfile = src.background.fileName
arf, rmf = src.multiresponse[0].arf, src.multiresponse[0].rmf
src.background = None

# copy response to source 2
src.multiresponse[1] = rmf
src.multiresponse[1].arf = arf

# make unit response for background model:
clo = 1
src.dummyrsp(lowE=ilo,
             highE=ihi,
             nBins=ihi - ilo,
             scaleType="lin",
             chanOffset=clo,
                names=('ObsId', 'Instrument', 'Piece', 'Model', 'PhoIndex',
                       'PhoIndex_sigma', 'Alpha', 'Alpha_sigma', 'Beta',
                       'Beta_sigma', 'Flux[erg/cm2/s]', 'Flux_error_range',
                       'Luminosity[e+44erg/s]', 'Lumin_error_range',
                       'Fit_statistic'),
                dtype=('object', 'object', 'object', 'object', 'object',
                       'object', 'object', 'object', 'object', 'object',
                       'object', 'object', 'object', 'object', 'object'))
            os.chdir(f"{target_dir}/{observation}/rgs/divided_spectra")
            model_list = ['const*tbabs*zpowerlw', 'const*tbabs*zlogpar']

            for i in range(1, n_intervals + 1):

                #Load RGS1 + RGS2 data
                xspec.AllData(
                    f"1:1 sourcespecRGS1_gti{i}.fits 2:2 sourcespecRGS2_gti{i}.fits"
                )

                spectrum1 = xspec.AllData(1)
                spectrum1.background = f"bgspecRGS1_gti{i}.fits"
                spectrum1.response = f"../{pairs_respli[0][0]}"

                spectrum2 = xspec.AllData(2)
                spectrum2.background = f"bgspecRGS2_gti{i}.fits"
                spectrum2.response = f"../{pairs_respli[0][1]}"

                xspec.AllData.ignore("bad")
                xspec.AllData.ignore('**-0.331 2.001-**')

                for model in model_list:
                    m1 = xspec.Model(model)