Ejemplo n.º 1
0
def main():
    """Simple test code.
    """
    import os
    from ximpol.srcmodel.spectrum import power_law
    from ximpol.srcmodel.polarization import constant
    from ximpol import XIMPOL_CONFIG
    src_base_model = dict(energy_spectrum = power_law(1., 2.),
                          polarization_degree = constant(0.1),
                          polarization_angle = constant(20.),
                          column_density = 1.0e-22,
                          redshift = 0.0012,
                          identifier = 0)
    s1 = xModelComponentBase('Source 1', **src_base_model)
    print(s1)
    s2 = xPointSource('Source 2', ra=10., dec=15., **src_base_model)
    print(s2)
    _ephem = xEphemeris(10., 0.033, min_validity_time=10.,
                        max_validity_time=10000.)
    s3 = xPeriodicPointSource('Source 3', ra=10., dec=15., ephemeris=_ephem,
                              **src_base_model)
    print(s3)
    s4 = xUniformDisk('Source 4', ra=10., dec=15., radius=0.01,
                      **src_base_model)
    print(s4)
    s5 = xGaussianDisk('Source 5', ra=10., dec=15., sigma=0.01,
                       **src_base_model)
    print(s5)
    img_file_path = os.path.join(XIMPOL_CONFIG, 'fits',
                                 'crab_0p3_10p0_keV.fits')
    s6 = xExtendedSource('Source 6', img_file_path, **src_base_model)
    print(s6)
Ejemplo n.º 2
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import numpy

from ximpol.srcmodel.roi import xPointSource, xROIModel
from ximpol.srcmodel.spectrum import power_law
from ximpol.srcmodel.polarization import constant

ROI_MODEL = xROIModel(10., 10.)

energy_spectrum1 = power_law(10., 2.)
polarization_degree1 = constant(1.0)
polarization_angle1 = constant(numpy.radians(65.))
src1 = xPointSource('Point source 1', 9.9750, 9.9833, energy_spectrum1,
                    polarization_degree1, polarization_angle1)

energy_spectrum2 = power_law(15., 3.)
polarization_degree2 = constant(0.0)
polarization_angle2 = constant(numpy.radians(0))
src2 = xPointSource('Point source 2', 10., 10., energy_spectrum2,
                    polarization_degree2, polarization_angle2)

ROI_MODEL.add_sources(src1, src2)

if __name__ == '__main__':
    print(ROI_MODEL)
Ejemplo n.º 3
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import numpy
import os

from ximpol.srcmodel.roi import xExtendedSource, xROIModel
from ximpol.srcmodel.spectrum import power_law
from ximpol.srcmodel.polarization import constant
from ximpol import XIMPOL_CONFIG


ROI_MODEL = xROIModel(83.633083, 22.014500)

img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'crab_0p3_10p0_keV.fits')
energy_spectrum = power_law(10., 2.)
polarization_degree = constant(0.157)
polarization_angle = constant(numpy.radians(161.1))
crab_nebula = xExtendedSource('Crab nebula', img_file_path, energy_spectrum,
                              polarization_degree, polarization_angle)

ROI_MODEL.add_source(crab_nebula)


if __name__ == '__main__':
    print(ROI_MODEL)
Ejemplo n.º 4
0
"""For the polarization degree we are literally making up something
that decreases with time.
"""
_t = integral_flux_spline.x
_p = 0.6*(1. - (_t/integral_flux_spline.xmax())**0.1)
fmt = dict(xname='Time', xunits='s', yname='Polarization degree')
pol_degree_spline = xInterpolatedUnivariateSplineLinear(_t, _p, **fmt)

def energy_spectrum(E, t):
    return pl_normalization_spline(t)*numpy.power(E, -PL_INDEX)

def polarization_degree(E, t, ra, dec):
    return pol_degree_spline(t)

polarization_angle = constant(numpy.radians(28.))

