Пример #1
0
def xpmdp(**kwargs):
    """Calculate the MDP.
    """
    logger.info('Loading the instrument response functions...')
    aeff = load_arf(kwargs['irfname'])
    modf = load_mrf(kwargs['irfname'])
    module_name = os.path.basename(kwargs['configfile']).replace('.py', '')
    ROI_MODEL = imp.load_source(module_name, kwargs['configfile']).ROI_MODEL
    logger.info(ROI_MODEL)

    # This is copied from xpobbsim and should probably be factored out.
    # Actually, this should be a method of the ROI class. TBD
    if kwargs['tstart'] < ROI_MODEL.min_validity_time():
        kwargs['tstart'] = ROI_MODEL.min_validity_time()
        logger.info('Simulation start time set to %s...' % kwargs['tstart'])
    tstop = kwargs['tstart'] + kwargs['duration']
    if tstop > ROI_MODEL.max_validity_time():
        tstop = ROI_MODEL.max_validity_time()
        logger.info('Simulation stop time set to %s...' % tstop)
    kwargs['tstop'] = tstop
    observation_time = kwargs['tstop'] - kwargs['tstart']

    # This is copied from roi.py and should probably be factored out.
    # Again, the ROI class should be able to sum the count spectra of all the
    # component and expose the result.
    sources = ROI_MODEL.values()
    if len(sources) > 1:
        abort('Multiple sources not implemented, yet.')
    source = sources[0]
    if isinstance(source, xPeriodicPointSource):
        psamples = numpy.linspace(kwargs['phasemin'], kwargs['phasemax'], 100)
        logger.info('Sampling phases: %s' % psamples)
        count_spectrum = xCountSpectrum(source.energy_spectrum,
                                        aeff,
                                        psamples,
                                        scale=observation_time)
        time_integrated_spectrum = count_spectrum.build_time_integral()
    else:
        tsamples = source.sampling_time(kwargs['tstart'], kwargs['tstop'])
        logger.info('Sampling times: %s' % tsamples)
        count_spectrum = xCountSpectrum(source.energy_spectrum, aeff, tsamples)
        time_integrated_spectrum = count_spectrum.build_time_integral()

    # Thuis should be a callable method in the binning module.
    ebinning = _make_binning(kwargs['ebinalg'], kwargs['emin'], kwargs['emax'],
                             kwargs['ebins'], kwargs['ebinning'])

    # And this might be implemented in the irf.mrf module.
    _x = time_integrated_spectrum.x
    _y = time_integrated_spectrum.y * modf(_x)
    mu_spectrum = xInterpolatedUnivariateSplineLinear(_x, _y)

    for _emin, _emax in zip(ebinning[:-1], ebinning[1:]) +\
        [(ebinning[0], ebinning[-1])]:
        num_counts = count_spectrum.num_expected_counts(emin=_emin, emax=_emax)
        mu_average = mu_spectrum.integral(_emin, _emax) / num_counts
        mdp = 4.29 / mu_average / numpy.sqrt(num_counts)
        logger.info('%.2f--%.2f keV: %d counts in %d s, mu %.3f, MDP %.2f%%' %\
                    (_emin, _emax, num_counts, observation_time, mu_average,
                     100*mdp))
Пример #2
0
 def setUpClass(cls):
     """Setup.
     """
     cls.aeff = load_arf(DEFAULT_IRF_NAME)
     cls.modf = load_mrf(DEFAULT_IRF_NAME)
     cls.generator = xAzimuthalResponseGenerator()
     cls.emin = 1.
     cls.emax = 10.
