コード例 #1
0
ファイル: spline.py プロジェクト: pabell/ximpol
    def plot(self,
             num_points=1000,
             overlay=False,
             logx=False,
             logy=False,
             scale=1.,
             offset=0.,
             show=True,
             **kwargs):
        """Plot the spline.

        Args
        ----
        num_points : int, optional
            The number of sampling points to be used to draw the spline.

        overlay : bool, optional
            If True, the original arrays passed to the spline are overlaid.

        show : bool, optional
            If True, `plt.show()` is called at the end, interrupting the flow.
        """
        from ximpol.utils.matplotlib_ import pyplot as plt
        if not logx:
            _x = numpy.linspace(self.xmin(), self.xmax(), num_points)
        else:
            _x = numpy.logspace(numpy.log10(self.xmin()),
                                numpy.log10(self.xmax()), num_points)
        _y = scale * self(_x) + offset
        if overlay:
            plt.plot(_x, _y, '-', self.x, self.y, 'o', **kwargs)
        else:
            plt.plot(_x, _y, '-', **kwargs)
        if self.xname is not None:
            plt.xlabel(self.xlabel())
        if self.yname is not None:
            plt.ylabel(self.ylabel())
        if logx:
            plt.gca().set_xscale('log')
        if logy:
            plt.gca().set_yscale('log')
        if show:
            plt.show()
コード例 #2
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)
コード例 #3
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)
コード例 #4
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()
コード例 #5
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()
コード例 #6
0
ファイル: spline.py プロジェクト: lucabaldini/ximpol
    def plot(self, num_points=1000, overlay=False, logx=False, logy=False,
             scale=1., offset=0., show=True, **kwargs):
        """Plot the spline.

        Args
        ----
        num_points : int, optional
            The number of sampling points to be used to draw the spline.

        overlay : bool, optional
            If True, the original arrays passed to the spline are overlaid.

        show : bool, optional
            If True, `plt.show()` is called at the end, interrupting the flow.
        """
        from ximpol.utils.matplotlib_ import pyplot as plt
        if not logx:
            _x = numpy.linspace(self.xmin(), self.xmax(), num_points)
        else:
            _x = numpy.logspace(numpy.log10(self.xmin()),
                                numpy.log10(self.xmax()), num_points)
        _y = scale*self(_x) + offset
        if overlay:
            plt.plot(_x, _y, '-', self.x, self.y, 'o', **kwargs)
        else:
            plt.plot(_x, _y, '-', **kwargs)
        if self.xname is not None:
            plt.xlabel(self.xlabel())
        if self.yname is not None:
            plt.ylabel(self.ylabel())
        if logx:
            plt.gca().set_xscale('log')
        if logy:
            plt.gca().set_yscale('log')
        if show:
            plt.show()
コード例 #7
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()
コード例 #8
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()
コード例 #9
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()
コード例 #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
    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)
