Ejemplo n.º 1
0
def plot_doc():
    """
    """
    img = xFITSImage(os.path.join(XIMPOL_DATA, 'crab_complex_cmap.fits'))
    fig = img.plot(show=False)
    xFITSImage.add_label(fig, 'XIPE %d ks' %DURATION/1000.)
    plt.show()
Ejemplo n.º 2
0
def makeMDPComparisonPlot(imaging_file_path):
    
    non_imaging_file_path = imaging_file_path.replace('_imaging.txt','_non_imaging.txt')
    print "Using %s for non imaging file path"%non_imaging_file_path
    
    _phase_ave, _phase_err, mdp_imaging = numpy.loadtxt(imaging_file_path, unpack=True)
    _phase_ave, _phase_err, mdp_nonimaging = numpy.loadtxt(non_imaging_file_path, unpack=True)
    scale_factor = 10.
    print "Improvement with imaging"
    for i, phase in enumerate(_phase_ave):
        imaging = 100*mdp_imaging[i]*(1/numpy.sqrt(scale_factor))
        non_imaging = 100*mdp_nonimaging[i]*(1/numpy.sqrt(scale_factor))
        print "%s\t Imaging (non):%s (%s) %s"%(phase,imaging,non_imaging,non_imaging/imaging)
        
   
    sim_label_imaging = 'XIPE %s ks\n Imaging 15"' % (SIM_DURATION*scale_factor/1000.)
    sim_label_nonimaging = 'Non imaging'
    lc_label = 'Light curve'
    plt.errorbar(_phase_ave, 100*mdp_imaging*(1/numpy.sqrt(scale_factor)),xerr=_phase_err, label=sim_label_imaging,fmt='o',markersize=6)
    
    plt.errorbar(_phase_ave, 100*mdp_nonimaging*(1/numpy.sqrt(scale_factor)),xerr=_phase_err, label=sim_label_nonimaging,fmt='v',markersize=6)
    
    pl_normalization_spline.plot(scale=10., show=False,
                                color='darkgray',label=lc_label)
    #on_phase = 0.25, 0.45
    #off_phase = 0.45,0.9
    plt.axvspan(0.25, 0.45, color='r', alpha=0.45, lw=0)
    plt.axvspan(0.45, 0.9, color='gray', alpha=0.25, lw=0)
    
    plt.ylabel('MDP 99\%')
    plt.legend()
    plt.savefig('crab_complex_mdp_imaging_vs_nonimaging_%i_shaded.png'%(SIM_DURATION*scale_factor/1000.))
    plt.show()
Ejemplo n.º 3
0
Archivo: rmf.py Proyecto: pabell/ximpol
    def plot(self, show=True):
        """Plot the energy dispersion.
        """
        from ximpol.utils.matplotlib_ import pyplot as plt
        from ximpol.utils.matplotlib_ import context_two_by_two
        emin = self.matrix.xmin()
        emax = self.matrix.xmax()

        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)

        with context_two_by_two():
            plt.figure(1)
            ax = plt.subplot(2, 2, 1)
            self.matrix.plot(show=False)
            ax = plt.subplot(2, 2, 2)
            self.ebounds.plot(overlay=False, show=False)
            _plot_vslice(emin + 0.333*(emax - emin), 3)
            _plot_vslice(emin + 0.666*(emax - emin), 4)
        if show:
            plt.show()
Ejemplo n.º 4
0
 def plot_polarization_angle(self, show=True, degree=False, **kwargs):
     """Plot the polarization angle as a function of energy.
     """
     if self.fit_results == []:
         self.fit()
     _x = self.emean
     _dx = [self.emean - self.emin, self.emax - self.emean]
     if degree:
         _y = [numpy.degrees(r.phase) for r in self.fit_results]
         _dy = [numpy.degrees(r.phase_error) for r in self.fit_results]
     else:
         _y = [(r.phase) for r in self.fit_results]
         _dy = [(r.phase_error) for r in self.fit_results]
     # If there's more than one energy binning we also fit the entire
     # energy interval, but we don't want the corresponding data point to
     # appear in the plot, se we brutally get rid of it.
     if len(self.fit_results) > 1:
         _x = _x[:-1]
         _dx = [_x - self.emin[:-1], self.emax[:-1] - _x]
         _y = _y[:-1]
         _dy = _dy[:-1]
     plt.errorbar(_x, _y, _dy, _dx, fmt='o', **kwargs)
     plt.xlabel('Energy [keV]')
     if degree:
         plt.ylabel('Polarization angle [$^\circ$]')
     else:
         plt.ylabel('Polarization angle [rad]')
     if show:
         plt.show()
Ejemplo n.º 5
0
def plotmdp():
    spin00_pol_degree_spline = buildspline(0.5)
    spin00_mcube =  xBinnedModulationCube(fetch_mcubepath(0.5))

    spin998_pol_degree_spline = buildspline(0.998)
    spin998_mcube =  xBinnedModulationCube(fetch_mcubepath(0.998))

    spin00_mcube.fit()
    spin998_mcube.fit()
    
    spin00_fit_results = spin00_mcube.fit_results[0]
    spin998_fit_results = spin998_mcube.fit_results[0]

    
    plt.figure('MDP')
    
    spin00_mdp = spin00_mcube.mdp99[:-1]
    spin998_mdp = spin998_mcube.mdp99[:-1]
    emean = spin00_mcube.emean[:-1]
    emin =  spin00_mcube.emin[:-1]
    emax =  spin00_mcube.emax[:-1]
    width = (emax-emin)/2.
    plt.errorbar(emean,spin00_mdp,xerr=width, label='Spin 0.5',marker='o',linestyle='--')
    
    plt.errorbar(emean,spin998_mdp,xerr=width, label='Spin 0.998',marker='o',linestyle='--')
            
    plt.figtext(0.2, 0.85,'XIPE %s ks'%((SIM_DURATION*NUM_RUNS)/1000.),size=18)
    plt.xlim([1,10])
    
    plt.ylabel('MPD 99\%')
    plt.xlabel('Energy (keV)')
    plt.legend()
    plt.show()