Пример #3
0
def xpmdp(**kwargs):
    """Calculate the MDP.
    """
    logger.info('Loading the instrument response functions...')
    aeff = load_arf(kwargs['irfname'])
    modf = load_mrf(kwargs['irfname'])
    module_name = os.path.basename(kwargs['configfile']).replace('.py', '')
    ROI_MODEL = imp.load_source(module_name, kwargs['configfile']).ROI_MODEL
    logger.info(ROI_MODEL)

    # This is copied from xpobbsim and should probably be factored out.
    # Actually, this should be a method of the ROI class. TBD
    if kwargs['tstart'] < ROI_MODEL.min_validity_time():
        kwargs['tstart'] = ROI_MODEL.min_validity_time()
        logger.info('Simulation start time set to %s...' % kwargs['tstart'])
    tstop = kwargs['tstart'] + kwargs['duration']
    if tstop > ROI_MODEL.max_validity_time():
        tstop = ROI_MODEL.max_validity_time()
        logger.info('Simulation stop time set to %s...' % tstop)
    kwargs['tstop'] = tstop
    observation_time = kwargs['tstop'] - kwargs['tstart']

    # This is copied from roi.py and should probably be factored out.
    # Again, the ROI class should be able to sum the count spectra of all the
    # component and expose the result.
    sources = ROI_MODEL.values()
    if len(sources) > 1:
        abort('Multiple sources not implemented, yet.')
    source = sources[0]
    if isinstance(source, xPeriodicPointSource):
        psamples = numpy.linspace(kwargs['phasemin'], kwargs['phasemax'], 100)
        logger.info('Sampling phases: %s' % psamples)
        count_spectrum = xCountSpectrum(source.energy_spectrum, aeff, psamples,
                                        scale=observation_time)
        time_integrated_spectrum = count_spectrum.build_time_integral()
    else:
        tsamples = source.sampling_time(kwargs['tstart'], kwargs['tstop'])
        logger.info('Sampling times: %s' % tsamples)
        count_spectrum = xCountSpectrum(source.energy_spectrum, aeff, tsamples)
        time_integrated_spectrum = count_spectrum.build_time_integral()

    # Thuis should be a callable method in the binning module.
    ebinning =_make_binning(kwargs['ebinalg'], kwargs['emin'], kwargs['emax'],
                            kwargs['ebins'], kwargs['ebinning'])

    # And this might be implemented in the irf.mrf module.
    _x = time_integrated_spectrum.x
    _y = time_integrated_spectrum.y*modf(_x)
    mu_spectrum = xInterpolatedUnivariateSplineLinear(_x, _y)

    for _emin, _emax in zip(ebinning[:-1], ebinning[1:]) +\
        [(ebinning[0], ebinning[-1])]:
        num_counts = count_spectrum.num_expected_counts(emin=_emin, emax=_emax)
        mu_average = mu_spectrum.integral(_emin, _emax)/num_counts
        mdp = 4.29/mu_average/numpy.sqrt(num_counts)
        logger.info('%.2f--%.2f keV: %d counts in %d s, mu %.3f, MDP %.2f%%' %\
                    (_emin, _emax, num_counts, observation_time, mu_average,
                     100*mdp))
 def setUpClass(cls):
     """Setup.
     """
     cls.irf_name = "xipe_baseline"
     cls.aeff = load_arf(cls.irf_name)
     cls.modf = load_mrf(cls.irf_name)
     cls.emin = 2.0
     cls.emax = 8.0
     cls.ebinning = numpy.linspace(cls.emin, cls.emax, 4)
     cls.ism_model = xpeInterstellarAbsorptionModel()
Пример #5
0
 def bin_(self):
     """Overloaded method.
     """
     from ximpol.irf import load_mrf
     from ximpol.irf.mrf import mdp99
     modf = load_mrf(self.event_file.irf_name())
     evt_header = self.event_file.hdu_list['PRIMARY'].header
     if self.get('mc'):
         energy = self.event_data['MC_ENERGY']
     else:
         energy = self.event_data['ENERGY']
     phi = self.event_data['PE_ANGLE']
     phi_hist, xedges, yedges = numpy.histogram2d(energy, phi,
                                                  bins=self.make_binning())
     primary_hdu = self.build_primary_hdu()
     emin, emax = xedges[:-1], xedges[1:]
     emean = []
     effmu = []
     ncounts = []
     mdp = []
     # If there's more than one bin in energy, we're also interested in all
     # the basic quantities in the entire energy range. This involves
     # extending the emin and emax arrays and summing up all the
     # phi histograms across the various energy slices.
     if len(emin) > 1:
         emin = numpy.append(emin, emin[0])
         emax = numpy.append(emax, emax[-1])
         _d1, _d2 = phi_hist.shape
         phi_hist_sum = numpy.sum(phi_hist, axis=0).reshape((1, _d2))
         phi_hist = numpy.append(phi_hist, phi_hist_sum, axis=0)
     for _emin, _emax in zip(emin, emax):
         _mask = (energy > _emin)*(energy < _emax)
         _energy = energy[_mask]
         _emean = numpy.mean(_energy)
         _effmu = modf.weighted_average(_energy)
         _ncounts = len(_energy)
         _mdp = mdp99(_effmu, _ncounts)
         emean.append(_emean)
         effmu.append(_effmu)
         ncounts.append(_ncounts)
         mdp.append(_mdp)
     data = [emin, emax, emean, effmu, ncounts, mdp, phi_hist]
     xBinTableHDUMCUBE.set_phi_spec(self.get('phibins'))
     mcube_hdu = xBinTableHDUMCUBE(data)
     mcube_hdu.setup_header(self.event_file.primary_keywords())
     gti_hdu = self.event_file.hdu_list['GTI']
     hdu_list = fits.HDUList([primary_hdu, mcube_hdu, gti_hdu])
     hdu_list.info()
     logger.info('Writing binned MCUBE data to %s...' % self.get('outfile'))
     hdu_list.writeto(self.get('outfile'), clobber=True)
     logger.info('Done.')