コード例 #12
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)
コード例 #13
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)
コード例 #14
0
ファイル: grb_mdp.py プロジェクト: lucabaldini/ximpol
def main():
    """Produce some plots
    """
    # If all_mdp = True, produces: 
    # 1) the plot of the MDP for all the Swift GRBs 
    #    and a given repointing time
    # 2) the plot of the correlation between MDP for all the Swift 
    #    GRBs and a given repointing time and the integral prompt 
    #    (first 10 min) flux
    all_mdp = True
    if all_mdp == True:
        grb_list = get_all_swift_grb_names()
        t_rep = 21600
        t_obs = 100000
        promt_time = 600
        mdp_list1,mdp_list2, flux_list, t0_list = [], [], [], []
        c, good_grb = [], []
        for grb in grb_list:
            mdp = get_grb_mdp(grb,repointing=t_rep,obs_time=t_obs)
            flux, t0 = get_integral_flux(grb,delta_t=promt_time)
            if mdp is not None and flux is not None:
                mdp_list1.append(mdp*100)
                if t0 < 350:
                    if mdp*100 <= 15:
                        c.append('red')
                    else:
                        c.append('blue')
                    mdp_list2.append(mdp*100)
                    flux_list.append(flux)
                    t0_list.append(t0)
                else:
                    continue
        _mdp1 = numpy.array(mdp_list1)
        _mdp2 = numpy.array(mdp_list2)
        _flux = numpy.array(flux_list)
        _t0 = numpy.array(t0_list)
        # 1)------------------------------------------------------
        histo = plt.figure(figsize=(10, 6), dpi=80)
        bins = numpy.linspace(0, 100, 100)
        plt.title('%i GRBs, $\Delta t_{obs}=%i s,$ $t_{repoint}=%i s$'\
                  %(len(_mdp1),t_obs,t_rep))
        plt.hist(_mdp1, bins, alpha=0.5)
        plt.xlabel('2.-10. keV MDP (%)')
        plt.ylabel('Number of GRBs')
        overlay_tag()
        save_current_figure('all_grbs_MDP_histo', clear=False)
        plt.show()
        # 1.1)----------------------------------------------------
        histo = plt.figure(figsize=(10, 6), dpi=80)
        bins = numpy.linspace(0, 100, 100)
        plt.title('%i GRBs, $\Delta t_{obs}=%i s,$ $t_{repoint}=%i s$'\
                  %(len(_mdp1),t_obs,t_rep))
        (n, bins, patches) = plt.hist(_mdp1, bins, histtype='step', cumulative=True)
        plt.xlabel('2.-10. keV MDP (%)')
        plt.ylabel('Cumulative number of GRBs')
        for i in range(0,len(bins)):
            print 'MDP %.2f%%: %i GRBs'%(i,n[i])
        overlay_tag()
        save_current_figure('all_grbs_MDP_cumulative', clear=False)
        plt.show()
        # 2)------------------------------------------------------
        plt.figure(figsize=(10, 6), dpi=80)
        ax = plt.gca()
        plt.scatter(_mdp2, _flux, s=30, marker='.', color=c)
        plt.xlabel('2.-10. keV MDP (%)')
        plt.ylabel('[keV$^{-1}$ cm$^{-2}$]')
        plt.title('$\Delta t_{obs}=%i s,$ $t_{repoint}=%i s$'%(t_obs,t_rep))
        plt.xlim(1, 100)
        ax.set_yscale('log')
        ax.set_xscale('log')
        overlay_tag()
        save_current_figure('grb_MDP_prompt',clear=False)
        plt.show()
    
    # If mdp_vs_time = True Produces: 
    # 1) the plot of the MDP for a given GRB 
    #    as a function of the repointing time
    # 2) the plot of the MDP for a given GRB 
    #    as a function of the observation duration
    mdp_vs_time = False
    color_list = []
    if mdp_vs_time == True:
        grb_list = ['GRB 060729', 'GRB 080411', 'GRB 091127', 'GRB 111209A',\
                    'GRB 120711A', 'GRB 130427A', 'GRB 130505A', 'GRB 130907A',\
                    'GRB 150403A']
        #1)------------------------------------------------------
        plt.figure(figsize=(10, 6), dpi=80)
        ax = plt.gca()
        for grb in grb_list:
            c = [random.uniform(0,1),random.uniform(0,1),random.uniform(0,1)]
            color_list.append(c)
            repointing_time = numpy.logspace(2,4.8,30)
            plot_grb_mdp_vs_repoint(grb,repointing_time,show=False,color=c)
        ax.legend(loc='upper left', shadow=False, fontsize='small')
        plt.plot([21600, 21600], [0, 30], 'k--', lw=1, color='green')
        plt.plot([43200, 43200], [0, 30], 'k--', lw=1,color='green')
        ax.set_yscale('log')
        ax.set_xscale('log')
        overlay_tag()
        save_current_figure('grb_MDP_vs_repoint',clear=False)
        plt.show()
        #2)------------------------------------------------------
        plt.figure(figsize=(10, 6), dpi=80)
        ax = plt.gca()
        for i,grb in enumerate(grb_list):
            obs_time = numpy.logspace(3,5,30)
            plot_grb_mdp_vs_obstime(grb,obs_time,show=False,color=color_list[i])
        ax.legend(loc='upper right', shadow=False, fontsize='small')
        plt.plot([50000, 50000], [0, 50], 'k--', lw=1, color='green')
        ax.set_yscale('log')
        ax.set_xscale('log')
        overlay_tag(x=0.5)
        save_current_figure('grb_MDP_vs_obstime',clear=False)
        plt.show()
