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()
Example #2
0
def analyze():
    """
    """
    if os.path.exists(ANALYSIS_FILE_PATH):
        logger.info('%s exists, delete it if you want to recreate it.' %\
                    ANALYSIS_FILE_PATH)
        return
    logger.info('Opening output file %s...' % ANALYSIS_FILE_PATH)
    analysis_file = open(ANALYSIS_FILE_PATH, 'w')
    for i, (_min, _max) in enumerate(PHASE_BINNING):
        _mcube = xBinnedModulationCube(_mcube_file_path(i))
        _mcube.fit()
        _fit_results = _mcube.fit_results[-1]
        print _fit_results
        _phase = 0.5*(_min + _max)
        _phase_err = 0.5*(_max - _min)
        _pol_deg = _fit_results.polarization_degree
        _pol_deg_err = _fit_results.polarization_degree_error
        _pol_angle = _fit_results.phase
        _pol_angle_err = _fit_results.phase_error
        _data = (_phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,
                 _pol_angle_err)
        _fmt = ('%.4e   ' * len(_data)).strip()
        _fmt = '%s\n' % _fmt
        _line = _fmt % _data
        analysis_file.write(_line)
    analysis_file.close()
Example #3
0
def analyze():
    """Analyze the data.
    """
    logger.info('Opening output file %s...' % ANALYSIS_FILE_PATH)
    analysis_file = open(ANALYSIS_FILE_PATH, 'w')
    for i, (_min, _max) in enumerate(zip(TIME_BINNING[:-1], TIME_BINNING[1:])):
        _mcube = xBinnedModulationCube(_mcube_file_path(i))
        _mcube.fit()
        _fit_results = _mcube.fit_results[0]
        _sel_file = xEventFile(_sel_file_path(i))
        _time = numpy.average(_sel_file.event_data['TIME'])
        _sel_file.close()
        _time_errp = _max - _time
        _time_errm = _time - _min
        _pol_deg = _fit_results.polarization_degree
        _pol_deg_err = _fit_results.polarization_degree_error
        _pol_angle = _fit_results.phase
        _pol_angle_err = _fit_results.phase_error
        _spec_fitter = PIPELINE.xpxspec(_pha1_file_path(i), plot=False)
        (_index, _index_err), (_norm,
                               _norm_err) = _spec_fitter.fit_parameters()
        # The division by the phase interval is a workaround and we should
        # keep track of that in xpselect.
        _norm /= (_max - _min)
        _norm_err /= (_max - _min)
        _data = (_time, _time_errp, _time_errm, _pol_deg, _pol_deg_err,
                 _pol_angle, _pol_angle_err, _index, _index_err, _norm,
                 _norm_err)
        _fmt = ('%.4e   ' * len(_data)).strip()
        _fmt = '%s\n' % _fmt
        _line = _fmt % _data
        analysis_file.write(_line)
    analysis_file.close()
Example #4
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()
Example #5
0
def analyze():
    """Analyze the data.
    """
    logger.info('Opening output file %s...' % ANALYSIS_FILE_PATH)
    analysis_file = open(ANALYSIS_FILE_PATH, 'w')
    for i, (_min, _max) in enumerate(zip(TIME_BINNING[:-1],
                                         TIME_BINNING[1:])):
        _mcube = xBinnedModulationCube(_mcube_file_path(i))
        _mcube.fit()
        _fit_results = _mcube.fit_results[0]
        _sel_file = xEventFile(_sel_file_path(i))
        _time = numpy.average(_sel_file.event_data['TIME'])
        _sel_file.close()
        _time_errp = _max - _time
        _time_errm = _time - _min
        _pol_deg = _fit_results.polarization_degree
        _pol_deg_err = _fit_results.polarization_degree_error
        _pol_angle = _fit_results.phase
        _pol_angle_err = _fit_results.phase_error
        _spec_fitter = PIPELINE.xpxspec(_pha1_file_path(i), plot=False)
        (_index, _index_err), (_norm, _norm_err) = _spec_fitter.fit_parameters()
        # The division by the phase interval is a workaround and we should
        # keep track of that in xpselect.
        _norm /= (_max - _min)
        _norm_err /= (_max - _min)
        _data = (_time, _time_errp, _time_errm, _pol_deg, _pol_deg_err,
                 _pol_angle, _pol_angle_err, _index, _index_err, _norm,
                 _norm_err)
        _fmt = ('%.4e   ' * len(_data)).strip()
        _fmt = '%s\n' % _fmt
        _line = _fmt % _data
        analysis_file.write(_line)
    analysis_file.close()