Пример #6
0
def xpmdp(**kwargs):
    """Calculate the MDP.
    """
    logger.info('Loading the instrument response functions...')
    aeff = load_arf(kwargs['irfname'])
    modf = load_mrf(kwargs['irfname'])
    module_name = os.path.basename(kwargs['configfile']).replace('.py', '')
    ROI_MODEL = imp.load_source(module_name, kwargs['configfile']).ROI_MODEL
    logger.info(ROI_MODEL)

    # This is copied from xpobbsim and should probably be factored out.
    # Actually, this should be a method of the ROI class. TBD
    if kwargs['tstart'] < ROI_MODEL.min_validity_time():
        kwargs['tstart'] = ROI_MODEL.min_validity_time()
        logger.info('Simulation start time set to %s...' % kwargs['tstart'])
    tstop = kwargs['tstart'] + kwargs['duration']
    if tstop > ROI_MODEL.max_validity_time():
        tstop = ROI_MODEL.max_validity_time()
        logger.info('Simulation stop time set to %s...' % tstop)
    kwargs['tstop'] = tstop

    # This is copied from roi.py and should probably be factored out.
    # Again, the ROI class should be able to sum the count spectra of all the
    # component and expose the result.
    sources = ROI_MODEL.values()
    if len(sources) > 1:
        abort('Multiple sources not implemented, yet.')
    source = sources[0]
    if isinstance(source, xPeriodicPointSource):
        observation_time = kwargs['tstop'] - kwargs['tstart']
        psamples = numpy.linspace(kwargs['phasemin'], kwargs['phasemax'], 100)
        logger.info('Sampling phases: %s' % psamples)
        count_spectrum = xCountSpectrum(source.energy_spectrum, aeff, psamples,
                                        source.column_density, source.redshift,
                                        scale_factor=observation_time)
    else:
        tsamples = source.sampling_time(kwargs['tstart'], kwargs['tstop'])
        logger.info('Sampling times: %s' % tsamples)
        count_spectrum = xCountSpectrum(source.energy_spectrum, aeff, tsamples,
                                        source.column_density, source.redshift)

    # Do the actual work.
    ebinning =_make_energy_binning(**kwargs)
    mdp_table = count_spectrum.build_mdp_table(ebinning, modf)
    logger.info(mdp_table)
    file_path = kwargs['outfile']
    if file_path is not None:
        logger.info('Writing output file path %s...' % file_path)
        open(file_path, 'w').write('%s\n\n%s' % (kwargs, mdp_table))
        logger.info('Done.')
    return mdp_table
Пример #7
0
    def test_xipe_mrf(self):
        """Test the XIPE modulation factor.

        This loads the modulation factor from the XIPE .mrf FITS file,
        then the corresponding values from the text file that the response
        functions are created from and makes sure that the two are close
        enough.
        """
        _x, _y = numpy.loadtxt(GPD_MODF_FILE_PATH, unpack=True)
        modf = load_mrf(IRF_NAME)
        _mask = _y > 0.
        _x = _x[_mask]
        _y = _y[_mask]
        _delta = abs((_y - modf(_x))/_y)
        self.assertTrue(_delta.max() < 5e-3, 'max. diff. %.9f' % _delta.max())
Пример #8
0
    def test_xipe_mrf(self):
        """Test the XIPE modulation factor.

        This loads the modulation factor from the XIPE .mrf FITS file,
        then the corresponding values from the text file that the response
        functions are created from and makes sure that the two are close
        enough.
        """
        _x, _y = numpy.loadtxt(GPD_MODF_FILE_PATH, unpack=True)
        modf = load_mrf(IRF_NAME)
        _mask = _y > 0.0
        _x = _x[_mask]
        _y = _y[_mask]
        _delta = abs((_y - modf(_x)) / _y)
        self.assertTrue(_delta.max() < 5e-3, "max. diff. %.9f" % _delta.max())