Ejemplo n.º 6
0
 def test_plots(self):
     """
     """
     model = xpeInterstellarAbsorptionModel()
     plt.figure()
     model.xsection.plot(logx=True, logy=True, show=False)
     save_current_figure('gabs_xsection.png', clear=False)
     plt.figure()
     model.xsection_ecube().plot(logx=True, show=False)
     save_current_figure('gabs_xsection_ecube.png', clear=False)
     plt.figure()
     ra, dec = 10.684, 41.269
     column_density = mapped_column_density_HI(ra, dec, 'LAB')
     trans = model.transmission_factor(column_density)
     trans.plot(logx=True, show=False, label='$n_H = $%.3e' % column_density)
     plt.legend(loc='upper left')
     save_current_figure('gabs_trans_lab.png', clear=False)
     plt.figure()
     for column_density in [1.e20, 1.e21, 1.e22, 1.e23]:
         trans = model.transmission_factor(column_density)
         trans.plot(logx=True, show=False, label='$n_H = $%.1e' %\
                    column_density)
     plt.legend(loc='upper left')
     save_current_figure('gabs_trans_samples.png', clear=False)
     if sys.flags.interactive:
         plt.show()
Ejemplo n.º 7
0
def main():
    """
    """
    plt.figure(figsize=(10, 6), dpi=80)
    plt.title('Swift XRT light curves of GRBs up to 130427A')
    #get_all_swift_grb_names = ['GRB 130427A','GRB 041223']
    num_grb = 0
    for i,grb_name in enumerate(get_all_swift_grb_names()):
        flux_outfile = download_swift_grb_lc_file(grb_name)
        if type(flux_outfile) is str:
            integral_flux_spline = parse_light_curve(flux_outfile)
            if integral_flux_spline != 0:
                if grb_name == 'GRB 130427A':
                    integral_flux_spline.plot(num_points=1000,logx=True,\
                                              logy=True,show=False,\
                                              color="red",linewidth=1.0)
                    num_grb += 1
                    break
                    plt.title('Swift XRT light curves of GRBs up to now')
                else:
                    c = random.uniform(0.4,0.8)
                    integral_flux_spline.plot(num_points=1000,logx=True,\
                                              logy=True,show=False,\
                                              color='%f'%c,linewidth=1.0)
                    num_grb += 1
    print num_grb
    plt.show()
Ejemplo n.º 8
0
def plot_swift_lc(grb_list,show=True):
    """Plots Swift GRB light curves.
    """
    plt.figure(figsize=(10, 8), dpi=80)
    plt.title('Swift XRT light curves')
    num_grb = 0
    for grb_name in grb_list:
        flux_outfile = download_swift_grb_lc_file(grb_name, min_obs_time=21600)
        if flux_outfile is not None:
            integral_flux_spline = parse_light_curve(flux_outfile)
            if integral_flux_spline is not None:
                if grb_name == 'GRB 130427A':
                    integral_flux_spline.plot(num_points=1000,logx=True,\
                                              logy=True,show=False,\
                                              color="red",linewidth=1.0)
                    num_grb += 1
                else:
                    c = random.uniform(0.4,0.8)
                    integral_flux_spline.plot(num_points=1000,logx=True,\
                                              logy=True,show=False,\
                                              color='%f'%c,linewidth=1.0)
                    num_grb += 1
        else:
            continue
    logger.info('%i GRBs included in the plot.'%num_grb)
    if show:
        plt.show()
Ejemplo n.º 9
0
def plot_doc():
    """
    """
    img = xFITSImage(os.path.join(XIMPOL_DATA, 'tycho_cmap.fits'))
    fig = img.plot(show=False)
    xFITSImage.add_label(fig, 'XIPE 300 ks')
    plt.show()
Ejemplo n.º 10
0
def display():
    """Display the source model.
    """
    from ximpol.utils.matplotlib_ import pyplot as plt
    print(ROI_MODEL)
    fig = plt.figure('Energy spectrum')
    total_spectral_model.plot(logy=True, show=False, label='Total')
    nonthermal_spectral_model.plot(logy=True, show=False, label='Non-thermal')
    thermal_spectral_model.plot(logy=True, show=False, label='Thermal')
    plt.legend(bbox_to_anchor=(0.95, 0.95))
    fig = thermal_component.image.plot(show=False)
    fig.add_label(0.1,
                  0.92,
                  '1.5-3 keV',
                  relative=True,
                  size='xx-large',
                  color='white',
                  horizontalalignment='left')
    fig = nonthermal_component.image.plot(show=False)
    fig.add_label(0.1,
                  0.92,
                  '4-6 keV',
                  relative=True,
                  size='xx-large',
                  color='white',
                  horizontalalignment='left')
    plt.show()
Ejemplo n.º 11
0
def view():
      
    _mcube = xBinnedModulationCube(MCUBE_FILE_PATH)
    _mcube.fit()
    _fit_results = _mcube.fit_results[0]
    plt.figure('Polarization degree')
    _mcube.plot_polarization_degree(show=False, color='blue')
    pol_degree_spline.plot(color='lightgray',label='Spin %s'%spindegree, show=False)
    plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18)
    #plt.errorbar(_energy_mean, _pol_deg, yerr=_pol_deg_err, color='blue',marker='o')
    
    plt.legend()

    plt.figure('Polarization angle')
    _mcube.plot_polarization_angle(show=False, color='blue', degree=False)
    pol_angle_spline.plot(color='lightgray',label='Spin %s'%spindegree, show=False)
    plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18)
    #plt.errorbar(_energy_mean,_pol_angle, yerr= _pol_angle_err,color='blue',marker='o')
    plt.xlim([1,10])
    plt.legend()
    plt.figure('MDP %s'%base_name)
    mdp = _mcube.mdp99[:-1]
    emean = _mcube.emean[:-1]
    emin =  _mcube.emin[:-1]
    emax =  _mcube.emax[:-1]
    width = (emax-emin)/2.
    plt.errorbar(emean,mdp,xerr=width, label='MDP99',marker='o',linestyle='--')
    plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18)
    plt.xlim([1,10])
    plt.ylabel('MPD 99\%')
    plt.xlabel('Energy (keV)')
    #plt.legend()
    plt.show()