def plot():
    
    spherical_mcube =  xBinnedModulationCube(SPHERICAL_MCUBE_PATH)
    wedge_mcube =  xBinnedModulationCube(WEDGE_MCUBE_PATH)

    spherical_mcube.fit()
    wedge_mcube.fit()
    
    spherical_fit_results = spherical_mcube.fit_results[0]
    wedge_fit_results = wedge_mcube.fit_results[0]

    
    plt.figure('Polarization degree')
    
    spherical_mcube.plot_polarization_degree(show=False, color='blue')
    pol_degree_spline_spherical.plot(color='lightblue',label='Spherical corona model (40 degree inclination)', show=False)

    wedge_mcube.plot_polarization_degree(show=False, color='red')
    pol_degree_spline_wedge.plot(color='lightsalmon',label='Wedge corona model  (40 degree inclination)', show=False)
    
    plt.figtext(0.2, 0.85,'XIPE %s ks'%((SIM_DURATION*NUM_RUNS)/1000.),size=18)
    plt.xlim([1,10])
    plt.legend()
    plt.show()
Example #7
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()
Example #8
0
def analyze():
    """Analyze the data.Testing this method, but I must be missing something, it does not work yet.
    """
    logger.info('Opening output file %s...' % ANALYSIS_FILE_PATH)
    analysis_file = open(ANALYSIS_FILE_PATH, 'w')
    _mcube = xBinnedModulationCube(MCUBE_FILE_PATH)
    _mcube.fit()
    _fit_results = _mcube.fit_results[0]
    _pol_deg = _fit_results.polarization_degree
    _pol_deg_err = _fit_results.polarization_degree_error
    _pol_angle = _fit_results.phase
    _pol_angle_err = _fit_results.phase_error
    #_energy_mean = _mcube.emean[0]
    #_emin = _mcube.emean[1]
    #_emax = _mcube.emean[2]
    #_data = (_energy_mean,_emin, _emax,_pol_deg, _pol_deg_err, _pol_angle, _pol_angle_err)
    print _data
    _fmt = ('%.4e   ' * len(_data)).strip()
    _fmt = '%s\n' % _fmt
    _line = _fmt % _data
    analysis_file.write(_line)
    analysis_file.close()
def analyze():
    """Analyze the data.
    """

    for j in range(len(E_BINNING)):
        if (j==len(E_BINNING)-1):
            logger.info('Opening output file %s...' % ANALYSIS_FILE_PATH)
            analysis_file = open(ANALYSIS_FILE_PATH, 'w')
        else:
            logger.info('Opening output file %s_%d ...' % (ANALYSIS_FILE_PATH,j))
            analysis_file = open('%s_%d' % (ANALYSIS_FILE_PATH,j), 'w')
        for i, (_min, _max) in enumerate(zip(PHASE_BINNING[:-1],
                                             PHASE_BINNING[1:])):
            _mcube = xBinnedModulationCube(_mcube_file_path(i))
            _mcube.fit()
            _fit_results = _mcube.fit_results[j]
            _emean = _mcube.emean[j]
            _emin = _mcube.emin[j]
            _emax = _mcube.emax[j]
            print("%g - %g - %g\n" % (_emin,_emean,_emax))
            _phase = 0.5*(_min + _max)
            _phase_err = 0.5*(_max - _min)
            _pol_deg = _fit_results.polarization_degree
            _pol_deg_err = _fit_results.polarization_degree_error
            _pol_angle = _fit_results.phase
            _pol_angle_err = _fit_results.phase_error
            _spec_fitter = PIPELINE.xpxspec(_pha1_file_path(i), plot=False,model='powerlaw')
            (_index, _index_err), (_norm, _norm_err) = _spec_fitter.fit_parameters()
            # The division by the phase interval is a workaround and we should
            # keep track of that in xpselect.
            _norm /= (_max - _min)
            _norm_err /= (_max - _min)
            _data = (_phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,
                     _pol_angle_err, _index, _index_err, _norm, _norm_err)
            _fmt = ('%.4e   ' * len(_data)).strip()
            _fmt = '%s\n' % _fmt
            _line = _fmt % _data
            analysis_file.write(_line)
        analysis_file.close()
