コード例 #1
0
ファイル: grb130427_swift.py プロジェクト: lucabaldini/ximpol
 def draw_time_grid(color='blue'):
     """
     """
     times = [3600., 3600.*24., 3600.*24.*7.]
     labels = ['1 hour', '1 day', '1 week']
     for t, l in zip(times, labels):
         plt.axvline(t, linestyle='dashed', color=color)
         ymin, ymax = plt.gca().get_ylim()
         y = ymin + 1.05*(ymax - ymin)
         plt.text(t, y, l, ha='center', color=color)
コード例 #2
0
 def draw_time_grid(color='blue'):
     """
     """
     times = [3600., 3600. * 24., 3600. * 24. * 7.]
     labels = ['1 hour', '1 day', '1 week']
     for t, l in zip(times, labels):
         plt.axvline(t, linestyle='dashed', color=color)
         ymin, ymax = plt.gca().get_ylim()
         y = ymin + 1.05 * (ymax - ymin)
         plt.text(t, y, l, ha='center', color=color)
コード例 #3
0
ファイル: rmf.py プロジェクト: pabell/ximpol
 def _plot_vslice(energy, position):
     """Convenience function to plot a generic vertical slice of the
     energy dispersion.
     """
     ax = plt.subplot(2, 2, position)
     vslice = self.matrix.vslice(energy)
     vslice.plot(overlay=False, show=False)
     plt.text(0.1, 0.9, '$E = %.2f\\ \\rm{keV}$' % energy,
              transform=ax.transAxes)
     ppf = vslice.build_ppf()
     eres = 0.5*(ppf(0.8413) - ppf(0.1586))/ppf(0.5)
     plt.text(0.1, 0.85, '$\sigma_E/E = %.3f$' % eres,
              transform=ax.transAxes)
コード例 #4
0
ファイル: rmf.py プロジェクト: pabell/ximpol
 def _plot_vslice(energy, position):
     """Convenience function to plot a generic vertical slice of the
     energy dispersion.
     """
     ax = plt.subplot(2, 2, position)
     vslice = self.matrix.vslice(energy)
     vslice.plot(overlay=False, show=False)
     plt.text(0.1,
              0.9,
              '$E = %.2f\\ \\rm{keV}$' % energy,
              transform=ax.transAxes)
     ppf = vslice.build_ppf()
     eres = 0.5 * (ppf(0.8413) - ppf(0.1586)) / ppf(0.5)
     plt.text(0.1,
              0.85,
              '$\sigma_E/E = %.3f$' % eres,
              transform=ax.transAxes)
コード例 #5
0
ファイル: mrf.py プロジェクト: pabell/ximpol
 def plot(self, show=False, stat=True, text_size=15, **options):
     """Plot the fit results.
     """
     from ximpol.utils.matplotlib_ import pyplot as plt
     _x = numpy.linspace(0., 2*numpy.pi, 100)
     _y = xAzimuthalResponseGenerator.fit_function(_x, *self.popt)
     plt.plot(_x, _y, **options)
     if stat:
         posh = 0.02
         posv = 0.25
         delv = 0.07
         for text in self.latex().split(','):
             text = text.strip()
             plt.text(posh, posv, text, transform=plt.gca().transAxes,
                      fontsize=text_size)
             posv -= delv
     if show:
         plt.show()
コード例 #6
0
ファイル: mrf.py プロジェクト: lucabaldini/ximpol
 def plot(self, show=False, stat=True, text_size=15, **options):
     """Plot the fit results.
     """
     from ximpol.utils.matplotlib_ import pyplot as plt
     _x = numpy.linspace(0., 2*numpy.pi, 100)
     _y = xAzimuthalResponseGenerator.fit_function(_x, *self.popt)
     plt.plot(_x, _y, **options)
     if stat:
         posh = 0.02
         posv = 0.25
         delv = 0.07
         for text in self.latex().split(','):
             text = text.strip()
             plt.text(posh, posv, text, transform=plt.gca().transAxes,
                      fontsize=text_size)
             posv -= delv
     if show:
         plt.show()