Ejemplo n.º 12
0
def plot_doc():
    """
    """
    img = xFITSImage(os.path.join(XIMPOL_DATA, 'tycho_cmap.fits'))
    fig = img.plot(show=False)
    xFITSImage.add_label(fig, 'XIPE 300 ks')
    plt.show()
Ejemplo n.º 13
0
Archivo: img.py Proyecto: pabell/ximpol
    def plot(self, show=True, zlabel='Counts/pixel', subplot=(1, 1, 1)):
        """Plot the image.

        This is using aplpy to render the image.

        Warning
        -------
        We have to figure out the subplot issue, here. I put in a horrible
        hack to recover the previous behavior when there's only one
        subplot.
        """
        import aplpy
        with context_no_grids():
            if subplot == (1, 1, 1):
                fig = aplpy.FITSFigure(self.hdu_list[0], figure=plt.figure())
            else:
                fig = aplpy.FITSFigure(self.hdu_list[0],
                                       figure=plt.figure(
                                           0,
                                           figsize=(10 * subplot[1],
                                                    10 * subplot[0])),
                                       subplot=subplot)
        fig.add_grid()
        fig.show_colorscale(cmap='afmhot', vmin=self.vmin, vmax=self.vmax)
        fig.add_colorbar()
        fig.colorbar.set_axis_label_text(zlabel)
        if show:
            plt.show()
        return fig
Ejemplo n.º 14
0
 def plot(self, show=True):
     """Overloaded plot method.
     """
     plt.errorbar(self.channel, self.rate, yerr=self.error, fmt='o')
     plt.xlabel('PHA')
     plt.ylabel('Rate [Hz]')
     plt.yscale('log')
     if show:
         plt.show()
Ejemplo n.º 15
0
 def plot(self, show=True):
     """Overloaded plot method.
     """
     fig = plt.figure('Phasogram')
     plt.errorbar(self.phase, self.counts, yerr=self.error, fmt='o')
     plt.xlabel('Phase')
     plt.ylabel('Counts/bin')
     if show:
         plt.show()
Ejemplo n.º 16
0
 def plot(self, show=True):
     """Overloaded plot method.
     """
     fig = plt.figure('Phasogram')
     plt.errorbar(self.phase, self.counts, yerr=self.error, fmt='o')
     plt.xlabel('Phase')
     plt.ylabel('Counts/bin')
     if show:
         plt.show()
Ejemplo n.º 17
0
 def plot(self, show=True):
     """Overloaded plot method.
     """
     plt.errorbar(self.time, self.counts/self.timedel,
                  yerr=self.error/self.timedel, fmt='o')
     plt.xlabel('Time [s]')
     plt.ylabel('Rate [Hz]')
     if show:
         plt.show()
Ejemplo n.º 18
0
def plot(save_plots=False):
    """
    """
    sim_label = 'XIPE %s ks' % (SIM_DURATION/1000.)
    mod_label = 'Input model'
    _phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,\
        _pol_angle_err = numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True)
    _colors = ['blue']*len(_pol_deg)
    plt.figure('Polarization degree')
    _good_fit = _pol_deg > 2*_pol_deg_err
    _bad_fit = numpy.logical_not(_good_fit)
    plt.errorbar(_phase[_good_fit], _pol_deg[_good_fit],
                 xerr=_phase_err[_good_fit], yerr=_pol_deg_err[_good_fit],
                 fmt='o', label=sim_label, color='blue')
    plt.errorbar(_phase[_bad_fit], _pol_deg[_bad_fit],
                 xerr=_phase_err[_bad_fit], yerr=_pol_deg_err[_bad_fit],
                 fmt='o', color='gray')
    pol_degree_spline.plot(show=False, label=mod_label, color='green')
    plt.axis([0., 1., 0., 0.1])
    plt.legend(bbox_to_anchor=(0.37, 0.95))
    plt.figtext(0.6, 0.8, '%.2f--%.2f keV' %\
                (E_BINNING[0], E_BINNING[-1]), size=16)
    if save_plots:
        plt.savefig('gk_per_polarization_degree.png')
    plt.figure('Polarization angle')
    plt.errorbar(_phase[_good_fit], _pol_angle[_good_fit],
                 xerr=_phase_err[_good_fit], yerr=_pol_angle_err[_good_fit],
                 fmt='o', label=sim_label, color='blue')
    plt.errorbar(_phase[_bad_fit], _pol_angle[_bad_fit],
                 xerr=_phase_err[_bad_fit], yerr=_pol_angle_err[_bad_fit],
                 fmt='o', color='gray')
    pol_angle_spline.plot(show=False, label=mod_label, color='green',
                          scale=numpy.radians(1.))
    plt.axis([0., 1., -0.1, 1.5])
    plt.xlabel('Rotational phase')
    plt.ylabel('Polarization angle [rad]')
    plt.legend(bbox_to_anchor=(0.37, 0.95))
    plt.figtext(0.6, 0.8, '%.2f--%.2f keV' %\
                (E_BINNING[0], E_BINNING[-1]), size=16)
    if save_plots:
        plt.savefig('gk_per_polarization_angle.png')
    _ebinning = zip(E_BINNING[:-1], E_BINNING[1:])
    if len(_ebinning) > 1:
        _ebinning.append((E_BINNING[0], E_BINNING[-1]))
    for i, (_emin, _emax) in enumerate(_ebinning):
        plt.figure('Phasogram %d' % i)
        phasogram = xBinnedPhasogram(_phasg_file_path(i))
        _scale = phasogram.counts.sum()/phasogram_spline.norm()/\
                 len(phasogram.counts)
        phasogram_spline.plot(show=False, label=mod_label, scale=_scale,
                              color='green')
        phasogram.plot(show=False, color='blue', label=sim_label )
        plt.legend(bbox_to_anchor=(0.37, 0.95))
        plt.figtext(0.65, 0.8, '%.2f--%.2f keV' % (_emin, _emax), size=16)
        if save_plots:
            plt.savefig('gk_per_phasogram_%d.png' % i)
    plt.show()