grb = xPointSource('GRB', GRB_RA, GRB_DEC, energy_spectrum, polarization_degree,
                   polarization_angle,
                   min_validity_time=integral_flux_spline.xmin(),
                   max_validity_time=integral_flux_spline.xmax())

def sampling_time(tstart, tstop):
    return numpy.logspace(numpy.log10(tstart), numpy.log10(tstop), 100)

grb.sampling_time = sampling_time


ROI_MODEL.add_source(grb)

Ejemplo n.º 5
0
#!/usr/bin/env python
#
# Copyright (C) 2015--2016, the ximpol team.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU GengReral Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import numpy
from ximpol.srcmodel.polarization import constant

POL_DEGREE = 0.5
POL_ANGLE = numpy.radians(65.)

POLARIZATION_DEGREE = constant(POL_DEGREE)
POLARIZATION_ANGLE = constant(POL_ANGLE)

if __name__ == '__main__':
    print 'Configuration file test for Chandra-to-ximpol converter.'
Ejemplo n.º 6
0
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import numpy

from ximpol.srcmodel.roi import xUniformDisk, xROIModel
from ximpol.srcmodel.spectrum import power_law
from ximpol.srcmodel.polarization import constant

ROI_MODEL = xROIModel(10., 10.)

energy_spectrum = power_law(10., 2.)
polarization_degree = constant(0.5)
polarization_angle = constant(numpy.radians(65.))
disk = xUniformDisk('disk', 10., 10., 0.01, energy_spectrum,
                    polarization_degree, polarization_angle)

ROI_MODEL.add_source(disk)

if __name__ == '__main__':
    print(ROI_MODEL)
Ejemplo n.º 7
0
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import numpy
from ximpol.srcmodel.polarization import constant

POL_DEGREE_BKG = constant(0)
POL_ANGLE_BKG = constant(numpy.radians(0))

POL_DEGREE_JET = constant(0.2)
POL_ANGLE_JET = constant(numpy.radians(70))

POL_DEGREE_CORE = constant(0)
POL_ANGLE_CORE = constant(numpy.radians(0))

POLARIZATION_DICT = {0: [POL_DEGREE_BKG, POL_ANGLE_BKG],
                     1: [POL_DEGREE_JET, POL_ANGLE_JET],
                     2: [POL_DEGREE_CORE,POL_ANGLE_CORE]}

if __name__ == '__main__':
    print 'Configuration file M87 for Chandra-to-ximpol converter.'