Пример #9
0
 def __init__(self, file_path):
     """Constructor.
     """
     xBinnedFileBase.__init__(self, file_path)
     self.data = self.hdu_list['MODULATION'].data
     self.emin = self.data['ENERGY_LO']
     self.emax = self.data['ENERGY_HI']
     self.emean = self.data['ENERGY_MEAN']
     self.phi_y = self.data['PHI_HIST']
     phibins = self.phi_y.shape[1]
     self.phi_binning = numpy.linspace(0, 2*numpy.pi, phibins + 1)
     self.phi_x = 0.5*(self.phi_binning[:-1] + self.phi_binning[1:])
     from ximpol.irf import load_mrf
     irf_name = self.hdu_list['PRIMARY'].header['IRFNAME']
     self.modf = load_mrf(irf_name)
     self.fit_results = []
Пример #10
0
 def __init__(self, file_path):
     """Constructor.
     """
     xBinnedFileBase.__init__(self, file_path)
     self.data = self.hdu_list['MODULATION'].data
     self.emin = self.data['ENERGY_LO']
     self.emax = self.data['ENERGY_HI']
     self.emean = self.data['ENERGY_MEAN']
     self.phi_y = self.data['PHI_HIST']
     phibins = self.phi_y.shape[1]
     self.phi_binning = numpy.linspace(0, 2 * numpy.pi, phibins + 1)
     self.phi_x = 0.5 * (self.phi_binning[:-1] + self.phi_binning[1:])
     from ximpol.irf import load_mrf
     irf_name = self.hdu_list['PRIMARY'].header['IRFNAME']
     self.modf = load_mrf(irf_name)
     self.fit_results = []
Пример #11
0
 def bin_(self):
     """Overloaded method.
     """
     from ximpol.irf import load_mrf
     from ximpol.irf.mrf import mdp99
     modf = load_mrf(self.event_file.irf_name())
     evt_header = self.event_file.hdu_list['PRIMARY'].header
     if self.get('mc'):
         energy = self.event_data['MC_ENERGY']
     else:
         energy = self.event_data['ENERGY']
     phi = self.event_data['PE_ANGLE']
     phi_hist, xedges, yedges = numpy.histogram2d(energy,
                                                  phi,
                                                  bins=self.make_binning())
     primary_hdu = self.build_primary_hdu()
     emin, emax = xedges[:-1], xedges[1:]
     emean = []
     effmu = []
     ncounts = []
     mdp = []
     for _emin, _emax in zip(emin, emax):
         _mask = (energy > _emin) * (energy < _emax)
         _energy = energy[_mask]
         _emean = numpy.mean(_energy)
         _effmu = modf.weighted_average(_energy)
         _ncounts = len(_energy)
         _mdp = mdp99(_effmu, _ncounts)
         emean.append(_emean)
         effmu.append(_effmu)
         ncounts.append(_ncounts)
         mdp.append(_mdp)
     data = [emin, emax, emean, effmu, ncounts, mdp, phi_hist]
     xBinTableHDUMCUBE.set_phi_spec(self.get('phibins'))
     mcube_hdu = xBinTableHDUMCUBE(data)
     mcube_hdu.setup_header(self.event_file.primary_keywords())
     gti_hdu = self.event_file.hdu_list['GTI']
     hdu_list = fits.HDUList([primary_hdu, mcube_hdu, gti_hdu])
     hdu_list.info()
     logger.info('Writing binned MCUBE data to %s...' % self.get('outfile'))
     hdu_list.writeto(self.get('outfile'), clobber=True)
     logger.info('Done.')
Пример #12
0
 def bin_(self):
     """Overloaded method.
     """
     from ximpol.irf import load_mrf
     from ximpol.irf.mrf import mdp99
     modf = load_mrf(self.event_file.irf_name())
     evt_header = self.event_file.hdu_list['PRIMARY'].header
     if self.get('mc'):
         energy = self.event_data['MC_ENERGY']
     else:
         energy = self.event_data['ENERGY']
     phi = self.event_data['PE_ANGLE']
     phi_hist, xedges, yedges = numpy.histogram2d(energy, phi,
                                                  bins=self.make_binning())
     primary_hdu = self.build_primary_hdu()
     emin, emax = xedges[:-1], xedges[1:]
     emean = []
     effmu = []
     ncounts = []
     mdp = []
     for _emin, _emax in zip(emin, emax):
         _mask = (energy > _emin)*(energy < _emax)
         _energy = energy[_mask]
         _emean = numpy.mean(_energy)
         _effmu = modf.weighted_average(_energy)
         _ncounts = len(_energy)
         _mdp = mdp99(_effmu, _ncounts)
         emean.append(_emean)
         effmu.append(_effmu)
         ncounts.append(_ncounts)
         mdp.append(_mdp)
     data = [emin, emax, emean, effmu, ncounts, mdp, phi_hist]
     xBinTableHDUMCUBE.set_phi_spec(self.get('phibins'))
     mcube_hdu = xBinTableHDUMCUBE(data)
     mcube_hdu.setup_header(self.event_file.primary_keywords())
     gti_hdu = self.event_file.hdu_list['GTI']
     hdu_list = fits.HDUList([primary_hdu, mcube_hdu, gti_hdu])
     hdu_list.info()
     logger.info('Writing binned MCUBE data to %s...' % self.get('outfile'))
     hdu_list.writeto(self.get('outfile'), clobber=True)
     logger.info('Done.')