Ejemplo n.º 19
0
 def plot(self, show=True):
     """Overloaded plot method.
     """
     fig = plt.figure('Count spectrum')
     plt.errorbar(self.channel, self.rate, yerr=self.error, fmt='o')
     plt.xlabel('PHA')
     plt.ylabel('Rate [Hz]')
     plt.yscale('log')
     if show:
         plt.show()
Ejemplo n.º 20
0
def display():
    """Display the source model.
    """
    from ximpol.utils.matplotlib_ import pyplot as plt
    from ximpol.srcmodel.img import xFITSImage

    print(ROI_MODEL)
    fig = plt.figure('Energy spectrum')
    spectral_model_spline.plot(logy=True, show=False, label='Total')
    plt.show()
Ejemplo n.º 21
0
def display():
    """Display the source model.
    """
    from ximpol.utils.matplotlib_ import pyplot as plt
    from ximpol.srcmodel.img import xFITSImage

    print(ROI_MODEL)
    fig = plt.figure('Energy spectrum')
    spectral_model_spline.plot(logy=True, show=False, label='Total')
    plt.show()
Ejemplo n.º 22
0
 def plot_ymap(self, overlay=True, show=False):
     """Plot the y polarization map.
     """
     if self.y_img is None:
         self.y_img = xFITSImage(self.ymap_file_path, build_cdf=False)
     fig = self.y_img.plot(show=False, zlabel="Polarization degree (y)")
     if overlay:
         self.overlay_arrows(fig)
     if show:
         plt.show()
     return fig
Ejemplo n.º 23
0
 def plot(self, show=True, **kwargs):
     """Overloaded plot method.
     """
     if not kwargs.has_key('fmt'):
         kwargs['fmt'] = 'o'
     plt.errorbar(self.phase, self.counts, yerr=self.error,
                  xerr=0.5*self.phase_delta, **kwargs)
     plt.xlabel('Phase')
     plt.ylabel('Counts/bin')
     if show:
         plt.show()
def plot(save=False):
    """Plot the stuff in the analysis file.
    """
    for j in range(len(E_BINNING)):
        if (j==len(E_BINNING)-1):
            analysis_file = ANALYSIS_FILE_PATH
            emin=E_BINNING[0]
            emax=E_BINNING[-1]
        else:
            analysis_file = '%s_%d' % (ANALYSIS_FILE_PATH,j)
            emin=E_BINNING[j]
            emax=E_BINNING[j+1]
            
        sim_label = 'XIPE %s ks' % (SIM_DURATION/1000.)
        mod_label = 'Input model'
        lc_label = 'Light curve'
        _phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,\
            _pol_angle_err, _index, _index_err, _norm,\
            _norm_err = numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True)
        plt.figure('Polarization degree (%g-%g keV)' % (emin,emax))
        plt.title('Her X-1 (%g-%g keV)' % (emin,emax))
        pl_normalization_spline.plot(scale=20, show=False, color='lightgray',
                                     label=lc_label)
        plt.errorbar(_phase, _pol_deg, xerr=_phase_err, yerr=_pol_deg_err, fmt='o',
                     label=sim_label)
        pol_degree_spline.plot(show=False, label=mod_label)
#        pol_degree_spline_noqed.plot(show=False, label='No QED')
        plt.axis([0., 1., 0., 1.1])
        plt.legend(bbox_to_anchor=(0.4, 0.5))
        if save:
            save_current_figure('herx1_polarization_degree_%d' % j, OUTPUT_FOLDER, False)
        plt.figure('Polarization angle (%g-%g keV)' % (emin,emax))
        plt.title('Her X-1 (%g-%g keV)' % (emin,emax))
        pl_normalization_spline.plot(scale=60, offset=0, show=False,
                                     color='lightgray', label=lc_label)
        plt.errorbar(_phase, _pol_angle, xerr=_phase_err, yerr=_pol_angle_err,
            fmt='o', label=sim_label)
        pol_angle_spline.plot(show=False, label=mod_label)
        plt.axis([0., 1., 0, 3.15])
        plt.legend(bbox_to_anchor=(0.4, 0.3))
        if save:
            save_current_figure('herx1_polarization_angle_%d' %j, OUTPUT_FOLDER, False)
        plt.figure('Flux (%g-%g keV)' % (emin,emax))
        plt.title('Her X-1 (%g-%g keV)' % (emin,emax))
        plt.errorbar(_phase,
                     0.21*_norm/(2-_index)*(10.**(2.0-_index)-2.**(2.-_index)), xerr=_phase_err,
                     yerr=0.21*_norm_err/(2-_index)*(10.**(2-_index)-2.**(2.-_index)), fmt='o',
                     label=sim_label)
        pl_normalization_spline.plot(scale=1,show=False, label=mod_label)
        plt.axis([0., 1., None, None])
        plt.legend(bbox_to_anchor=(0.75, 0.95))
        if save:
            save_current_figure('herx1_flux_%d' % j, OUTPUT_FOLDER, False)
        plt.show()