Example #10
0
def fit_pol_map():
    
    
    output_file =  file('%s/%s'%(XIMPOL_DATA,OUTPUT_FILE),'w')
    
    _ra = numpy.linspace(ra_min, ra_max, num_points)
    _dec = numpy.linspace(dec_min, dec_max, num_points)
    for i,ra in enumerate(_ra):
        for j,dec in enumerate(_dec):
            mcube_file_path = get_mcube_file_path(i,j)
            mcube = xBinnedModulationCube(mcube_file_path)
            mcube.fit()
            for j,fit in enumerate(mcube.fit_results):

                degree = fit.polarization_degree
                degree_error = fit.polarization_degree_error
                angle = fit.phase
                angle_error = fit.phase_error
                counts = mcube.counts[j]
                emin = mcube.emin[j]
                emax = mcube.emax[j]
                
                #These conditions are needed to make sure that we do not get unphysical values for the polarization degree due to low statistics in the fitting stage. 
                if degree_error > degree or counts < 10000:
                    degree = 0.0
                  #  degree_error = 0.0
                else:
                    degree = degree*100
                    degree_error = degree_error*100
                
                if degree > 50:
                    mcube.plot_bin(0)
                #write the fit values to a txt file the first time you run the code and then simply read the txt file for fast plotting after.
                line = '%s,%s,%s,%s,%s,%s,%s\n'%(emin,emax,degree, degree_error, angle, angle_error, counts)
                print "Info",line
                output_file.write(line)

    output_file.close()
Example #11
0
def analyze():
    """
    """
    if os.path.exists(ANALYSIS_FILE_PATH):
        logger.info('%s exists, delete it if you want to recreate it.' %\
                    ANALYSIS_FILE_PATH)
        return
    modf = load_mrf('xipe_goal')
    logger.info('Opening output file %s...' % ANALYSIS_FILE_PATH)
    analysis_file = open(ANALYSIS_FILE_PATH, 'w')
    for i, (_min, _max) in enumerate(PHASE_BINNING):
        _evt_file = xEventFile(_sel_file_path(i))
        _energy = _evt_file.event_data['ENERGY']
        _phase = _evt_file.event_data['PHASE']
        exp = (polarization_degree(_energy, _phase, 0, 0)*modf(_energy)).sum()/\
              modf(_energy).sum()
        _mcube = xBinnedModulationCube(_mcube_file_path(i))
        _mcube.fit()
        _fit_results = _mcube.fit_results[-1]
        print _fit_results
        print exp
        print polarization_degree(_mcube.emean[-1], _phase, 0, 0)
        raw_input()
        _phase = 0.5*(_min + _max)
        _phase_err = 0.5*(_max - _min)
        _pol_deg = _fit_results.polarization_degree
        _pol_deg_err = _fit_results.polarization_degree_error
        _pol_angle = _fit_results.phase
        _pol_angle_err = _fit_results.phase_error
        _data = (_phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,
                 _pol_angle_err)
        _fmt = ('%.4e   ' * len(_data)).strip()
        _fmt = '%s\n' % _fmt
        _line = _fmt % _data
        analysis_file.write(_line)
    analysis_file.close()