コード例 #7
0
ファイル: binning.py プロジェクト: petarmimica/ximpol
 def plot_bin(self, i, show=True, fit=True):
     """Plot the azimuthal distribution for the i-th energy slice.
     """
     _emin = self.emin[i]
     _emax = self.emax[i]
     _emean = self.emean[i]
     label = '%.2f-%.2f $<$%.2f$>$ keV' % (_emin, _emax, _emean)
     plt.errorbar(self.phi_x, self.phi_y[i], yerr=numpy.sqrt(self.phi_y[i]),
                  fmt='o')
     if fit:
         fit_results = self.fit_bin(i)
         fit_results.plot(label=label)
    
     plt.axis([0., 2*numpy.pi, 0.0, 1.2*self.phi_y[i].max()])
     plt.xlabel('Azimuthal angle [rad]')
     plt.ylabel('Counts/bin')
     plt.text(0.02, 0.92, label, transform=plt.gca().transAxes,
              fontsize=15)
     if show:
         plt.show()
コード例 #8
0
ファイル: rmf.py プロジェクト: lucabaldini/ximpol
 def view(self, show=True):
     """Plot the energy dispersion.
     """
     from ximpol.utils.matplotlib_ import pyplot as plt
     plt.figure('Energy redistribution')
     self.matrix.plot(show=False)
     plt.figure('Energy bounds')
     self.ebounds.plot(overlay=False, show=False)
     energy = 0.5*(self.matrix.xmin() + self.matrix.xmax())
     plt.figure('Energy dispersion @ %.2f keV' % energy)
     vslice = self.matrix.vslice(energy)
     vslice.plot(overlay=False, show=False)
     plt.text(0.1, 0.9, '$E = %.2f\\ \\rm{keV}$' % energy,
              transform=plt.gca().transAxes)
     ppf = vslice.build_ppf()
     eres = 0.5*(ppf(0.8413) - ppf(0.1586))/ppf(0.5)
     plt.text(0.1, 0.85, '$\sigma_E/E = %.3f$' % eres,
              transform=plt.gca().transAxes)
     if show:
         plt.show()
コード例 #9
0
ファイル: casa_pol_map.py プロジェクト: lucabaldini/ximpol
def plot_pol_map_from_ascii():
    
    output_file = get_output_file()
    logger.info('Opening file %s for plotting...' % output_file)
    emin,emax, degree, degree_error, angle, angle_error, counts = numpy.loadtxt(output_file, delimiter=',', unpack=True)
    
        
    _ra = numpy.linspace(ra_min, ra_max, num_points)
    _dec = numpy.linspace(dec_min, dec_max, num_points)

    _ra, _dec = numpy.meshgrid(_ra, _dec)
   
    fig = plt.figure()
    for i in range(len(E_BINNING) - 1):
        sigma_array = degree[emin==E_BINNING[i]]/degree_error[emin==E_BINNING[i]]
        pol_array = degree[emin==E_BINNING[i]].reshape((num_points,num_points))
        sigma_array = sigma_array.reshape((num_points,num_points))  
        ax1 = fig.add_subplot()
        label = 'XIPE %.1d ks'%(DURATION/1000.)

        plt.contourf(_ra,_dec,pol_array)
        cbar = plt.colorbar()
        cbar.ax.set_ylabel('Polarization degree')
        
        plt.text(0.02, 0.92, label, transform=plt.gca().transAxes,
                 fontsize=20,color='w')
        plt.xlabel('RA')
        plt.ylabel('DEC')
       # fig.gca().add_artist(psf)
        plt.show()
        ax2 = fig.add_subplot()
    
        plt.contourf(_ra,_dec,sigma_array)
        cbar2 = plt.colorbar()
        cbar2.ax.set_ylabel('Sigma')
        plt.text(0.02, 0.92, label, transform=plt.gca().transAxes,
                 fontsize=20,color='w')
        plt.xlabel('RA')
        plt.ylabel('DEC')
        plt.show()