コード例 #15
0
ファイル: grb_swift_mdp.py プロジェクト: lucabaldini/ximpol
def main():
    """Produce some plots
    """
    # If process_grb_mdp = True, produces a fits file with all the 
    # main infos on each grb
    if process_grb_mdp == True:
        data = process_grb_list(duration=50000.)
        build_grb_fits_file(data,OUTFILE)
    
    # 1) the plot of the MDP for all the Swift GRBs
    #    and a given repointing time
    # 2) the cumulative of the previous histogram
    # 3) the plot of the correlation between MDP for all the Swift
    #    GRBs and a given repointing time and the integral prompt
    #    (first 10 min) flux

    # 1)------------------------------------------------------
    plt.figure(figsize=(10, 6), dpi=80)
    bins = numpy.linspace(0, 100, 100)
    hdulist = fits.open(OUTFILE)
    grbdata = hdulist[1].data
    _mdp = grbdata['MDP 99%']
    t_obs = '50000'
    t_rep = '21600'
    plt.title('%i GRBs, $\Delta t_{obs}=%s s,$ $t_{repoint}=%s s$'\
              %(len(_mdp),t_obs,t_rep))
    plt.hist(_mdp*100, bins, alpha=0.5)
    plt.xlabel('2.-10. keV MDP (%)')
    plt.ylabel('Number of GRBs')
    overlay_tag()
    save_current_figure('all_grbs_MDP_histo', clear=False)

    # 2)----------------------------------------------------
    plt.figure(figsize=(10, 6), dpi=80)
    plt.title('%i GRBs, $\Delta t_{obs}=%s s,$ $t_{repoint}=%s s$'\
              %(len(_mdp),t_obs,t_rep))
    (n, bins, patches) = plt.hist(_mdp*100, bins, histtype='step', \
                                  cumulative=True)
    plt.xlabel('2.-10. keV MDP (%)')
    plt.ylabel('Cumulative number of GRBs')
    for i in range(0,30):
        print 'MDP %.2f%%: %i GRBs'%(i,n[i])
    overlay_tag()
    save_current_figure('all_grbs_MDP_cumulative', clear=False)

    # 3)------------------------------------------------------
    plt.figure(figsize=(10, 6), dpi=80)
    ax = plt.gca()
    _prompt_tstart = grbdata['PROMPT_START']
    _flux = grbdata['PROMPT_FLUX']
    _good_indexes = numpy.where(_prompt_tstart>350)
    _flux = numpy.delete(_flux,_good_indexes)
    _mdp = numpy.delete(_mdp,_good_indexes)
    plt.scatter(_mdp*100, _flux, s=30, marker='.', color='blue')
    plt.xlabel('2.-10. keV MDP (%)')
    plt.ylabel('[erg $\cdot$ cm$^{-2}$]')
    plt.title('%i GRBs, $\Delta t_{obs}=%s s,$ $t_{repoint}=%s s$'%(len(_flux),\
                                                                    t_obs,t_rep))
    plt.xlim(1, 100)
    plt.ylim(1e-9,1e-4)
    plt.plot([20, 20], [1e-9,1e-4], 'k--', lw=1, color='green')
    ax.set_yscale('log')
    ax.set_xscale('log')
    overlay_tag()
    save_current_figure('grb_MDP_prompt',clear=False)
    plt.show()



    # If mdp_vs_time = True Produces:
    # 1) the plot of the MDP for a given GRB
    #    as a function of the repointing time
    # 2) the plot of the MDP for a given GRB
    #    as a function of the observation duration
    color_list = ['red','salmon','goldenrod','darkgreen','limegreen',\
                  'royalblue','mediumpurple','darkviolet','deeppink']\
                  #'yellow','darkcyan'] 
    if mdp_vs_time == True:
        grb_list = ['GRB 060729', 'GRB 080411', 'GRB 091127', 'GRB 111209A',\
                    'GRB 120711A', 'GRB 130427A', 'GRB 130505A', 'GRB 130907A',\
                    'GRB 150403A']

        #1)------------------------------------------------------
        plt.figure(figsize=(10, 6), dpi=80)
        ax = plt.gca()
        for i,grb in enumerate(grb_list):
            repointing_time = numpy.logspace(2,4.8,20)
            plot_grb_mdp_vs_repoint(grb,repointing_time,show=False,\
                                    color=color_list[i])
        ax.legend(loc='upper left', shadow=False, fontsize='small')
        #plt.ylim(0,100)
        plt.plot([21600, 21600], [0, 100], 'k--', lw=1, color='green')
        plt.plot([43200, 43200], [0, 100], 'k--', lw=1,color='green')
        ax.set_yscale('log')
        ax.set_xscale('log')
        overlay_tag()
        save_current_figure('grb_MDP_vs_repoint',clear=False)

        #2)------------------------------------------------------
        plt.figure(figsize=(10, 6), dpi=80)
        ax = plt.gca()
        for i,grb in enumerate(grb_list):
            obs_time = numpy.logspace(3,5,30)
            plot_grb_mdp_vs_obstime(grb,obs_time,show=False,color=color_list[i])
        ax.legend(loc='upper right', shadow=False, fontsize='small')
        ax.set_yscale('log')
        ax.set_xscale('log')
        overlay_tag(x=0.5)
        save_current_figure('grb_MDP_vs_obstime',clear=False)
        plt.show()