Example #12
0
def analyze():

    """Analyze the data.Testing this method, but I must be missing something, it does not work yet.
    """
    logger.info('Opening output file %s...' % ANALYSIS_FILE_PATH)
    analysis_file = open(ANALYSIS_FILE_PATH, 'w')
    _mcube = xBinnedModulationCube(MCUBE_FILE_PATH)
    _mcube.fit()
    for j, fit in enumerate(_mcube.fit_results):
    #_fit_results = _mcube.fit_results[0]
        _pol_deg = fit.polarization_degree
        _pol_deg_err = fit.polarization_degree_error
        _pol_angle = fit.phase
        _pol_angle_err = fit.phase_error
        _energy_mean = _mcube.emean[j]
        _emin = _mcube.emin[j]
        _emax = _mcube.emax[j]
        _data = (_energy_mean,_emin, _emax,_pol_deg, _pol_deg_err, _pol_angle, _pol_angle_err)
        print _data
        _fmt = ('%.4e   ' * len(_data)).strip()
        _fmt = '%s\n' % _fmt
        _line = _fmt % _data
        analysis_file.write(_line)
    analysis_file.close()
Example #13
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 %s corona'%model_type, 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='Model %s corona'%model_type, 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.legend()
    plt.figure('MDP %s'%base_name)
    mdp = _mcube.mdp99
    emean = _mcube.emean
    emin =  _mcube.emin
    emax =  _mcube.emax
    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()
    elif '-o'   in a: outfile = sys.argv[i+1]
    pass

fig=xBinnedMap(file_map).plot(show=False,subplot=(1,2,1))#,figure=fig)
fig.show_circles(ra,dec,rad,lw=1)
rad*=60
evtSelect=xEventSelect(evt_file_path, ra=ra, dec=dec, rad=rad, outfile=file_selected_path,
                       emax=None, emin=None, mc=False, mcsrcid=[], phasemax=None, phasemin=None, phimax=None, phimin=None, tmax=None, tmin=None)
evtSelect.select()

evtBin=xEventBinningMCUBE(file_selected_path, ebins=1, outfile=file_selected_cube_path, evfile=file_selected_path,
                          emax=10.0,nypix=256, ebinfile=None, phasebins=50,ebinalg='LIN',
                          xref=None,phibins=75,nxpix=256,tbins=100,proj='TAN',tstart=None,tbinalg='LIN',algorithm='MCUBE',mc=False,binsz=2.5,yref=None,tbinfile=None,emin=1.0,tstop=None)
evtBin.bin_()

binModulation = xBinnedModulationCube(file_selected_cube_path)
binModulation.plot(show=False,xsubplot=1)
for fit in binModulation.fit_results:
    print fit
    angle      = fit.phase
    angle_err  = fit.phase_error

    visibility = fit.visibility

    scale=10.
    dx1=visibility/scale*numpy.cos(angle+10*angle_err)
    dy1=visibility/scale*numpy.sin(angle+10*angle_err)

    dx2=visibility/scale*numpy.cos(angle-10*angle_err)
    dy2=visibility/scale*numpy.sin(angle-10*angle_err)