Ejemplo n.º 25
0
def plot(save=False):
    """Plot the stuff in the analysis file.
    """
    sim_label = 'XIPE %s ks' % (SIM_DURATION/1000.)
    sim_label = 'OBS: %s ks' % (SIM_DURATION/1000.)
    mod_label = 'Input model'
    lc_label = 'Light curve'
    _phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,\
        _pol_angle_err, _index, _index_err, _norm,\
        _norm_err = numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True)
    plt.figure('Polarization degree')
    pl_normalization_spline.plot(scale=0.12, show=False, color='lightgray',
                                 label=lc_label)

    _pol_deg_err_p=numpy.where((_pol_deg+_pol_deg_err)<1.0,_pol_deg_err,1.0-_pol_deg)
    _pol_deg_err_m=numpy.where((_pol_deg-_pol_deg_err)>0.0,_pol_deg_err,_pol_deg)
    #if (_pol_deg+_pol_deg_err)>1.0: _pol_deg_err=1.0-yerr_p
    
    plt.errorbar(_phase, _pol_deg, xerr=_phase_err, yerr=[_pol_deg_err_m,_pol_deg_err_p], fmt='o',
                 label=sim_label)
    pol_degree_spline.plot(show=False, label=mod_label)
    plt.axis([0., 1., 0., 0.5])
    plt.legend(bbox_to_anchor=(0.45, 0.95))
    if save:
        save_current_figure('crab_polarization_degree', OUTPUT_FOLDER, False)
    plt.figure('Polarization angle')
    pl_normalization_spline.plot(scale=0.4, offset=1.25, show=False,
                                 color='lightgray', label=lc_label)
    plt.errorbar(_phase, _pol_angle, xerr=_phase_err, yerr=_pol_angle_err,
                 fmt='o', label=sim_label)
    pol_angle_spline.plot(show=False, label=mod_label)
    plt.axis([0., 1., 1.25, 3.])
    plt.legend(bbox_to_anchor=(0.45, 0.95))
    if save:
        save_current_figure('crab_polarization_angle', OUTPUT_FOLDER, False)
    plt.figure('PL normalization')
    plt.errorbar(_phase, _norm, xerr=_phase_err, yerr=_norm_err, fmt='o',
                 label=sim_label)
    pl_normalization_spline.plot(show=False, label=mod_label)
    plt.axis([0., 1., None, None])
    plt.legend(bbox_to_anchor=(0.45, 0.95))
    if save:
        save_current_figure('crab_pl_norm', OUTPUT_FOLDER, False)
    plt.figure('PL index')
    pl_normalization_spline.plot(scale=0.18, offset=1.3, show=False,
                                 color='lightgray', label=lc_label)
    plt.errorbar(_phase, _index, xerr=_phase_err, yerr=_index_err, fmt='o',
                 label=sim_label)
    pl_index_spline.plot(show=False, label=mod_label)
    plt.axis([0., 1., 1.3, 2.1])
    plt.legend(bbox_to_anchor=(0.45, 0.95))
    if save:
        save_current_figure('crab_pl_index', OUTPUT_FOLDER, False)
    plt.show()
Ejemplo n.º 26
0
 def plot(self, show=True):
     """Overloaded plot method.
     """
     fig = plt.figure('Light curve')
     plt.errorbar(self.time,
                  self.counts / self.timedel,
                  yerr=self.error / self.timedel,
                  fmt='o')
     plt.xlabel('Time [s]')
     plt.ylabel('Rate [Hz]')
     if show:
         plt.show()
Ejemplo n.º 27
0
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')
    pol_degree.plot(show=False)
    fig = plt.figure('Polarization angle')
    pol_angle.plot(show=False)
    plt.show()
Ejemplo n.º 28
0
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')
    pol_degree.plot(show=False)
    fig = plt.figure('Polarization angle')
    pol_angle.plot(show=False)
    plt.show()
Ejemplo n.º 29
0
def main(interactive=False):
    """Test the script plotting the light curve og GRB 130427A
    """
    #If you want all the GRBs use the following line:    
    grb_list = get_all_swift_grb_names()
    #grb_list = ['GRB 130427A','GRB 050124']
    plot_swift_lc(grb_list,show=False)
    overlay_tag()
    save_current_figure('Swift_XRT_light_curves',
                        clear=False)
    if interactive:
        plt.show()
Ejemplo n.º 30
0
def plot_doc():
    """
    """
    img = xFITSImage(os.path.join(XIMPOL_DATA, 'casa_cmap.fits'))
    fig = img.plot(show=False)
    #Option to draw the psf circle on the count map
    RAD_PSF = 11/60.
    fig.show_circles(350.769, 58.873, RAD_PSF/60., lw=2, color='white')
    fig.add_label(0.73,0.90, 'PSF', relative=True, size='x-large',
                                    color='white', horizontalalignment='left') 
    xFITSImage.add_label(fig, 'XIPE 250 ks')
    plt.show()
Ejemplo n.º 31
0
    def view(self, show=True):
        """Overloaded plot method (with default log scale on the y-axis).
        """
        from ximpol.utils.matplotlib_ import pyplot as plt

        plt.figure("PSF")
        xInterpolatedUnivariateSpline.plot(self, logy=True, show=False)
        plt.figure("Solid-angle convolution")
        self.generator.plot(logy=True, show=False)
        plt.figure("EEF")
        self.eef.plot(show=False)
        if show:
            plt.show()
Ejemplo n.º 32
0
 def plot_polarization_degree(self, show=True, **kwargs):
     """Plot the polarization degree as a function of energy.
     """
     if self.fit_results == []:
         self.fit()
     _x = self.emean
     _dx = [self.emean - self.emin, self.emax - self.emean]
     _y = [r.polarization_degree for r in self.fit_results]
     _dy = [r.polarization_degree_error for r in self.fit_results]
     plt.errorbar(_x, _y, _dy, _dx, fmt='o', **kwargs)
     plt.xlabel('Energy [keV]')
     plt.ylabel('Polarization degree')
     if show:
         plt.show()
Ejemplo n.º 33
0
 def view(self, off_axis_angle = 10., show=True):
     """Plot the effective area.
     """
     from ximpol.utils.matplotlib_ import pyplot as plt
     plt.figure('Effective area')
     xInterpolatedUnivariateSplineLinear.plot(self, show=False,
                                              label='On axis')
     plt.plot(self.x, self.eval_(self.x, off_axis_angle),
              label='%s arcmin off-axis' % off_axis_angle)
     plt.legend(bbox_to_anchor=(0.85, 0.75))
     plt.figure('Vignetting')
     self.vignetting.plot(show=False)
     if show:
         plt.show()
Ejemplo n.º 34
0
 def plot_polarization_degree(self, show=True, **kwargs):
     """Plot the polarization degree as a function of energy.
     """
     if self.fit_results == []:
         self.fit()
     _x = self.emean
     _dx = [self.emean - self.emin, self.emax - self.emean]
     _y = [r.polarization_degree for r in self.fit_results]
     _dy = [r.polarization_degree_error for r in self.fit_results]
     plt.errorbar(_x, _y, _dy, _dx, fmt='o', **kwargs)
     plt.xlabel('Energy [keV]')
     plt.ylabel('Polarization degree')
     if show:
         plt.show()
