def parse_spectral_model(file_name, emin=0.9, emax=11.): """Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux, _fluxerr = numpy.loadtxt(file_path, unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _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)
pl_normalization_spline = xInterpolatedUnivariateSpline(_phi, esum, k=3, **fmt) # Build the polarization angle as a function of the phase. _pol_angle = polarization_angle(0,_phi,0,0) fmt = dict(xname='Pulsar phase', yname='Polarization angle [rad]') pol_angle_spline = xInterpolatedUnivariateSpline(_phi, _pol_angle, k=1, **fmt) # Build the polarization degree as a function of the phase. _pol_degree = polarization_degree(0,_phi,0,0) fmt = dict(xname='Pulsar phase', yname='Polarization degree') pol_degree_spline = xInterpolatedUnivariateSpline(_phi, _pol_degree, k=1, **fmt) ROI_MODEL = xROIModel(254.457625, 35.3423888889) herx1_ephemeris = xEphemeris(0., 0.8064516129, 0, 0) herx1_pulsar = xPeriodicPointSource('Her X-1', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle, herx1_ephemeris) ROI_MODEL.add_source(herx1_pulsar) if __name__ == '__main__': print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt plt.figure() pl_index_spline.plot(show=False) plt.figure() pl_normalization_spline.plot(show=False) plt.figure()
# 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)
# 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)
fmt = dict(xname='Pulsar phase', yname='Polarization angle [rad]') _phi=numpy.linspace(0,1,23) _pol_angle = polarization_angle(0,_phi,0,0) pol_angle_spline = xInterpolatedUnivariateSpline(_phi, _pol_angle, k=1, **fmt) _pol_degree = polarization_degree(0,_phi,0,0) fmt = dict(xname='Pulsar phase', yname='Polarization degree') pol_degree_spline = xInterpolatedUnivariateSpline(_phi, _pol_degree, k=1, **fmt) _pol_degree_noqed = polarization_degree_noqed(0,_phi,0,0) pol_degree_spline_noqed = xInterpolatedUnivariateSpline(_phi, _pol_degree_noqed, k=1, **fmt) ROI_MODEL = xROIModel(26.59342, 61.75078) fouru_ephemeris = xEphemeris(0., 0.115088121, -2.64E-14, 0) fouru_pulsar = xPeriodicPointSource('4U 0142+61', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle, fouru_ephemeris) ROI_MODEL.add_source(fouru_pulsar) if __name__ == '__main__': print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt plt.figure() pl_index_spline.plot(show=False) plt.figure() pl_normalization_spline.plot(show=False) plt.figure()
def energy_spectrum(E, t): return spectral_model(E) def polarization_degree(E, t, ra, dec): return pol_degree(E) def polarization_angle(E, t, ra, dec): return numpy.radians(pol_angle(E)) RA = 203.973 DEC = -34.2960 ROI_MODEL = xROIModel(RA, DEC) source = xPointSource('MCG-6-30-15', RA, DEC, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(source) def display(): """Display the source model. """ print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt fig = plt.figure('Energy spectrum') spectral_model.plot(show=False, logy=True) fig = plt.figure('Polarization degree')
tave.append(_tave) fave.append(_fave) tave = numpy.log10(numpy.array(tave)) fave = numpy.log10(numpy.array(fave)) spline = xInterpolatedUnivariateSplineLinear(tave, fave) tave = numpy.linspace(tave[0], tave[-1], num_bins) fave = spline(tave) tave = numpy.power(10., tave) fave = numpy.power(10., fave) fmt = dict(xname='Time', xunits='s', yname='Energy integral flux 0.3-10 keV', yunits='erg cm$^{-2}$ s$^{-1}$') return xInterpolatedUnivariateSplineLinear(tave, fave, **fmt) ROI_MODEL = xROIModel(GRB_RA, GRB_DEC) lc_file_path = os.path.join(XIMPOL_CONFIG, 'ascii/GRB130427_Swift.dat') integral_flux_spline = parse_light_curve(lc_file_path) scale_factor = int_eflux2pl_norm(1, MIN_ENERGY, MAX_ENERGY, PL_INDEX) fmt = dict(yname='PL normalization', yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$') pl_normalization_spline = integral_flux_spline.scale(scale_factor, **fmt) """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 polarization_angle(E, t, ra, dec): return numpy.radians(pol_angle(E)) energy, flux, degree, angle = parse(file_path) flux = scale_flux(energy, flux) fmt = dict(xname='Energy', xunits='keV', yname='Flux', yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$') spectral_model = xInterpolatedUnivariateSplineLinear(energy, flux, **fmt) fmt = dict(xname='Energy', xunits='keV', yname='Polarization degree') pol_degree = xInterpolatedUnivariateSplineLinear(energy, degree, **fmt) fmt = dict(xname='Energy', xunits='keV', yname='Polarization angle', yunits='$^\\circ$') pol_angle = xInterpolatedUnivariateSplineLinear(energy, angle, **fmt) ROI_MODEL = xROIModel(RA, DEC) source = xPointSource('MCG-6-30-15', RA, DEC, energy_spectrum, polarization_degree, polarization_angle, max_validity_time=50000000.) ROI_MODEL.add_source(source) def display(): """Display the source model. """ print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt fig = plt.figure('Energy spectrum') spectral_model.plot(show=False, logy=True) fig = plt.figure('Polarization degree')
def parse_spectral_model(file_name, emin=0.5, emax=15.): """Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux = numpy.loadtxt(file_path, delimiter=',', unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _energy = _energy[_mask] _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)
"""Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux = numpy.loadtxt(file_path, delimiter=',', unpack=True) _mask = (_energy >= emin) * (_energy <= emax) _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(6.340, 64.137) #This image was taken from the Chandra webpage http://hea-www.cfa.harvard.edu/ChandraSNR/G120.1+01.4/chandra_images.cgi for the energy range 0.95 - 2.65 keV le_img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'tycho_unsmoothed_1_3_keV.fits') he_img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'tycho_4p1_6p1_keV.fits') # 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
""" return numpy.degrees(numpy.arctan(physical_radius/8000.)) def parse_spectral_model(file_name): """Parse a spectral model written by XSPEC and return the corresponding interpolated univariate spline. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) data = numpy.loadtxt(file_path, unpack=True) 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 parse_spectral_model(file_name, emin=1., emax=15.): """Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux = numpy.loadtxt(file_path, delimiter=',', unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _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(350.8664167, 58.8117778) le_img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'casa_1p5_3p0_keV.fits') he_img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'casa_4p0_6p0_keV.fits') # Read in the spectral models. 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)
def parse_spectral_model(file_name, emin=0.9, emax=11.): """Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux, _fluxerr = numpy.loadtxt(file_path, unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _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(68.4021, -13.2908) # Read in the spectral models. spectral_model_spline = parse_spectral_model('Abell_496.txt') def energy_spectrum(E, t): return spectral_model_spline(E) polarization_degree = constant(0.) polarization_angle = constant(0.) abell496 = xPointSource('Abell 496', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(abell496)
fmt = dict(xname='Energy', yname='Polarization angle [rad]') pol_angle_spline = xInterpolatedUnivariateSpline(_energy, _pol_angle, k=1, **fmt) #""" #put together the flux for the source starting from the txt file _energy, _flux = numpy.loadtxt(FLUX_FILE_PATH, unpack=True) _mask = (_energy >= MIN_ENERGY)*(_energy <= MAX_ENERGY) _energy = _energy[_mask] _flux = _flux[_mask] fmt = dict(xname='Energy', xunits='keV', yname='Flux', yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$') _energy_spectrum = xInterpolatedUnivariateSpline(_energy, _flux, **fmt) ROI_MODEL = xROIModel(GRS1915_RA, GRS1915_DEC) src = xPointSource('GRS1915_105', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(src) if __name__ == '__main__': print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt fig = plt.figure('Spectrum') _energy_spectrum.plot(show=False) fig = plt.figure('Polarization angle')
# 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 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__":
"""Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux = numpy.loadtxt(file_path, delimiter=',', unpack=True) _mask = (_energy >= emin) * (_energy <= emax) _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(350.8664167, 58.8117778) le_img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'casa_1p5_3p0_keV.fits') he_img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'casa_4p0_6p0_keV.fits') # Read in the spectral models. 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 parse_spectral_model(file_name, emin=0.5, emax=15.): """Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _binw, _flux, _fluxerr, _mod = numpy.loadtxt(file_path, unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _energy = _energy[_mask] _mod = _mod[_mask] _mod /= _energy**2. fmt = dict(xname='Energy', xunits='keV', yname='Flux', yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$') return xInterpolatedUnivariateSplineLinear(_energy, _mod, **fmt) ROI_MODEL = xROIModel(207.2521, 26.5853) # Read in the spectral models. spectral_model_spline = parse_spectral_model('Abell_1795.txt') def energy_spectrum(E, t): return spectral_model_spline(E) polarization_degree = constant(0.) polarization_angle = constant(0.) abell1795 = xPointSource('Abell 1795', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(abell1795)
fave.append(_fave) tave = numpy.log10(numpy.array(tave)) fave = numpy.log10(numpy.array(fave)) spline = xInterpolatedUnivariateSplineLinear(tave, fave) tave = numpy.linspace(tave[0], tave[-1], num_bins) fave = spline(tave) tave = numpy.power(10., tave) fave = numpy.power(10., fave) fmt = dict(xname='Time', xunits='s', yname='Energy integral flux 0.3-10 keV', yunits='erg cm$^{-2}$ s$^{-1}$') return xInterpolatedUnivariateSplineLinear(tave, fave, **fmt) ROI_MODEL = xROIModel(GRB_RA, GRB_DEC) lc_file_path = os.path.join(XIMPOL_CONFIG, 'ascii/GRB130427_Swift.dat') integral_flux_spline = parse_light_curve(lc_file_path) # This needs to be fixed---the conversion between integral energy flux # and differential flux is wrong. scale_factor = (2. - PL_INDEX)/(numpy.power(MAX_ENERGY, 2. - PL_INDEX) - \ numpy.power(MIN_ENERGY, 2. - PL_INDEX)) # Convert from erg to keV. scale_factor *= 6.242e8 fmt = dict(yname='PL normalization', yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$') pl_normalization_spline = integral_flux_spline.scale(scale_factor, **fmt) """For the polarization degree we are literally making up something that decreases with time. """ _t = integral_flux_spline.x
def polarization_angle(E, phase, ra, dec): """Return the polarization angle. """ return numpy.radians(pol_angle_spline(phase)) ephem = xEphemeris(0.0, 1.0 / GK_PER_PERIOD) """We have all the ingredients, can define the ROI. Note that, since the input XSPEC model is already including the interstellar abrosorption, we are setting the column density explicitely to 0 here. """ ROI_MODEL = xROIModel(GK_PER_RA, GK_PER_DEC) gk_per = xPeriodicPointSource( "GK Per", GK_PER_RA, GK_PER_DEC, energy_spectrum, polarization_degree, polarization_angle, ephem, column_density=0.0, redshift=0.0, ) ROI_MODEL.add_source(gk_per) if __name__ == "__main__":
def parse_spectral_model(file_name, emin=0.9, emax=11.): """Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux, _fluxerr = numpy.loadtxt(file_path, unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _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(54.6471, 9.9650) # Read in the spectral models. spectral_model_spline = parse_spectral_model('2a0335_096.txt') def energy_spectrum(E, t): return spectral_model_spline(E) polarization_degree = constant(0.) polarization_angle = constant(0.) a0335 = xPointSource('2A 0335+096', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(a0335)
def parse_spectral_model(file_name, emin=0.9, emax=11.): """Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux, _fluxerr = numpy.loadtxt(file_path, unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _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(247.1542, 39.5244) # Read in the spectral models. spectral_model_spline = parse_spectral_model('Abell_2199.txt') def energy_spectrum(E, t): return spectral_model_spline(E) polarization_degree = constant(0.) polarization_angle = constant(0.) abell2199 = xPointSource('Abell 2199', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(abell2199)
def parse_spectral_model(file_name, emin=1., emax=15.): """Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux = numpy.loadtxt(file_path, delimiter=',', unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _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(6.340, 64.137) #This image was taken from the Chandra webpage http://hea-www.cfa.harvard.edu/ChandraSNR/G120.1+01.4/chandra_images.cgi for the energy range 0.95 - 2.65 keV le_img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'tycho_unsmoothed_1_3_keV.fits') he_img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'tycho_4p1_6p1_keV.fits') # 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)
due to the absence of lines between 4 and 6 keV we're attaching the latter to the non-thermal spectrum and the former to the thermal component. The polarization map is a simple geometrical, radially-symmetric, model. """ 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 # Location of the ROI: ROI_MODEL = xROIModel(83.633083, 22.014500) # Image: img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'crab_0p3_10p0_keV.fits') # Spectrum # The idea is to have multiple extended sources, one per region. # For example to create multiple region polarization map, from the bin diurectory: #./xppolmap.py --image ../config/fits/crab_0p3_10p0_keV.fits --region ../config/fits/crab_nebula_complex.reg --output ../config/fits/crab_nebula_complex.fits ############################## base_names=['crab_nebula_complex_pmax020_reg000','crab_nebula_complex_pmax017_reg001','crab_nebula_complex_pmax010_reg002'] polarization_maps=[] for i,base_name in enumerate(base_names): energy_spectrum = power_law(9.59/len(base_names), 2.108) # This ineeds to be checked! pol_mapx_path = os.path.join(XIMPOL_CONFIG, 'fits', '%s_x.fits' % base_name)
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"]
def parse_spectral_model(file_name, emin=0.5, emax=11.): """Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux, _fluxerr = numpy.loadtxt(file_path, unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _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(10.4075, -9.3425) # Read in the spectral models. spectral_model_spline = parse_spectral_model('Abell_85.txt') 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) img_file_path = os.path.join(XIMPOL_CONFIG, 'fits', 'abell85.fits') abell85 = xExtendedSource('Abell 85', img_file_path, energy_spectrum,
def parse_spectral_model(file_name, emin=0.5, emax=11.): """Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _flux, _fluxerr = numpy.loadtxt(file_path, unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _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(239.5833, 27.2334) # Read in the spectral models. spectral_model_spline = parse_spectral_model('Abell_2142.txt') def energy_spectrum(E, t): return spectral_model_spline(E) polarization_degree = constant(0.) polarization_angle = constant(0.) abell2142 = xPointSource('Abell 2142', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(abell2142)
# 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 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)
fmt = dict(xname='Energy', yname='Polarization angle [rad]') pol_angle_spline = xInterpolatedUnivariateSpline(_energy, _pol_angle, k=1, **fmt) #""" #put together the flux for the source starting from the txt file _energy, _flux = numpy.loadtxt(FLUX_FILE_PATH, unpack=True) _mask = (_energy >= MIN_ENERGY)*(_energy <= MAX_ENERGY) _energy = _energy[_mask] _flux = _flux[_mask] fmt = dict(xname='Energy', xunits='keV', yname='Flux', yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$') _energy_spectrum = xInterpolatedUnivariateSpline(_energy, _flux, **fmt) #""" ROI_MODEL = xROIModel(CYGX1_RA, CYGX1_DEC) src = xPointSource('Cyg-X1', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(src) if __name__ == '__main__': print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt fig = plt.figure('Spectrum') _energy_spectrum.plot(show=False)
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']
"""Parse the input file with the spectral point. """ file_path = os.path.join(XIMPOL_CONFIG, 'ascii', file_name) logger.info('Parsing input file %s...' % file_path) _energy, _binw, _flux, _fluxerr, _mod, _a, _b = numpy.loadtxt(file_path, unpack=True) _mask = (_energy >= emin)*(_energy <= emax) _energy = _energy[_mask] _mod = _mod[_mask] _mod /= _energy**2. fmt = dict(xname='Energy', xunits='keV', yname='Flux', yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$') return xInterpolatedUnivariateSplineLinear(_energy, _mod, **fmt) ROI_MODEL = xROIModel(44.7371, 13.5822) # Read in the spectral models. spectral_model_spline = parse_spectral_model('Abell_401.txt') def energy_spectrum(E, t): return spectral_model_spline(E) polarization_degree = constant(0.) polarization_angle = constant(0.) abell401 = xPointSource('Abell 401', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(abell401)
#""" #put together the flux for the source starting from the txt file _energy, _flux = numpy.loadtxt(FLUX_FILE_PATH, unpack=True) _mask = (_energy >= MIN_ENERGY) * (_energy <= MAX_ENERGY) _energy = _energy[_mask] _flux = _flux[_mask] fmt = dict(xname='Energy', xunits='keV', yname='Flux', yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$') _energy_spectrum = xInterpolatedUnivariateSpline(_energy, _flux, **fmt) #""" ROI_MODEL = xROIModel(CYGX1_RA, CYGX1_DEC) src = xPointSource('Cyg-X1', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(src) if __name__ == '__main__': print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt fig = plt.figure('Spectrum') _energy_spectrum.plot(show=False) fig = plt.figure('Polarization angle') pol_angle_spline.plot(show=False) fig = plt.figure('Polarization degree') pol_degree_spline.plot(show=False)
# 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 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)