コード例 #10
0
ファイル: binning.py プロジェクト: pabell/ximpol
 def plot_bin(self, i, show=True, fit=True):
     """Plot the azimuthal distribution for the i-th energy slice.
     """
     _emin = self.emin[i]
     _emax = self.emax[i]
     _emean = self.emean[i]
     label = '%.2f-%.2f $<$%.2f$>$ keV' % (_emin, _emax, _emean)
     plt.errorbar(self.phi_x,
                  self.phi_y[i],
                  yerr=numpy.sqrt(self.phi_y[i]),
                  fmt='o')
     if fit:
         fit_results = self.fit_bin(i)
         fit_results.plot(label=label)
     view_range = 1.5 * (self.phi_y[i].max() - self.phi_y[i].min())
     view_ymin = self.phi_y[i].min() - view_range
     view_ymax = self.phi_y[i].max() + view_range
     plt.axis([0., 2 * numpy.pi, view_ymin, view_ymax])
     plt.xlabel('Azimuthal angle [rad]')
     plt.ylabel('Counts/bin')
     plt.text(0.02, 0.92, label, transform=plt.gca().transAxes, fontsize=15)
     if show:
         plt.show()
コード例 #11
0
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))

plt.figure("Average polarization degree", (11, 8))
_x = numpy.logspace(-13, -7, 100)
for obs_time in [1.0e3, 10.0e3, 100.0e3, 1.0e6]:
    _y = 100.0 * mdp_ref * numpy.sqrt(OBS_TIME_REF / obs_time * FLUX_REF / _x)
    plt.plot(_x, _y, color=GRID_COLOR, ls="dashed", lw=0.6)
    _i = 51
    if obs_time is 1.0e3:
        _x_text = _x[_i]
        _y_text = _y[_i]
    plt.text(_x_text, _y_text, "$T_{obs} =$ %d ks" % (obs_time / 1000.0), color=GRID_COLOR, rotation=-43.0, size=14)
    _x_text /= 10
plt.xscale("log")
plt.yscale("log")
plt.xlabel("Integral energy flux %.0f-%.0f keV [erg cm$^{-2}$ s$^{-1}$]" % (E_MIN, E_MAX))
plt.ylabel("MDP 99% CL [%]")

for j, blazar in enumerate(blazar_list):
    _x_max = blazar["flux_max"]
    _x_min = blazar["flux_min"]
    _y_max = blazar["p_opt_max"]
    _y_min = blazar["p_opt_min"]
    plt.plot([_x_min, _x_max, _x_max], [_y_max, _y_max, _y_min], color=_color[:, j], lw=1.5)
    _x_text = numpy.sqrt((_x_max) * (_x_min))
    if j in mirror_list:
        _y_text = 0.88 * _y_max