Ejemplo n.º 35
0
 def plot(self, off_axis_angle=10., show=True):
     """Plot the effective area.
     """
     from ximpol.utils.matplotlib_ import pyplot as plt
     plt.figure('Effective area')
     xInterpolatedUnivariateSplineLinear.plot(self,
                                              show=False,
                                              label='On axis')
     plt.plot(self.x,
              self.eval_(self.x, off_axis_angle),
              label='%s arcmin off-axis' % off_axis_angle)
     plt.legend(bbox_to_anchor=(0.85, 0.75))
     plt.figure('Vignetting')
     self.vignetting.plot(show=False)
     if show:
         plt.show()
Ejemplo n.º 36
0
def display():
    """Display the source model.
    """
    from ximpol.utils.matplotlib_ import pyplot as plt
    print(ROI_MODEL)
    fig = plt.figure('Energy spectrum')
    total_spectral_model.plot(logy=True, show=False, label='Total')
    nonthermal_spectral_model.plot(logy=True, show=False, label='Non-thermal')
    thermal_spectral_model.plot(logy=True, show=False, label='Thermal')
    plt.legend(bbox_to_anchor=(0.95, 0.95))
    fig = thermal_component.image.plot(show=False)
    fig.add_label(0.1, 0.92, '1.5-3 keV', relative=True, size='xx-large',
                  color='white', horizontalalignment='left')
    fig = nonthermal_component.image.plot(show=False)
    fig.add_label(0.1, 0.92, '4-6 keV', relative=True, size='xx-large',
                  color='white', horizontalalignment='left')
    plt.show()
Ejemplo n.º 37
0
 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()
Ejemplo n.º 38
0
 def plot_polarization_angle(self, show=True, degree=True, **kwargs):
     """Plot the polarization angle as a function of energy.
     """
     if self.fit_results == []:
         self.fit()
     _x = self.emean
     _dx = [self.emean - self.emin, self.emax - self.emean]
     if degree:
         _y = [numpy.degrees(r.phase) for r in self.fit_results]
         _dy = [numpy.degrees(r.phase_error) for r in self.fit_results]
     else:
         _y = [(r.phase) for r in self.fit_results]
         _dy = [(r.phase_error) for r in self.fit_results]
     plt.errorbar(_x, _y, _dy, _dx, fmt='o', **kwargs)
     plt.xlabel('Energy [keV]')
     plt.ylabel('Polarization angle [$^\circ$]')
     if show:
         plt.show()
Ejemplo n.º 39
0
Archivo: mrf.py Proyecto: 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()
Ejemplo n.º 40
0
 def plot_polarization_angle(self, show=True, degree=True, **kwargs):
     """Plot the polarization angle as a function of energy.
     """
     if self.fit_results == []:
         self.fit()
     _x = self.emean
     _dx = [self.emean - self.emin, self.emax - self.emean]
     if degree:
         _y = [numpy.degrees(r.phase) for r in self.fit_results]
         _dy = [numpy.degrees(r.phase_error) for r in self.fit_results]
     else:
         _y = [(r.phase) for r in self.fit_results]
         _dy = [(r.phase_error) for r in self.fit_results]
     plt.errorbar(_x, _y, _dy, _dx, fmt='o', **kwargs)
     plt.xlabel('Energy [keV]')
     plt.ylabel('Polarization angle [$^\circ$]')
     if show:
         plt.show()
Ejemplo n.º 41
0
    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()
Ejemplo n.º 42
0
Archivo: psf.py Proyecto: pabell/ximpol
def main():
    """
    """
    import os
    from ximpol import XIMPOL_IRF
    from ximpol.utils.matplotlib_ import pyplot as plt

    file_path = os.path.join(XIMPOL_IRF,'fits','xipe_baseline.psf')
    psf = xPointSpreadFunction(file_path)
    print(psf.rvs(10))
    ra, dec = 1., 1.
    print(psf.smear_single(ra, dec, 10))
    rmax = 50
    plt.hist(psf.rvs(100000), rmax, (0, rmax), rwidth=1, histtype='step',
             lw=2, normed=True)
    _r = numpy.linspace(0, rmax, rmax)
    _psf = psf(_r)/psf.norm()
    plt.plot(_r, _psf)
    plt.show()
Ejemplo n.º 43
0
    def plot(self,
             num_pointsx=100,
             num_pointsy=100,
             num_contours=75,
             logz=False,
             show=True):
        """Plot the spline.

        Args
        ----
        num_pointsx : int
            The number of x sampling points to be used to draw the spline.

        num_pointsy : int
            The number of y sampling points to be used to draw the spline.

        num_contours : int
            The number of contours for the color plot.

        show : bool, optional
            If True, `plt.show()` is called at the end, interrupting the flow.
        """
        from ximpol.utils.matplotlib_ import pyplot as plt
        _x = numpy.linspace(self.xmin(), self.xmax(), num_pointsx)
        _y = numpy.linspace(self.ymin(), self.ymax(), num_pointsy)
        _x, _y = numpy.meshgrid(_x, _y)
        _z = self(_x, _y, grid=False)
        if logz:
            from matplotlib.colors import LogNorm
            _levels = numpy.logspace(-4, numpy.log10(_z.max()), num_contours)
            contour = plt.contourf(_x, _y, _z, levels=_levels, norm=LogNorm())
        else:
            contour = plt.contourf(_x, _y, _z, num_contours)
        bar = plt.colorbar()
        if self.xname is not None:
            plt.xlabel(self.xlabel())
        if self.yname is not None:
            plt.ylabel(self.ylabel())
        if self.zname is not None:
            bar.set_label(self.zlabel())
        if show:
            plt.show()
Ejemplo n.º 44
0
 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()