Example #15
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'))
Example #16
0
def run():
    outfile = PIPELINE.chandra2ximpol(
        INPUT_FILE_PATH, acis=ACIS, seed=SEED, duration=TIME, regfile=REG_FILE_PATH, configfile=CONFIG_FILE_PATH
    )
    cmap_file = PIPELINE.xpbin(outfile, algorithm=ALGORITHM[1], nxpix=512, nypix=512, binsz=1.25)
    # outfile = PIPELINE.xpselect(outfile, ra=RA, dec=DEC, rad=RAD)
    # outfile = PIPELINE.xpselect(outfile, ra=RA_CORE, dec=DEC_CORE, rad=RAD_PSF)
    outfile = PIPELINE.xpselect(outfile, ra=RA_JET, dec=DEC_JET, rad=RAD_PSF)
    mod_file = PIPELINE.xpbin(outfile, algorithm=ALGORITHM[0], emin=EMIN, emax=EMAX, ebins=EBINS)

    mod_cube = xBinnedModulationCube(mod_file)
    mod_cube.fit()

    event = xEventFile(outfile)
    energy = event.event_data["ENERGY"]
    src_id = event.event_data["MC_SRC_ID"]
    jet_tot = 0
    core_tot = 0
    bkg_tot = 0
    mu_tot = 0.0
    for i in range(0, len(mod_cube.emax)):
        mask_jet = (energy > mod_cube.emin[i]) * (energy < mod_cube.emax[i]) * (src_id == 1)
        mask_bkg = (energy > mod_cube.emin[i]) * (energy < mod_cube.emax[i]) * (src_id == 0)
        mask_core = (energy > mod_cube.emin[i]) * (energy < mod_cube.emax[i]) * (src_id == 2)
        cnts_jet = len(energy[mask_jet])
        cnts_bkg = len(energy[mask_bkg])
        cnts_core = len(energy[mask_core])
        jet_tot += cnts_jet
        bkg_tot += cnts_bkg
        core_tot += cnts_core
        cnts_tot = cnts_jet + cnts_bkg + cnts_core
        mu_tot += mod_cube.effective_mu[i] * cnts_tot
        mdp = mdp99(mod_cube.effective_mu[i], cnts_jet, cnts_bkg + cnts_core)
        logger.info(
            "%.2f--%.2f keV: %d jet counts (%.1f%%) in %d s, mu %.3f, MDP %.2f%%"
            % (
                mod_cube.emin[i],
                mod_cube.emax[i],
                cnts_jet,
                100 * cnts_jet / float(cnts_tot),
                TIME,
                mod_cube.effective_mu[i],
                100 * mdp,
            )
        )
        # print cnts_jet, cnts_bkg, cnts_core
    if EBINS > 1:
        cnts_tot = jet_tot + bkg_tot + core_tot
        mu_tot /= cnts_tot
        mdp_tot = mdp99(mu_tot, jet_tot, bkg_tot + core_tot)
        logger.info(
            "%.2f--%.2f keV: %d jet counts (%.1f%%) in %d s, mu %.3f, MDP %.2f%%"
            % (
                mod_cube.emin[0],
                mod_cube.emax[len(mod_cube.emax) - 1],
                jet_tot,
                100 * jet_tot / float(cnts_tot),
                TIME,
                mu_tot,
                100 * mdp_tot,
            )
        )
        # print jet_tot, bkg_tot, core_tot
    if PLOT is True:
        plot(cmap_file)
        plt.show()
    logger.info("Done.")
Example #17
0
def calcMDP(plot=False):
    mdp_file = open(MDP_OUTPUT_FILE,'w')
    mdp_file.write('#Simulation time %s sec \n'%SIM_DURATION)
    mdp_file.write('#Phase Ave delta phase Mean energy  delta energy mdp99\n')
    nebula_mcube_file = xBinnedModulationCube(NEBULA_MCUBE_FILE_PATH)
    nebula_counts = nebula_mcube_file.counts
    nebula_mdp =  nebula_mcube_file.mdp99
    txt = "Pulsar phase\t Emin - Emax\t Pulsar counts\t Nebula counts\t MDP\n"
    MDP99_PULSAR = []
    phase = []
    phase_err = [] 
    for i, (_min, _max) in enumerate(PHASE_BINS):
            #zip(PHASE_BINS[:-1],PHASE_BINS[1:])):

        pulse_diff = numpy.fabs(_max -_min)
        _phase_ave = 0.5*(_min + _max)
        phase.append(_phase_ave)
        _phase_err = 0.5*(_max - _min)
        phase_err.append(_phase_err)
        
        pulsar_phase_mcube_file = xBinnedModulationCube(_mcube_file_path(i))
        
        
        pulsar_emean = pulsar_phase_mcube_file.emean
        for j, _energy_mean in enumerate(pulsar_emean):
            pulsar_emin = pulsar_phase_mcube_file.emin[j]
            pulsar_emax = pulsar_phase_mcube_file.emax[j]
            pulsar_e_err = 0.5*(pulsar_emax-pulsar_emin)
            
            pulsar_phase_counts = pulsar_phase_mcube_file.counts[j]
            pulsar_mdp = pulsar_phase_mcube_file.mdp99[j]
            #scale the nebula counts for the time used for the pulsar phase
            scaled_nebula_counts = pulse_diff*nebula_counts[j]
        
            count_sqrt = numpy.sqrt(pulsar_phase_counts + scaled_nebula_counts)
       
            eff_mu_pulsar =  pulsar_phase_mcube_file.effective_mu[j]
            
            mdp = 4.292/eff_mu_pulsar*count_sqrt/pulsar_phase_counts
            MDP99_PULSAR.append(100*mdp)
            _data = (_phase_ave, _phase_err, _energy_mean, pulsar_e_err, pulsar_e_err, mdp)
            
            _fmt = ('%.4e   ' * len(_data)).strip()
            _fmt = '%s\n' % _fmt
            _line = _fmt % _data
            mdp_file.write(_line)
           
            #txt += "%s\t %s - %s\t %s\t %s\t %.3f\n"%(PHASE_BINS[i], pulsar_emin[0], pulsar_emax[0], pulsar_phase_counts[0], scaled_nebula_counts[0], 100*mdp)
        
    MDP99_PULSAR = numpy.array(MDP99_PULSAR)
    PHASE = numpy.array(phase)
    mdp_file.close()
    if plot:
        scale_factor = 10
        sim_label = 'XIPE %s ks' % (SIM_DURATION*scale_factor/1000.)
        lc_label = 'Light curve'
        plt.errorbar(PHASE, MDP99_PULSAR*(1/numpy.sqrt(10)),xerr=phase_err, label=sim_label,fmt='o')
        pl_normalization_spline.plot(scale=10., show=False,
                                color='lightgray',label=lc_label)
        plt.ylabel('MDP 99\%')
        plt.legend()
        plt.savefig('crab_complex_mdp_nonimaging_%i.png'%(SIM_DURATION*scale_factor/1000.))
      
        #plt.show()
    print txt