Пример #13
0
def analyze():
    """
    """
    if os.path.exists(ANALYSIS_FILE_PATH):
        logger.info('%s exists, delete it if you want to recreate it.' %\
                    ANALYSIS_FILE_PATH)
        return
    modf = load_mrf('xipe_goal')
    logger.info('Opening output file %s...' % ANALYSIS_FILE_PATH)
    analysis_file = open(ANALYSIS_FILE_PATH, 'w')
    for i, (_min, _max) in enumerate(PHASE_BINNING):
        _evt_file = xEventFile(_sel_file_path(i))
        _energy = _evt_file.event_data['ENERGY']
        _phase = _evt_file.event_data['PHASE']
        exp = (polarization_degree(_energy, _phase, 0, 0)*modf(_energy)).sum()/\
              modf(_energy).sum()
        _mcube = xBinnedModulationCube(_mcube_file_path(i))
        _mcube.fit()
        _fit_results = _mcube.fit_results[-1]
        print _fit_results
        print exp
        print polarization_degree(_mcube.emean[-1], _phase, 0, 0)
        raw_input()
        _phase = 0.5*(_min + _max)
        _phase_err = 0.5*(_max - _min)
        _pol_deg = _fit_results.polarization_degree
        _pol_deg_err = _fit_results.polarization_degree_error
        _pol_angle = _fit_results.phase
        _pol_angle_err = _fit_results.phase_error
        _data = (_phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,
                 _pol_angle_err)
        _fmt = ('%.4e   ' * len(_data)).strip()
        _fmt = '%s\n' % _fmt
        _line = _fmt % _data
        analysis_file.write(_line)
    analysis_file.close()
Пример #14
0
            p_opt_min = 0.5
        if p_opt_max > 0.5:
            src = {
                "name": name,
                "flux_min": flux_min,
                "flux_max": flux_max,
                "p_opt_max": p_opt_max,
                "p_opt_min": p_opt_min,
            }
            src_list.append(src)


pl_norm_ref = int_eflux2pl_norm(FLUX_REF, E_MIN, E_MAX, PL_INDEX)
logger.info("PL normalization @ %.3e erg cm^-2 s^-1: %.3e keV^-1 cm^-2 s^-1" % (FLUX_REF, pl_norm_ref))
aeff = load_arf(DEFAULT_IRF_NAME)
modf = load_mrf(DEFAULT_IRF_NAME)
tsamples = numpy.array([0, OBS_TIME_REF])
ebinning = numpy.array([E_MIN, E_MAX])
energy_spectrum = power_law(pl_norm_ref, PL_INDEX)
count_spectrum = xCountSpectrum(energy_spectrum, aeff, tsamples)
mdp_table = count_spectrum.build_mdp_table(ebinning, modf)
mdp_ref = mdp_table.mdp_values()[-1]
logger.info("Reference MDP for %s s: %.3f" % (OBS_TIME_REF, mdp_ref))

blazar_list = parse_blazar_list(PRIORITY_ONLY)
mirror_list = [1, 3, 9, 17, 18]

numpy.random.seed(10)
_color = numpy.random.random((3, len(blazar_list)))
# numpy.random.seed(1)
# _disp = numpy.random.uniform(0.7, 2., len(blazar_list))
 def setUpClass(self):
     """Setup---here we essentially create the modulation factor.
     """
     self.measx, self.measy = numpy.loadtxt(GPD_MODF_FILE_PATH, unpack=True)
     self.modf = load_mrf(IRF_NAME)
     self.interactive = sys.flags.interactive
Пример #16
0
 def setUpClass(cls):
     """Setup---here we essentially create the modulation factor.
     """
     cls.measx, cls.measy = numpy.loadtxt(GPD_MODF_FILE_PATH, unpack=True)
     cls.modf = load_mrf(IRF_NAME)
     cls.interactive = sys.flags.interactive