Ejemplo n.º 45
0
def view():
    #_energy_mean,_emin, _emax, _pol_deg, _pol_deg_err, _pol_angle, \
    #    _pol_angle_err = \
    #                    numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True)
    _mcube = xBinnedModulationCube(MCUBE_FILE_PATH)
    _mcube.fit()
    _fit_results = _mcube.fit_results[0]
    plt.figure('Polarization degree')
    _mcube.plot_polarization_degree(show=False, color='blue')
    pol_degree_spline.plot(color='lightgray', label='Model', show=False)

    #plt.errorbar(_energy_mean, _pol_deg, yerr=_pol_deg_err, color='blue',marker='o')

    plt.figure('Polarization angle')
    _mcube.plot_polarization_angle(show=False, color='blue', degree=False)
    pol_angle_spline.plot(color='lightgray', label='Model', show=False)
    #plt.errorbar(_energy_mean,_pol_angle, yerr= _pol_angle_err,color='blue',marker='o')

    plt.legend()
    plt.show()
Ejemplo n.º 46
0
def display():
    """Display the source model.
    """
    from ximpol.utils.matplotlib_ import pyplot as plt
    from ximpol.srcmodel.img import xFITSImage

    print(ROI_MODEL)
    fig = plt.figure('Energy spectrum')
    total_spectral_model.plot(logy=True, show=False, label='Total')
    nonthermal_spectral_model.plot(logy=True, show=False, label='Non-thermal')
    thermal_spectral_model.plot(logy=True, show=False, label='Thermal')
    plt.legend(bbox_to_anchor=(0.95, 0.95))
    fig = thermal_component.image.plot(show=False)
    xFITSImage.add_label(fig, 'Chandra 1.5-3.0 keV')
    fig = nonthermal_component.image.plot(show=False)
    xFITSImage.add_label(fig, 'Chandra 4.0-6.0 keV')
    img = xFITSImage(he_img_file_path)
    fig = img.plot(show=False)
    polarization_map.build_grid_sample(ROI_MODEL.ra, ROI_MODEL.dec)
    polarization_map.overlay_arrows(fig)
    plt.show()
Ejemplo n.º 47
0
 def plot(self, show=True, fit=True, analyze=True, xsubplot=0):
     """Plot the azimuthal distributions for all the energy bins.
     """
     if analyze:
         fit = True
     for i, _emean in enumerate(self.emean):
         if xsubplot == 0:
             plt.figure()
         else:
             plt.subplot(len(self.emean), xsubplot + 1,
                         (xsubplot + 1) * (i + 1))
         self.plot_bin(i, False, False)
         if fit:
             _res = self.fit_bin(i)
             _res.plot(color=xpColor(i))
     if analyze:
         fig = plt.figure('Polarization degree vs. energy')
         self.plot_polarization_degree(show=False)
         fig = plt.figure('Polarization angle vs. energy')
         self.plot_polarization_angle(show=False)
     if show:
         plt.show()
Ejemplo n.º 48
0
 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()
Ejemplo n.º 49
0
Archivo: psf.py Proyecto: pabell/ximpol
def main():
    """
    """
    import os
    from ximpol import XIMPOL_IRF
    from ximpol.utils.matplotlib_ import pyplot as plt

    file_path = os.path.join(XIMPOL_IRF, 'fits', 'xipe_baseline.psf')
    psf = xPointSpreadFunction(file_path)
    print(psf.rvs(10))
    ra, dec = 1., 1.
    print(psf.smear_single(ra, dec, 10))
    rmax = 50
    plt.hist(psf.rvs(100000),
             rmax, (0, rmax),
             rwidth=1,
             histtype='step',
             lw=2,
             normed=True)
    _r = numpy.linspace(0, rmax, rmax)
    _psf = psf(_r) / psf.norm()
    plt.plot(_r, _psf)
    plt.show()
Ejemplo n.º 50
0
Archivo: rmf.py Proyecto: pabell/ximpol
    def plot(self, show=True):
        """Plot the energy dispersion.
        """
        from ximpol.utils.matplotlib_ import pyplot as plt
        from ximpol.utils.matplotlib_ import context_two_by_two
        emin = self.matrix.xmin()
        emax = self.matrix.xmax()

        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)

        with context_two_by_two():
            plt.figure(1)
            ax = plt.subplot(2, 2, 1)
            self.matrix.plot(show=False)
            ax = plt.subplot(2, 2, 2)
            self.ebounds.plot(overlay=False, show=False)
            _plot_vslice(emin + 0.333 * (emax - emin), 3)
            _plot_vslice(emin + 0.666 * (emax - emin), 4)
        if show:
            plt.show()