def plot(angle=False):
    spin05_pol_degree_spline, spin05_pol_angle_spline = buildspline(0.5)
    spin05_mcube =  xBinnedModulationCube(fetch_mcubepath(0.5))

    spin09_pol_degree_spline, spin09_pol_angle_spline = buildspline(0.9)
    spin09_mcube =  xBinnedModulationCube(fetch_mcubepath(0.9))

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

    spin05_mcube.fit()
    spin09_mcube.fit()
    spin998_mcube.fit()
    
    spin05_fit_results = spin05_mcube.fit_results[0]
    spin09_fit_results = spin09_mcube.fit_results[0]
    spin998_fit_results = spin998_mcube.fit_results[0]

    
    plt.figure('Polarization degree')
    
    spin05_mcube.plot_polarization_degree(show=False, color='blue')
    
    spin05_pol_degree_spline.plot(color='lightblue',label='Spin 0.5', show=False)

    spin998_mcube.plot_polarization_degree(show=False, color='red')
    spin998_pol_degree_spline.plot(color='lightsalmon',label='Spin 0.998', show=False)
    
    plt.figtext(0.2, 0.85,'XIPE %s ks'%((SIM_DURATION*NUM_RUNS)/1000.),size=18)
    plt.ylim([0.00,0.045])
    plt.xlim([1,10])
    plt.legend()
    plt.show()

    if angle:
        plt.figure('Polarization angle')
    
        spin05_mcube.plot_polarization_angle(show=False, degree=True, color='blue')
        #Converting to degrees
        spin05_y = numpy.degrees(spin05_pol_angle_spline.y)
        energy = spin05_pol_angle_spline.x
        
        plt.plot(energy, spin05_y, color='lightblue',label='Spin 0.5')


        spin09_mcube.plot_polarization_angle(show=False, degree=True, color='gray')
        #Converting to degrees
        spin09_y = numpy.degrees(spin09_pol_angle_spline.y)
        energy = spin09_pol_angle_spline.x
        
        plt.plot(energy, spin09_y, color='lightgray',label='Spin 0.9')
    

        spin998_mcube.plot_polarization_angle(show=False, degree=True, color='red')
        spin998_y = numpy.degrees(spin998_pol_angle_spline.y)
        energy = spin998_pol_angle_spline.x
        
        plt.plot(energy, spin998_y, color='lightsalmon',label='Spin 0.998')
        #spin998_pol_angle_spline.plot(color='lightsalmon',label='Spin 0.998', show=False)
    
        plt.figtext(0.2, 0.85,'XIPE %s ks'%((SIM_DURATION*NUM_RUNS)/1000.),size=18)
        plt.xlim([1,10])
        plt.ylim([40,200])
        plt.legend()
        plt.show()