コード例 #12
0
    def test_power_law_stationary(self):
        """Test a time-independent power law.

        This creates a count spectrum with no time dependence, i.e., with
        only two (identical) interpolating time points on the auxiliary
        (time) axis. The power-law parameters (C and gamma) are constant

        >>> tmin = 0.
        >>> tmax = 100.
        >>> C = 1.
        >>> Gamma = 2.
        >>>
        >>> def powerlaw(E, t):
        >>>     return C*numpy.power(E, -Gamma)
        >>>
        >>> _t = numpy.linspace(tmin, tmax, 2)
        >>> count_spectrum = xCountSpectrum(powerlaw, self.aeff, _t)

        and the underlying xUnivariateAuxGenerator looks like.

        .. image:: ../figures/test_power_law_stationary_2d.png

        Then a vertical slice (i.e., an interpolated linear spline) is taken
        in the middle of the auxiliary axis

        >>> tref = 0.5*(tmin + tmax)
        >>> ref_slice = count_spectrum.slice(tref)

        and the y-values of the spline are compared with the direct product of
        the effective area and the input spectrum:

        >>> _x = self.aeff.x
        >>> _y = C*numpy.power(_x, -Gamma)*self.aeff.y

        (Note that in general the two are technically not the same thing, as
        going from the count spectrum to the slice we do interpolate in time,
        although in this particular case the interpolation is trivial).
        If everything goes well, they should be on top of each other.
        The figure below is also showing the original power-law spectrum
        multiplied by the peak effective area.

        .. image:: ../figures/test_power_law_stationary_slice.png

        """
        tmin = 0.
        tmax = 100.
        tref = 0.5*(tmin + tmax)
        C = 1.
        Gamma = 2.

        def powerlaw(E, t):
            """Function defining a time-dependent energy spectrum.
            """
            return C*numpy.power(E, -Gamma)

        _t = numpy.linspace(tmin, tmax, 2)
        count_spectrum = xCountSpectrum(powerlaw, self.aeff, _t)
        count_spectrum.plot(show=False)
        overlay_tag(color='white')
        save_current_figure('test_power_law_stationary_2d.png',
                            show=self.interactive)

        ref_slice = count_spectrum.slice(tref)
        _x = self.aeff.x
        _y = C*numpy.power(_x, -Gamma)*self.aeff.y.max()
        plt.plot(_x, _y, '-', label='Original power-law spectrum')
        _y = C*numpy.power(_x, -Gamma)*self.aeff.y
        _mask = _y > 0.
        _x = _x[_mask]
        _y = _y[_mask]
        delta = abs((_y - ref_slice(_x))/_y).max()
        self.assertTrue(delta < 1e-3, 'max deviation %.9f' % delta)
        plt.plot(_x, _y, 'o', label='Direct convolution with aeff')
        ref_slice.plot(logx=True, logy=True, show=False,
                       label='xCountSpectrum output')
        overlay_tag()
        plt.text(0.1, 0.1, 'Max. difference = %.3e' % delta,
                 transform=plt.gca().transAxes)
        plt.legend(bbox_to_anchor=(0.75, 0.5))
        plt.axis([0.6, 10, None, None])
        save_current_figure('test_power_law_stationary_slice.png',
                            show=self.interactive)
コード例 #13
0
    def test_power_law_rvs(self, num_events=1000000):
        """Test the generation of event energies from a count power-law
        spectrum convoluted with the effective area.

        This turned out to be more tricky than we anticipated. Since the
        convolution of the source spectrum with the effective area falls
        pretty quickly at high energy, there's typically very few events above
        a few keV and, as a consequence, the slope of the corresponding ppf is
        fairly steep close to one.

        .. image:: ../figures/test_power_law_rvs_vppf.png

        This implies that the ppf in each slice must be properly sampled
        close to 1 (initial tests showed, e.g., that a uniform grid with
        100 points between 0 and 1 was not enough to throw meaningful random
        numbers for a typical power-law source spectrum). This is particularly
        true for soft spectral indices---which is why we picked `Gamma = 3.`
        for this test.

        .. image:: ../figures/test_power_law_rvs_counts.png

        """
        tmin = 0.
        tmax = 100.
        tref = 0.5*(tmin + tmax)
        C = 1.
        Gamma = 3.

        def powerlaw(E, t):
            """Function defining a time-dependent energy spectrum.
            """
            return C*numpy.power(E, -Gamma)

        _t = numpy.linspace(tmin, tmax, 2)
        count_spectrum = xCountSpectrum(powerlaw, self.aeff, _t)

        count_spectrum.vppf.vslice(tref).plot(show=False, overlay=True)
        overlay_tag()
        save_current_figure('test_power_law_rvs_vppf.png',
                            show=self.interactive)

        ref_slice = count_spectrum.slice(tref)
        _time = numpy.full(num_events, tref)
        _energy = count_spectrum.rvs(_time)
        _binning = numpy.linspace(self.aeff.xmin(), self.aeff.xmax(), 100)
        obs, bins, patches = plt.hist(_energy, bins=_binning,
                                      histtype='step', label='Random energies')
        plt.yscale('log')
        # We want to overlay the reference count-spectrum slice, normalized
        # to the total number of events simulated.
        bin_width = (bins[1] - bins[0])
        scale = num_events*bin_width/ref_slice.norm()
        _x = 0.5*(bins[:-1] + bins[1:])
        _y = scale*ref_slice(_x)
        plt.plot(_x, _y, label='Underlying pdf')
        # And, for the chisquare, we do correctly integrate the slice in each
        # energy bin, rather than evaluating it at the bin center.
        exp = []
        scale = num_events/ref_slice.norm()
        for _emin, _emax in zip(bins[:-1], bins[1:]):
            exp.append(scale*ref_slice.integral(_emin, _emax))
        exp = numpy.array(exp)
        _mask = exp > 0.
        exp = exp[_mask]
        obs = obs[_mask]
        chi2 = ((exp - obs)**2/exp).sum()
        ndof = len(obs)
        chi2_min = ndof - 3*numpy.sqrt(2*ndof)
        chi2_max = ndof + 3*numpy.sqrt(2*ndof)
        self.assertTrue(chi2 > chi2_min, 'chisquare too low (%.2f/%d)' %\
                        (chi2, ndof))
        self.assertTrue(chi2 < chi2_max, 'chisquare too high (%.2f/%d)' %\
                        (chi2, ndof))
        plt.text(0.5, 0.1, '$\chi^2$/ndof = %.2f/%d' % (chi2, ndof),
                 transform=plt.gca().transAxes)
        plt.legend(bbox_to_anchor=(0.85, 0.75))
        overlay_tag()
        save_current_figure('test_power_law_rvs_counts.png',
                            show=self.interactive)