Ejemplo n.º 51
0
def plot(save=False):
    """Plot the stuff in the analysis file.
    """
    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)

    sim_label = 'XIPE'
    mod_label = 'Input model'
    lc_label = 'Light curve'
    _time, _time_errp, _time_errm, _pol_deg, _pol_deg_err, _pol_angle,\
        _pol_angle_err, _index, _index_err, _norm,\
        _norm_err = numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True)
    logger.info(_time)
    logger.info((_time_errp + _time_errm) / 3600.)
    _pol_angle = numpy.degrees(_pol_angle)
    _pol_angle_err = numpy.degrees(_pol_angle_err)
    plt.figure('Polarization degree')
    pol_degree_spline.plot(show=False, label=mod_label, logx=True)
    plt.errorbar(_time,
                 _pol_deg,
                 xerr=[_time_errm, _time_errp],
                 yerr=_pol_deg_err,
                 fmt='o',
                 label=sim_label)
    plt.axis([100., 1e6, 0., 0.6])
    plt.legend(bbox_to_anchor=(0.4, 0.95))
    draw_time_grid()
    if save:
        save_current_figure('grb130427_swift_polarization_degree',
                            OUTPUT_FOLDER, False)
    plt.figure('Polarization angle')
    _x = pol_degree_spline.x
    _y = numpy.full(len(_x), polarization_angle(_x, None, None, None))
    _y = numpy.degrees(_y)
    fmt = dict(xname='Time',
               xunits='s',
               yname='Polarization angle',
               yunits=r'$^\circ$')
    _s = xInterpolatedUnivariateSpline(_x, _y, **fmt)
    _s.plot(logx=True, show=False, label=mod_label)
    plt.errorbar(_time,
                 _pol_angle,
                 xerr=[_time_errm, _time_errp],
                 yerr=_pol_angle_err,
                 fmt='o',
                 label=sim_label)
    plt.axis([100., 1e6, None, None])
    plt.legend(bbox_to_anchor=(0.4, 0.95))
    draw_time_grid()
    if save:
        save_current_figure('grb130427_swift_polarization_angle',
                            OUTPUT_FOLDER, False)
    plt.figure('PL index')
    _y = numpy.full(len(_x), PL_INDEX)
    fmt = dict(xname='Time', xunits='s', yname='PL index')
    _s = xInterpolatedUnivariateSpline(_x, _y, **fmt)
    _s.plot(logx=True, show=False, label=mod_label)
    plt.errorbar(_time,
                 _index,
                 xerr=[_time_errm, _time_errp],
                 yerr=_index_err,
                 fmt='o',
                 label=sim_label)
    plt.axis([100., 1e6, None, None])
    plt.legend(bbox_to_anchor=(0.4, 0.95))
    draw_time_grid()
    if save:
        save_current_figure('grb130427_swift_pl_index', OUTPUT_FOLDER, False)
    #plt.figure('PL normalization')
    #plt.errorbar(_time, _norm, xerr=[_time_errm, _time_errp], yerr=_norm_err,
    #             fmt='o', label=sim_label)
    #pl_normalization_spline.plot(show=False, label=mod_label)
    #plt.axis([100., 1e6, None, None])
    #plt.legend(bbox_to_anchor=(0.4, 0.95))
    #draw_time_grid()
    #if save:
    #    save_current_figure('grb130427_swift_pl_norm', OUTPUT_FOLDER, False)
    plt.figure('Light curve')
    lc = xBinnedLightCurve(_lc_file_path())
    lc.plot(show=False)
    # This should be implemented in the binned LC class.
    plt.xscale('log')
    plt.yscale('log')
    plt.axis([100., 1e6, None, None])
    draw_time_grid()
    if save:
        save_current_figure('grb130427_swift_lc', OUTPUT_FOLDER, False)
    plt.show()
Ejemplo n.º 52
0
#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)
    plt.show()
Ejemplo n.º 53
0
def plot(save=False):
    logger.info('Plotting stuff...')
    pipeline.xpbin(evt_file_path, algorithm='CMAP', outfile=map_file_path)
    regions = pyregion.open(reg_file_path)
    full_map = xBinnedMap(map_file_path)
    fig_all = full_map.plot(show=False)

    for i, region in enumerate(regions):
        ra, dec, rad = region.coord_list
        #fig_all.show_circles(ra, dec, rad, lw=1)

        fig = full_map.plot(show=False, subplot=(1, 2, 1))
        plt.subplots_adjust(hspace=0.001)
        fig.show_circles(ra, dec, rad, lw=1)
        mcube_file_path = get_mcube_file_path(i)
        mcube = xBinnedModulationCube(mcube_file_path)
        mcube.plot(show=False, analyze=False, xsubplot=1)

        scale_x  = rad/numpy.cos(numpy.deg2rad(dec)) # This is to take into account the effect of the projection.
        scale_y  = rad

        for j,fit in enumerate(mcube.fit_results):
            angle = fit.phase
            angle_error = fit.phase_error
            degree = fit.polarization_degree

            #nangles=20
            #for t in range(nangles):
            #    dx = scale_x*numpy.cos(numpy.pi*2.0*t/float(nangles))#angle)
            #    dy = scale_y*numpy.sin(numpy.pi*2.0*t/float(nangles))#angle)
            #    fig.show_arrows(ra, dec, dx, dy, color='w', alpha=1, width=1,head_width=0, head_length=0)
            #    pass

            dx = scale_x*numpy.cos(angle)
            dy = scale_y*numpy.sin(angle)

            dx1 = scale_x*degree*numpy.cos(angle+angle_error)
            dy1 = scale_y*degree*numpy.sin(angle+angle_error)
            dx2 = scale_x*degree*numpy.cos(angle-angle_error)
            dy2 = scale_y*degree*numpy.sin(angle-angle_error)

            fig.show_arrows(ra, dec, dx, dy, color=xpColor(j), alpha=1, linestyle='dashed', width=0.2,head_width=0, head_length=0)
            fig.show_arrows(ra, dec, -dx, -dy, color=xpColor(j), alpha=1, linestyle='dashed', width=0.2,head_width=0, head_length=0)
            fig.show_arrows(ra, dec, dx1, dy1, color=xpColor(j), alpha=1, width=1,head_width=0, head_length=0)
            fig.show_arrows(ra, dec, -dx1, -dy1, color=xpColor(j), alpha=1, width=1,head_width=0, head_length=0)
            fig.show_arrows(ra, dec, dx2, dy2, color=xpColor(j), alpha=1, width=1,head_width=0, head_length=0)
            fig.show_arrows(ra, dec, -dx2, -dy2, color=xpColor(j), alpha=1, width=1,head_width=0, head_length=0)

            fig_all.show_arrows(ra, dec, dx, dy, color=xpColor(j), alpha=1, linestyle='dashed', width=0.2,head_width=0, head_length=0)
            fig_all.show_arrows(ra, dec, -dx, -dy, color=xpColor(j), alpha=1, linestyle='dashed', width=0.2,head_width=0, head_length=0)
            fig_all.show_arrows(ra, dec, dx1, dy1, color=xpColor(j), alpha=1, width=1,head_width=0, head_length=0)
            fig_all.show_arrows(ra, dec, -dx1, -dy1, color=xpColor(j), alpha=1, width=1,head_width=0, head_length=0)
            fig_all.show_arrows(ra, dec, dx2, dy2, color=xpColor(j), alpha=1, width=1,head_width=0, head_length=0)
            fig_all.show_arrows(ra, dec, -dx2, -dy2, color=xpColor(j), alpha=1, width=1,head_width=0, head_length=0)


        if save:
            fig.save(mcube_file_path.replace('.fits', '.png'))
            plt.clf()
        else:
            plt.show()
        pass
    fig_all.save(os.path.join(XIMPOL_DATA, 'tycho_reg_all.png'))