from ximpol.evt.binning import xBinnedModulationCube
from ximpol.utils.matplotlib_ import pyplot as plt
from ximpol.config.lamp_post_accreting_bh_XTE import pol_degree, pol_angle


CFG_FILE = os.path.join(XIMPOL_CONFIG, 'lamp_post_accreting_bh_XTE.py')
DURATION = 100000.
E_BINNING = [1., 2., 3., 4., 5., 7., 10.]
SEED = 0

pipeline = xPipeline(clobber=False)
evt_file_path = pipeline.xpobssim(configfile=CFG_FILE, duration=DURATION, seed=SEED)
pipeline.xpbin(evt_file_path, algorithm='CMAP')
mcube_file_path = pipeline.xpbin(evt_file_path, algorithm='MCUBE',
                                 ebinalg='LIST', ebinning=E_BINNING)

mcube = xBinnedModulationCube(mcube_file_path)
mcube.fit()

fig = plt.figure('Polarization degree')
mcube.plot_polarization_degree(show=False, label='Data')
pol_degree.plot(show=False, label='Model', linestyle='dashed')
plt.legend(bbox_to_anchor=(0.30, 0.95))
plt.axis([1, 10, None, None])
fig = plt.figure('Polarization angle')
mcube.plot_polarization_angle(show=False, label='Data')
pol_angle.plot(show=False, label='Model', linestyle='dashed')
plt.legend(bbox_to_anchor=(0.95, 0.95))
plt.axis([1, 10, None, None])
plt.show()
Example #20
0
def analyze():
    """Analyze the data.
    """
    logger.info('Opening output file %s...' % ANALYSIS_FILE_PATH)
    analysis_file = open(ANALYSIS_FILE_PATH, 'w')
    _nevents=[]
    for i, (_min, _max) in enumerate(zip(PHASE_BINNING[:-1],
                                         PHASE_BINNING[1:])):
        _nevents.append(fits.open(_sel_file_path(i))['EVENTS'].header['NAXIS2'])
        logger.info("PHASE BIN %d [%.1f-%.1f] - EVENTS = %d" %(i,_min,_max,_nevents[i]))        
        pass
    out_phase=numpy.min(_nevents)
    for i, (_min, _max) in enumerate(zip(PHASE_BINNING[:-1],
                                         PHASE_BINNING[1:])):
        _mcube = xBinnedModulationCube(_mcube_file_path(i))
        _mcube.fit()
        _fit_results = _mcube.fit_results[0]
        _phase = 0.5*(_min + _max)
        _phase_err = 0.5*(_max - _min)
        _pol_deg = _fit_results.polarization_degree
        _pol_deg_err = _fit_results.polarization_degree_error
        _pol_angle = _fit_results.phase
        _pol_angle_err = _fit_results.phase_error
        if (_nevents[i]-out_phase)>0:
            _factor=(_nevents[i])/(_nevents[i]-out_phase)
            print '------->',_nevents[i],out_phase,_nevents[i]-out_phase,_factor
            _pol_deg*=_factor
            _pol_deg_err*=_factor
        else:
            _pol_deg=1e-6
            _pol_deg_err=1e-6
            pass
        if _pol_deg>1.0: _pol_deg=1.0
        #_total_px=_pol_deg*numpy.cos(_pol_angle)
        #_total_py=_pol_deg*numpy.sin(_pol_angle)
        #_nebula_px=0.157*numpy.cos(numpy.radians(161.1))
        #_nebula_py=0.157*numpy.sin(numpy.radians(161.1))
        #_pulsar_px=_total_px-_nebula_px
        #_pulsar_py=_total_py-_nebula_py
        #_pol_angle=numpy.arctan2(_pulsar_py,_pulsar_px)
        #_pol_deg=numpy.sqrt(_pulsar_px*_pulsar_px+_pulsar_py*_pulsar_py)
        
        if False:
            _spec_fitter = PIPELINE.xpxspec(_pha1_file_path(i), plot=False)
            (_index, _index_err), (_norm, _norm_err) = _spec_fitter.fit_parameters()
            # The division by the phase interval is a workaround and we should
            # keep track of that in xpselect.
            _norm /= (_max - _min)
            _norm_err /= (_max - _min)
        else:
            _norm=0.0
            _norm_err=0.0
            _index=0.0
            _index_err=0.0
            pass
        
        _data = (_phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,
                 _pol_angle_err, _index, _index_err, _norm, _norm_err)
        _fmt = ('%.4e   ' * len(_data)).strip()
        _fmt = '%s\n' % _fmt
        _line = _fmt % _data
        analysis_file.write(_line)
        ### Plot the cmap with the arrow...
        full_map = xBinnedMap(_cmap_file_path(i))
        full_map.image.vmin=0
        full_map.image.vmax=10000        
        fig_map = full_map.plot(show=False)
        fig_map.show_circles(RA, DEC, RAD_ANA/60.0, lw=1)
                
        _plot_arrows(ra=RA,dec=DEC,rad=RAD_ANA/60.,
                     angle=_phase,angle_error=_phase_err,
                     degree=_pol_deg,fig=fig_map,color='b')
        
        fig_map_file=_cmap_file_path(i).replace('.fits','.png')        
        print 'saving map in...',fig_map_file
        fig_map.save(fig_map_file)
        ###
    analysis_file.close()