コード例 #14
0
    def test_power_law_variable(self):
        """Test a time-dependent power law.

        This creates a time-dependent count spectrum, where the two parameters
        of the underlying power law (C and Gamma) vary linearly with time, in
        opposite direction, between 1 and 2.

        >>> def C(t):
        >>>     return 1. + (t - tmin)/(tmax - tmin)
        >>>
        >>> def Gamma(t):
        >>>    return 2. - (t - tmin)/(tmax - tmin)
        >>>
        >>> def powerlaw(E, t):
        >>>    return C(t)*numpy.power(E, -Gamma(t))

        (Beware: this does not mean that you can interpolate linearly between
        the two time extremes, as both parameters vary at the same time and
        the spectral shape does not evolve linearly with time---we're sampling
        the time axis with 100 points).
        The underlying xUnivariateAuxGenerator looks like.

        .. image:: ../figures/test_power_law_variable_2d.png

        Then a vertical slice (i.e., an interpolated linear spline) is taken
        in the middle of the auxiliary axis and the y-values of the spline
        are compared with the direct product of the effective area and the
        count spectrum (evaluated at the same time). If everything goes well,
        they should be on top of each other. The figure below is also showing
        the orignal power-law spectrum multiplied by the peak effective area.

        .. image:: ../figures/test_power_law_variable_slice.png

        Finally, we do test the light-curve building by comparing it with the
        values from a direct intergration of the vertical slices on a
        fixed-spacing grid. Note that, since the normalization increases with
        time and the spectral index becomes harder, the light-curve increases
        more than linearly.

        .. image:: ../figures/test_power_law_variable_lc.png

        """
        tmin = 0.
        tmax = 100.
        tref = 0.5*(tmin + tmax)

        def C(t):
            """Time-dependent C---equals to 1 @ tmin and 2 @ tmax.
            """
            return 1. + (t - tmin)/(tmax - tmin)

        def Gamma(t):
            """Time-dependent C---equals to 2 @ tmin and 1 @ tmax.
            """
            return 2. - (t - tmin)/(tmax - tmin)

        def powerlaw(E, t):
            """Function defining a time-dependent energy spectrum.
            """
            return C(t)*numpy.power(E, -Gamma(t))

        _t = numpy.linspace(tmin, tmax, 100)
        count_spectrum = xCountSpectrum(powerlaw, self.aeff, _t)
        count_spectrum.plot(show=False)
        overlay_tag(color='white')
        save_current_figure('test_power_law_variable_2d.png',
                            show=self.interactive)

        ref_slice = count_spectrum.slice(tref)
        _x = self.aeff.x
        _y = self.aeff.y.max()*C(tref)*numpy.power(_x, -Gamma(tref))
        plt.plot(_x, _y, '-', label='Original power-law spectrum')
        _y = C(tref)*numpy.power(_x, -Gamma(tref))*self.aeff.y
        _mask = _y > 0.
        _x = _x[_mask]
        _y = _y[_mask]
        delta = abs((_y - ref_slice(_x))/_y).max()
        self.assertTrue(delta < 1e-3, 'max deviation %.9f' % delta)
        plt.plot(_x, _y, 'o', label='Direct convolution with aeff')
        ref_slice.plot(logx=True, logy=True, show=False,
                       label='xCountSpectrum output')
        overlay_tag()
        plt.text(0.1, 0.1, 'Max. difference = %.3e' % delta,
                 transform=plt.gca().transAxes)
        plt.legend(bbox_to_anchor=(0.75, 0.5))
        plt.axis([0.6, 10, None, None])
        save_current_figure('test_power_law_variable_slice.png',
                            show=self.interactive)

        _x = numpy.linspace(tmin, tmax, 33)
        _y = []
        for _xp in _x:
            _y.append(count_spectrum.slice(_xp).norm())
        _y = numpy.array(_y)
        plt.plot(_x, _y, 'o', label='Direct integral flux values')
        delta = abs((_y - count_spectrum.light_curve(_x))/_y).max()
        self.assertTrue(delta < 1e-3, 'max deviation %.9f' % delta)
        count_spectrum.light_curve.plot(show=False,
                                        label='xCountSpectrum light-curve')
        overlay_tag()
        plt.legend(bbox_to_anchor=(0.65, 0.75))
        plt.text(0.5, 0.1, 'Max. difference = %.3e' % delta,
                 transform=plt.gca().transAxes)
        save_current_figure('test_power_law_variable_lc.png',
                            show=self.interactive)