Ejemplo n.º 8
0
    _energy = _energy[_mask]
    _flux = _flux[_mask]
    fmt = dict(xname='Energy', xunits='keV', yname='Flux',
               yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$')
    return xInterpolatedUnivariateSplineLinear(_energy, _flux, **fmt)


ROI_MODEL = xROIModel(63.3363, 10.4764)

# Read in the spectral models.
spectral_model_spline = parse_spectral_model('Abell_478.txt')

def energy_spectrum(E, t):
    return spectral_model_spline(E)

polarization_degree = constant(0.)
polarization_angle = constant(0.)

abell478 = xPointSource('Abell 478', ROI_MODEL.ra, ROI_MODEL.dec,
                       energy_spectrum, polarization_degree, polarization_angle)

ROI_MODEL.add_source(abell478)


def display():
    """Display the source model.
    """
    from ximpol.utils.matplotlib_ import pyplot as plt
    from ximpol.srcmodel.img import xFITSImage

    print(ROI_MODEL)
Ejemplo n.º 9
0
"""
_t = integral_flux_spline.x
_p = 0.6 * (1. - (_t / integral_flux_spline.xmax())**0.1)
fmt = dict(xname='Time', xunits='s', yname='Polarization degree')
pol_degree_spline = xInterpolatedUnivariateSplineLinear(_t, _p, **fmt)


def energy_spectrum(E, t):
    return pl_normalization_spline(t) * numpy.power(E, -PL_INDEX)


def polarization_degree(E, t, ra, dec):
    return pol_degree_spline(t)


polarization_angle = constant(numpy.radians(28.))

grb = xPointSource('GRB',
                   GRB_RA,
                   GRB_DEC,
                   energy_spectrum,
                   polarization_degree,
                   polarization_angle,
                   min_validity_time=integral_flux_spline.xmin(),
                   max_validity_time=integral_flux_spline.xmax())


def sampling_time(tstart, tstop):
    return numpy.logspace(numpy.log10(tstart), numpy.log10(tstop), 100)

Ejemplo n.º 10
0
total_spectral_model = parse_spectral_model('casa_total_spectrum.csv')
nonthermal_spectral_model = parse_spectral_model(
    'casa_nonthermal_spectrum.csv')
thermal_spectral_model = total_spectral_model - nonthermal_spectral_model


def thermal_energy_spectrum(E, t):
    return thermal_spectral_model(E)


def nonthermal_energy_spectrum(E, t):
    return nonthermal_spectral_model(E)


# The thermal component is totally unpolarized.
thermal_polarization_angle = constant(0.)
thermal_polarization_degree = constant(0.)

# Read the polarization maps for the non-thermal component.
#pol_mapx_path = os.path.join(XIMPOL_CONFIG, 'fits', 'casa_50_x.fits')
pol_mapx_path = os.path.join(XIMPOL_CONFIG, 'fits', 'casa_x.fits')
#pol_mapy_path = os.path.join(XIMPOL_CONFIG, 'fits', 'casa_50_y.fits')
pol_mapy_path = os.path.join(XIMPOL_CONFIG, 'fits', 'casa_y.fits')
polarization_map = xPolarizationMap(pol_mapx_path, pol_mapy_path)


def nonthermal_polarization_angle(E, t, ra, dec):
    return polarization_map.polarization_angle(ra, dec)


def nonthermal_polarization_degree(E, t, ra, dec):
Ejemplo n.º 11
0
    _flux = _flux[_mask]
    _flux /= _energy**2.
    fmt = dict(xname='Energy', xunits='keV', yname='Flux',
               yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$')
    return xInterpolatedUnivariateSplineLinear(_energy, _flux, **fmt)


ROI_MODEL = xROIModel(10.4075, -9.3425)

# Read in the spectral models.
spectral_model_spline = parse_spectral_model('abell_85.csv')

def energy_spectrum(E, t):
    return spectral_model_spline(E)

polarization_degree = constant(0.)
polarization_angle = constant(0.)

abell85 = xPointSource('Abell 85', ROI_MODEL.ra, ROI_MODEL.dec,
                       energy_spectrum, polarization_degree, polarization_angle)

ROI_MODEL.add_source(abell85)


def display():
    """Display the source model.
    """
    from ximpol.utils.matplotlib_ import pyplot as plt
    from ximpol.srcmodel.img import xFITSImage

    print(ROI_MODEL)
Ejemplo n.º 12
0
    energy, flux = data[0], data[2]
    fmt = dict(xname='Energy', xunits='keV', yname='Flux',
               yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$')
    return xInterpolatedUnivariateSplineLinear(energy, flux, **fmt)


ROI_MODEL = xROIModel(266.8, -28.46)

spectrum_spline_b1 = parse_spectral_model('spec_model_SgrB1.txt')

def energy_spectrum_b1(E, t):
    """
    """
    return spectum_spline_b1(E)

polarization_degree_b1 = constant(0.405)
polarization_angle_b1 = constant(numpy.radians(88.3))
sgrb1 = xUniformDisk('Sgr B1', 266.75833, -28.5325, angular_radius(6.),
                     energy_spectrum_b1, polarization_degree_b1,
                     polarization_angle_b1)

spectrum_spline_b2 = parse_spectral_model('spec_model_SgrB2.txt')

def energy_spectrum_b2(E, t):
    """
    """
    return spectrum_spline_b2(E)

polarization_degree_b2 = constant(0.455)
polarization_angle_b2 = constant(numpy.radians(84.4))
sgrb2 = xUniformDisk('Sgr B2', 266.835, -28.38528, angular_radius(5.),
Ejemplo n.º 13
0
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import numpy

from ximpol.srcmodel.roi import xPointSource, xROIModel
from ximpol.srcmodel.spectrum import power_law
from ximpol.srcmodel.polarization import constant


ROI_MODEL = xROIModel(10.0, 10.0)

energy_spectrum1 = power_law(10.0, 2.0)
polarization_degree1 = constant(1.0)
polarization_angle1 = constant(numpy.radians(65.0))
src1 = xPointSource("Point source 1", 9.9750, 9.9833, energy_spectrum1, polarization_degree1, polarization_angle1)

energy_spectrum2 = power_law(15.0, 3.0)
polarization_degree2 = constant(0.0)
polarization_angle2 = constant(numpy.radians(0))
src2 = xPointSource("Point source 2", 10.0, 10.0, energy_spectrum2, polarization_degree2, polarization_angle2)

ROI_MODEL.add_sources(src1, src2)


if __name__ == "__main__":
    print(ROI_MODEL)
Ejemplo n.º 14
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import numpy
import os

from ximpol.srcmodel.roi import xExtendedSource, xROIModel
from ximpol.srcmodel.spectrum import power_law
from ximpol.srcmodel.polarization import constant
from ximpol import XIMPOL_CONFIG


ROI_MODEL = xROIModel(83.633083, 22.014500)

img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'crab_0p3_10p0_keV.fits')
energy_spectrum = power_law(9.59, 2.108)
polarization_degree = constant(0.157)
polarization_angle = constant(numpy.radians(161.1))
crab_nebula = xExtendedSource('Crab nebula', img_file_path, energy_spectrum,
                              polarization_degree, polarization_angle)

ROI_MODEL.add_source(crab_nebula)


if __name__ == '__main__':
    print(ROI_MODEL)
Ejemplo n.º 15
0
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import numpy

from ximpol.srcmodel.roi import xGaussianDisk, xROIModel
from ximpol.srcmodel.spectrum import power_law
from ximpol.srcmodel.polarization import constant

ROI_MODEL = xROIModel(10., 15.)

energy_spectrum = power_law(10., 2.)
polarization_degree = constant(0.5)
polarization_angle = constant(numpy.radians(65.))

src = xGaussianDisk('Gaussian disk', 10., 15., 0.005, energy_spectrum,
                    polarization_degree, polarization_angle)

ROI_MODEL.add_source(src)


if __name__ == '__main__':
    print(ROI_MODEL)
Ejemplo n.º 16
0
# Read in the spectral models.
#Still using the casa spectrum for now.
total_spectral_model = parse_spectral_model('casa_total_spectrum.csv')
nonthermal_spectral_model = parse_spectral_model('casa_nonthermal_spectrum.csv')
thermal_spectral_model = total_spectral_model - nonthermal_spectral_model

def thermal_energy_spectrum(E, t):
    return thermal_spectral_model(E)

def nonthermal_energy_spectrum(E, t):
    return nonthermal_spectral_model(E)


# The thermal component is totally unpolarized.

thermal_polarization_angle = constant(0.)
thermal_polarization_degree = constant(0.)

# Read the polarization maps for the non-thermal component.
pol_mapx_path = os.path.join(XIMPOL_CONFIG, 'fits', 'tycho_x.fits')
pol_mapy_path = os.path.join(XIMPOL_CONFIG, 'fits', 'tycho_y.fits')
polarization_map = xPolarizationMap(pol_mapx_path, pol_mapy_path)


def nonthermal_polarization_angle(E, t, ra, dec):
    return polarization_map.polarization_angle(ra, dec)

def nonthermal_polarization_degree(E, t, ra, dec):
    return polarization_map.polarization_degree(ra, dec)

Ejemplo n.º 17
0
def chandra2ximpol(file_path, **kwargs):
    """Make the conversion from Chandra to ximpol.
    """
    assert(file_path.endswith('.fits'))
    if kwargs['outfile'] is None:
        outfile = os.path.basename(file_path).replace('.fits','_xipe.fits')
        mkdir(XIMPOL_DATA)
        kwargs['outfile'] = os.path.join(XIMPOL_DATA, outfile)
        logger.info('Setting output file path to %s...' % kwargs['outfile'])
    if os.path.exists(kwargs['outfile']) and not kwargs['clobber']:
        logger.info('Output file %s already exists.' % kwargs['outfile'])
        logger.info('Remove the file or set "clobber = True" to overwite it.')
        return kwargs['outfile']
   
    chrono = xChrono()
    logger.info('Setting the random seed to %d...' % kwargs['seed'])
    numpy.random.seed(kwargs['seed'])   
    logger.info('Loading the instrument response functions...')
    aeff, psf, modf, edisp = load_irfs(kwargs['irfname'])   
    c_aeff_name = 'chandra_acis_%s.arf' % kwargs['acis']
    c_aeff_file = os.path.join(XIMPOL_IRF, 'fits', c_aeff_name)   
    logger.info('Reading Chandra effective area data from %s...' % c_aeff_file)    
    c_aeff = load_chandra_arf(c_aeff_file) 
    _x = aeff.x
    _y = aeff.y/c_aeff(_x)
    aeff_ratio = xInterpolatedUnivariateSplineLinear(_x, _y)
    logger.info('Loading the input FITS event file...')
    hdu_list = fits.open(file_path)
    # If configuration file is not provided we assume a non-polarized source
    if kwargs['configfile'] is None:
        logger.info('Configuration file not provided.')
        logger.info('Setting polarization angle and degree to zero...')                 
        polarization_degree = constant(0.)
        polarization_angle = constant(0.)
    else:
        logger.info('Setting up the polarization source model...')
        module_name = os.path.basename(kwargs['configfile']).replace('.py', '')
        polarization_degree = imp.load_source(module_name, 
                                    kwargs['configfile']).POLARIZATION_DEGREE
        polarization_angle = imp.load_source(module_name, 
                                    kwargs['configfile']).POLARIZATION_ANGLE
    logger.info('Done %s.' % chrono)
    
    hdr = hdu_list[1].header
    tbdata = hdu_list[1].data        
    tstart = hdr['TSTART']
    tstop = hdr['TSTOP']
    obs_time = tstop - tstart
    logger.info('Chandra observation time: %i s.' %obs_time)
    ra_pnt = hdr['RA_PNT']
    dec_pnt = hdr['DEC_PNT']
    ROI_MODEL = xROIModel(ra_pnt, dec_pnt)
    
    logger.info('Reading Chandra data...')
    col_mc_energy = tbdata['energy']*0.001 # eV -> keV
    rnd_ratio = numpy.random.random(len(col_mc_energy))
    # The condition col_mc_energy < 10. is needed to avoid to take the bunch of 
    # events with energy > 10 keV included into the Chandra photon list (we
    # actually don't know the reason).
    _mask = (rnd_ratio < aeff_ratio(col_mc_energy))*(col_mc_energy<10.)
    # This is needed for over-sample the events in case of effective area ratio
    # greater than 1.
    _mask_ratio = (rnd_ratio < (aeff_ratio(col_mc_energy)-1.))*\
                                                            (col_mc_energy<10.)
    col_mc_energy = numpy.append(col_mc_energy[_mask], 
                                                    col_mc_energy[_mask_ratio])

    col_time = numpy.append(tbdata['time'][_mask],tbdata['time'][_mask_ratio])
    col_mc_ra, col_mc_dec = _get_radec(hdr, tbdata)
    col_mc_ra = numpy.append(col_mc_ra[_mask], col_mc_ra[_mask_ratio])
    col_mc_dec = numpy.append(col_mc_dec[_mask], col_mc_dec[_mask_ratio])

    duration = kwargs['duration']
    if not numpy.isnan(duration):
        logger.info('Setting the observation time to %d s...' % duration)                             
        scale = numpy.modf(duration/obs_time)
        tstop = tstart + duration
        logger.info('Scaling counts according to observation time...')
        col_mc_energy, col_time, col_mc_ra, col_mc_dec = time_scaling(scale, 
                                col_mc_energy, col_time, col_mc_ra, col_mc_dec)
          
    logger.info('Converting from Chandra to ximpol...')
    gti_list = [(tstart, tstop)]
    event_list = xMonteCarloEventList()    
    event_list.set_column('TIME', col_time)    
    event_list.set_column('MC_ENERGY', col_mc_energy)
    col_pha = edisp.matrix.rvs(col_mc_energy)
    event_list.set_column('PHA', col_pha)
    col_energy = edisp.ebounds(col_pha)
    event_list.set_column('ENERGY',col_energy)
    event_list.set_column('MC_RA', col_mc_ra)
    event_list.set_column('MC_DEC', col_mc_dec)
    col_ra, col_dec = psf.smear(col_mc_ra, col_mc_dec)
    event_list.set_column('RA', col_ra)
    event_list.set_column('DEC', col_dec)
    pol_degree = polarization_degree(col_mc_energy, col_time, col_mc_ra,
                                                              col_mc_dec)
    pol_angle = polarization_angle(col_mc_energy, col_time, col_mc_ra,
                                                              col_mc_dec)
    col_pe_angle = modf.rvs_phi(col_mc_energy, pol_degree, pol_angle)
    event_list.set_column('PE_ANGLE', col_pe_angle)
    # Set the phase to rnd [0-1] for all non-periodic sources.
    phase=numpy.random.uniform(0,1,len(col_dec))
    event_list.set_column('PHASE', phase)   
    event_list.set_column('MC_SRC_ID', numpy.zeros(len(col_dec)))  
    logger.info('Done %s.' % chrono)
    
    simulation_info = xSimulationInfo()
    simulation_info.gti_list = gti_list
    simulation_info.roi_model = ROI_MODEL
    simulation_info.irf_name = kwargs['irfname']
    simulation_info.aeff = aeff
    simulation_info.psf = psf
    simulation_info.modf = modf
    simulation_info.edisp = edisp
    event_list.sort()
    event_list.write_fits(kwargs['outfile'], simulation_info)
    
    logger.info('All done %s!' % chrono)
    return kwargs['outfile']
Ejemplo n.º 18
0
def chandra2ximpol(file_path, **kwargs):
    """Make the conversion from Chandra to ximpol.
    """
    assert file_path.endswith(".fits")
    if kwargs["outfile"] is None:
        outfile = os.path.basename(file_path).replace(".fits", "_xipe.fits")
        mkdir(XIMPOL_DATA)
        kwargs["outfile"] = os.path.join(XIMPOL_DATA, outfile)
        logger.info("Setting output file path to %s..." % kwargs["outfile"])
    if os.path.exists(kwargs["outfile"]) and not kwargs["clobber"]:
        logger.info("Output file %s already exists." % kwargs["outfile"])
        logger.info('Remove the file or set "clobber = True" to overwite it.')
        return kwargs["outfile"]

    chrono = xChrono()
    logger.info("Setting the random seed to %d..." % kwargs["seed"])
    numpy.random.seed(kwargs["seed"])
    logger.info("Loading the instrument response functions...")
    aeff, psf, modf, edisp = load_irfs(kwargs["irfname"])
    c_aeff_name = "chandra_acis_%s.arf" % kwargs["acis"]
    c_aeff_file = os.path.join(XIMPOL_IRF, "fits", c_aeff_name)
    logger.info("Reading Chandra effective area data from %s..." % c_aeff_file)
    c_aeff = _load_chandra_arf(c_aeff_file)
    c_vign_name = "chandra_vignet.fits"
    c_vign_file = os.path.join(XIMPOL_IRF, "fits", c_vign_name)
    logger.info("Reading Chandra vignetiing data from %s..." % c_vign_file)
    c_vign = _load_chandra_vign(c_vign_file)
    aeff_ratio = _make_aeff_ratio(aeff, c_aeff, c_vign)
    logger.info("Done %s." % chrono)

    logger.info("Loading the input FITS event file...")
    hdu_list = fits.open(file_path)
    hdr = hdu_list[1].header
    tbdata = hdu_list[1].data
    tstart = hdr["TSTART"]
    tstop = hdr["TSTOP"]
    obs_time = tstop - tstart
    logger.info("Chandra observation time: %i s." % obs_time)
    ra_pnt = hdr["RA_PNT"]
    dec_pnt = hdr["DEC_PNT"]
    ROI_MODEL = xROIModel(ra_pnt, dec_pnt)

    logger.info("Reading Chandra data...")
    col_mc_energy = tbdata["energy"] * 0.001  # eV -> keV
    col_mc_ra, col_mc_dec = _get_radec(hdr, tbdata)
    ref_skyccord = SkyCoord(ra_pnt, dec_pnt, unit="deg")
    evt_skycoord = SkyCoord(col_mc_ra, col_mc_dec, unit="deg")
    separation = evt_skycoord.separation(ref_skyccord).arcmin

    logger.info("Converting from Chandra to ximpol...")
    rnd_ratio = numpy.random.random(len(col_mc_energy))
    # The condition col_mc_energy < 10. is needed to avoid to take the bunch of
    # events with energy > 10 keV included into the Chandra photon list (we
    # actually don't know the reason).
    _mask = (rnd_ratio < aeff_ratio(col_mc_energy, separation)) * (col_mc_energy < 10.0)
    # This is needed for over-sample the events in case of effective area ratio
    # greater than 1.
    _mask_ratio = (rnd_ratio < (aeff_ratio(col_mc_energy, separation) - 1.0)) * (col_mc_energy < 10.0)
    col_mc_energy = numpy.append(col_mc_energy[_mask], col_mc_energy[_mask_ratio])
    col_mc_ra = numpy.append(col_mc_ra[_mask], col_mc_ra[_mask_ratio])
    col_mc_dec = numpy.append(col_mc_dec[_mask], col_mc_dec[_mask_ratio])
    col_time = numpy.append(tbdata["time"][_mask], tbdata["time"][_mask_ratio])

    # If duration parameter is provided the counts are down- or oversampled.
    duration = kwargs["duration"]
    if not numpy.isnan(duration):
        logger.info("Setting the observation time to %d s..." % duration)
        scale = numpy.modf(duration / obs_time)
        tstop = tstart + duration
        logger.info("Scaling counts according to observation time...")
        col_mc_energy, col_time, col_mc_ra, col_mc_dec = _time_scaling(
            scale, col_mc_energy, col_time, col_mc_ra, col_mc_dec
        )

    # The Ra Dec coordinates are calculated here because they are needed in
    # source id definition (in case of kwargs['chandra']==False)
    col_ra, col_dec = psf.smear(col_mc_ra, col_mc_dec)
    # The default source id in case of no regfile and for regions not selected
    # is zero. For regions selected in the regfile the source id is determined
    # by the order of definition (starting with 1).
    logger.info("Defining source id...")
    src_id = numpy.zeros(len(col_mc_dec))
    n_reg = -1
    if kwargs["regfile"] is not None:
        regions = pyregion.open(kwargs["regfile"])
        for n_reg, region in enumerate(regions):
            if kwargs["mc"] is True:
                mask = filter_region(region, col_mc_ra, col_mc_dec)
            else:
                mask = filter_region(region, col_ra, col_dec)
            src_id[mask] = n_reg + 1

    # If configuration file is not provided we assume a non-polarized source.
    # In case of configfile with polarization model defined in different
    # regions the photoelectron distribution is generated according to them.
    if kwargs["configfile"] is None:
        logger.info("Configuration file not provided.")
        logger.info("Setting polarization angle and degree to zero...")
        polarization_degree = constant(0.0)
        polarization_angle = constant(0.0)
        pol_dict = {0: [polarization_degree, polarization_angle]}
        for k in range(1, n_reg + 2):
            pol_dict[k] = [polarization_degree, polarization_angle]
    else:
        logger.info("Setting up the polarization source model...")
        module_name = os.path.basename(kwargs["configfile"]).replace(".py", "")
        pol_dict = imp.load_source(module_name, kwargs["configfile"]).POLARIZATION_DICT
    logger.info("Generating photoelectron azimuthal distribution...")
    col_pe_angle = numpy.empty(len(col_mc_dec))
    for key, pol_list in pol_dict.items():
        _mask_src = src_id == key
        pol_degree = pol_list[0](
            col_mc_energy[_mask_src], col_time[_mask_src], col_mc_ra[_mask_src], col_mc_dec[_mask_src]
        )
        pol_angle = pol_list[1](
            col_mc_energy[_mask_src], col_time[_mask_src], col_mc_ra[_mask_src], col_mc_dec[_mask_src]
        )
        col_pe_angle[_mask_src] = modf.rvs_phi(col_mc_energy[_mask_src], pol_degree, pol_angle)

    gti_list = [(tstart, tstop)]
    event_list = xMonteCarloEventList()
    event_list.set_column("TIME", col_time)
    event_list.set_column("MC_ENERGY", col_mc_energy)
    col_pha = edisp.matrix.rvs(col_mc_energy)
    event_list.set_column("PHA", col_pha)
    col_energy = edisp.ebounds(col_pha)
    event_list.set_column("ENERGY", col_energy)
    event_list.set_column("MC_RA", col_mc_ra)
    event_list.set_column("MC_DEC", col_mc_dec)
    event_list.set_column("RA", col_ra)
    event_list.set_column("DEC", col_dec)
    event_list.set_column("MC_SRC_ID", src_id)
    event_list.set_column("PE_ANGLE", col_pe_angle)
    # Set the phase to rnd [0-1] for all non-periodic sources.
    phase = numpy.random.uniform(0, 1, len(col_dec))
    event_list.set_column("PHASE", phase)
    logger.info("Done %s." % chrono)

    simulation_info = xSimulationInfo()
    simulation_info.gti_list = gti_list
    simulation_info.roi_model = ROI_MODEL
    simulation_info.irf_name = kwargs["irfname"]
    simulation_info.aeff = aeff
    simulation_info.psf = psf
    simulation_info.modf = modf
    simulation_info.edisp = edisp
    event_list.sort()
    event_list.write_fits(kwargs["outfile"], simulation_info)

    logger.info("All done %s!" % chrono)
    return kwargs["outfile"]
Ejemplo n.º 19
0
# Copyright (C) 2015--2016, the ximpol team.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU GengReral Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import numpy
from ximpol.srcmodel.polarization import constant

POL_DEGREE = constant(0.5)
POL_ANGLE = constant(numpy.radians(65.))

""" Dictionary scheme for source polarization model:
    POLARIZATION_DICT = {source_id: [pol_degree, pol_angle]}
"""
POLARIZATION_DICT = {0: [POL_DEGREE, POL_ANGLE]}

if __name__ == '__main__':
    print 'Configuration file test for Chandra-to-ximpol converter.'
Ejemplo n.º 20
0
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import numpy

from ximpol.srcmodel.roi import xPointSource, xROIModel
from ximpol.srcmodel.spectrum import power_law
from ximpol.srcmodel.polarization import constant


ROI_MODEL = xROIModel(90., 0.)
PL_NORM = 10.
PL_INDEX = 2.0
POL_DEGREE = 0.5
POL_ANGLE = numpy.radians(65.)

energy_spectrum = power_law(PL_NORM, PL_INDEX)
polarization_degree = constant(POL_DEGREE)
polarization_angle = constant(POL_ANGLE)

src = xPointSource('Point source', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum,
                   polarization_degree, polarization_angle)

ROI_MODEL.add_source(src)


if __name__ == '__main__':
    print(ROI_MODEL)