Example #21
0
E_BINNING = [2.,3.,5.,8.]
SIM_NUM = 10

pol_degree_array = numpy.empty([SIM_NUM, len(E_BINNING)])
pol_degree_error_array = numpy.empty([SIM_NUM, len(E_BINNING)])
pol_angle_array = numpy.empty([SIM_NUM, len(E_BINNING)])
pol_angle_error_array = numpy.empty([SIM_NUM, len(E_BINNING)])

pipeline = xPipeline(clobber=True)
for j in range(0, SIM_NUM):
    SEED = j
    evt_file_path = pipeline.xpobssim(configfile=CFG_FILE, duration=TIME, seed=SEED)
    #pipeline.xpbin(evt_file_path, algorithm='CMAP')
    mod_cube_file_path = pipeline.xpbin(evt_file_path, algorithm='MCUBE',
                                        ebinalg='LIST', ebinning=E_BINNING)
    mod_cube = xBinnedModulationCube(mod_cube_file_path)
    mod_cube.fit()
    pol_degree_array[j,:] = numpy.array([r.polarization_degree for
                                         r in mod_cube.fit_results])
    pol_degree_error_array[j,:] = numpy.array([r.polarization_degree_error for
                                               r in mod_cube.fit_results])
    pol_angle_array[j,:] = numpy.array([numpy.degrees(r.phase) for
                                        r in mod_cube.fit_results])
    pol_angle_error_array[j,:] = numpy.array([numpy.degrees(r.phase_error) for
                                              r in mod_cube.fit_results])

for i in range(0, len(mod_cube.emax)):
    cnts = mod_cube.counts[i]
    logger.info('%.2f--%.2f keV: %d counts in %d s, mu %.3f, MDP %.2f%%' %\
            (mod_cube.emin[i], mod_cube.emax[i], mod_cube.counts[i], TIME,
             mod_cube.effective_mu[i], 100*mod_cube.mdp99[i]))
Example #22
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'))
Example #23
0
                            phibins=75,
                            nxpix=256,
                            tbins=100,
                            proj='TAN',
                            tstart=None,
                            tbinalg='LIN',
                            algorithm='MCUBE',
                            mc=False,
                            binsz=2.5,
                            yref=None,
                            tbinfile=None,
                            emin=1.0,
                            tstop=None)
evtBin.bin_()

binModulation = xBinnedModulationCube(file_selected_cube_path)
binModulation.plot(show=False, xsubplot=1)
for fit in binModulation.fit_results:
    print fit
    angle = fit.phase
    angle_err = fit.phase_error

    visibility = fit.visibility

    scale = 10.
    dx1 = visibility / scale * numpy.cos(angle + 10 * angle_err)
    dy1 = visibility / scale * numpy.sin(angle + 10 * angle_err)

    dx2 = visibility / scale * numpy.cos(angle - 10 * angle_err)
    dy2 = visibility / scale * numpy.sin(angle - 10 * angle_err)