コード例 #15
0
ファイル: xipe_obs_plan.py プロジェクト: lucabaldini/ximpol
obs_plan_list = parse_obs_plan_list(PRIORITY_ONLY)
mirror_list = [5, 6, 7, 8]

numpy.random.seed(1)
_color = numpy.random.random((3, len(obs_plan_list)))
numpy.random.seed(17)
_disp = numpy.random.uniform(0.9, 1.4, len(obs_plan_list))

plt.figure('Average polarization degree', (14, 10))
_x = numpy.logspace(-13, -7, 100)
for obs_time in [1.e3, 10.e3, 100.e3, 1.e6]:
    _y = 100.* mdp_ref * numpy.sqrt(OBS_TIME_REF/obs_time * FLUX_REF/_x)
    plt.plot(_x, _y, color=GRID_COLOR, ls='dashed', lw=0.5)
    _i = 53
    plt.text(_x[_i], _y[_i], '$T_{obs} =$ %d ks' % (obs_time/1000.),
             color=GRID_COLOR, rotation=-45.)
plt.xscale('log')
plt.yscale('log')
plt.xlabel('Integral energy flux %.0f-%.0f keV [erg cm$^{-2}$ s$^{-1}$]' %\
           (E_MIN, E_MAX))
plt.ylabel('MDP 99% CL [%]')

for j, source in enumerate(obs_plan_list):
    _x = source['flux']
    _y = source['mdp']*_disp[j]
    plt.plot(_x, _y, 'o', color=_color[:,j])
    _text = source['name']
    if source['notes'] is not '':
        _text += '\n' + source['notes']
    if j in mirror_list:
        _y *= 0.8