Ejemplo n.º 1
0
 def plot_time_course(self, data, mode='boolean', fontsize=16):
     # TODO sort columnsi alphabetically
     # FIXME: twiny labels are slightly shifted
     # TODO flip 
     if mode == 'boolean':
         cm = pylab.get_cmap('gray')
         pylab.clf() 
         data = pd.DataFrame(data).fillna(0.5)
         pylab.pcolor(data, cmap=cm, vmin=0, vmax=1, 
             shading='faceted')
         pylab.colorbar()
         ax1 = pylab.gca()
         ax1.set_xticks([])
         Ndata = len(data.columns)
         ax1.set_xlim(0, Ndata)
         ax = pylab.twiny()
         ax.set_xticks(pylab.linspace(0.5, Ndata+0.5, Ndata ))
         ax.set_xticklabels(data.columns, fontsize=fontsize, rotation=90)
         times = list(data.index)
         Ntimes = len(times)
         ax1.set_yticks([x+0.5 for x in times])
         ax1.set_yticklabels(times[::-1],  
                 fontsize=fontsize)
         pylab.sca(ax1)
     else:
         print('not implemented')
Ejemplo n.º 2
0
    def plotsim(self, experiments=None, fontsize=16, vmin=0, vmax=1, cmap='gray'):
        """

        :param experiments: if None, shows the steady state for each experiment and species
            if provided, must be a valid experiment name (see midas.experiments attribute)
            in which case, for that particular experiment, the steady state and all previous
            states are shown for each species.


        A simulation must be performed using :meth:`simulate`
        ::

            # those 2 calls are identical
            s.plotsim(experiments=8)
            s.plotsim(experiments=8)
            # This plot the steady states for all experiments
            s.plotsim()

        """
        # This is for all experiments is experiments is None
        cm = pylab.get_cmap(cmap)
        pylab.clf()

        if experiments is None: # takes the latest (steady state) of each experiments
            data = pd.DataFrame(self.debug_values[-1]).fillna(0.5)
        else:
            exp_name = self.midas.experiments.ix[experiments].name
            index_exp = list(self.midas.experiments.index).index(exp_name)

            data = [(k, [self.debug_values[i][k][index_exp] for i in range(0, len(self.debug_values))])
                    for k in self.debug_values[0].keys()]
            data = dict(data)
            data = pd.DataFrame(data).fillna(0.5)
            data = data.ix[data.index[::-1]]
        self.dummy = data

        pylab.pcolor(data, cmap=cm, vmin=vmin, vmax=vmax,
                shading='faceted', edgecolors='gray')
        pylab.colorbar()
        ax1 = pylab.gca()
        ax1.set_xticks([])
        Ndata = len(data.columns)
        ax1.set_xlim(0, Ndata)
        ax1.set_ylim(0, len(data))
        ax = pylab.twiny()

        # FIXME seems shifted. could not fix it xticklabels seems to reset the position of the ticks
        xr = pylab.linspace(0.5, Ndata-1.5, Ndata)
        ax.set_xticks(xr)
        ax.set_xticklabels(data.columns, fontsize=fontsize, rotation=90)
        times = list(data.index)
        Ntimes = len(times)
        ax1.set_yticks([x+0.5 for x in times])
        ax1.set_yticklabels(times[::-1],
                    fontsize=fontsize)
        pylab.sca(ax1)
        #pylab.title("Steady state for all experiments(x-axis)\n\n\n\n")
        pylab.tight_layout()
Ejemplo n.º 3
0
def xaxissfrlog(ax1, dy=0):
    x1, x2 = ax1.get_xlim()
    ax2 = pl.twiny()
    #xa=getsfrfromlir(10.**x1)
    #xb=getsfrfromlir(10.**x2)
    #print x1, x2
    #print xa, xb
    ax2.set_xlim(getsfrfromlir(10.**x1), getsfrfromlir(10.**x2))
    ax2.set_xscale('log')
Ejemplo n.º 4
0
    s = shelve.open("AR_many_runs_shelf",flag='r')
    data.append(s[m].__dict__['sigv50k_estimates'])
    s.close()
plt.boxplot(data)

plt.axvline(2.5,color="grey")
plt.axvline(4.5,color="grey")
plt.gcf().subplots_adjust(left=0.12, bottom=0.2)
plt.ylabel(r"$\hat{\sigma}_{v,50k}$",rotation=90,fontsize=24)

plt.xticks([1,2,3,4], [r"$500$",r"$5k$",r"$0.6$",r"$0.9$"],fontsize=20,rotation=90)
plt.xlabel("tuning parameter value", fontsize=20)

plt.tick_params(axis='x', which='both', length=0)

plt.twiny()
plt.xlim(0,5)
plt.xticks([1,3,4.5], ["BEM","OEM","IOEM"], fontsize=20)
plt.tick_params(axis='x', which='both', length=0)

plt.savefig("sigv_50k.png")
plt.close()

#sigw

plt.rcParams.update({'font.size': 20})
plt.rcParams['xtick.major.pad']='12'
plt.axis([0,5,0,5])
plt.axhline(1)
data = []
Ejemplo n.º 5
0
    def candplot1(self, plotcands={}, save=0):
        """ Uses results of bispectrum results (calculated in do_search and find_candidates) to produce summary plot per candidate.
        This is a "tier 1" plot, since it only uses info available to bispectrum search algorithm.
        Requires do_search and find_candidates to be run first to build "master" objects.
        Candidate should be dictionary with keys of beam location and value of a list of 3-element lists (dtind, int, dmbin).
        save defines whether plots are also saved.
        """

        print 'Building Tier 1 candidate plot.'

        if n.array([len(plotcands[beam]) for beam in plotcands.keys()]).sum() == 0:
            print 'No candidates available...'
            return

        figi = 1
        for beam in plotcands.keys():
            if len(plotcands[beam]) == 0:
                continue
            if (n.ndim(plotcands[beam]) != 2) | (n.shape(plotcands[beam])[1] != 3):
                print 'Candidate does not seem to be in proper format. Skipping.'
                continue

            for cand in plotcands[beam]:
                # find island containing candidate
                for island in self.islands[beam]:
                    if n.any([n.all(member == cand) for member in island]):   # if any member of island that has all three coords the same as plotcand, break
                        break

                # next find snr for all candidates in island
                islandind = []
                for i in range(len(island)):
                    ww = n.where( (n.array(self.masterloc[beam])[:,0]==island[i,0]) & (n.array(self.masterloc[beam])[:,1]==island[i,1]) & (n.array(self.masterloc[beam])[:,2]==island[i,2]) )
                    islandind.append(ww[0][0])
                loc = n.array(self.masterloc[beam])[islandind]
                snr = n.array(self.masterprop[beam])[islandind, 0]

                # then plot snr as function of dmind and dtind for island
                fixed_dt = n.where(loc[:,0] == cand[0])
                fixed_dm = n.where(loc[:,2] == cand[2])
                dmdist = n.squeeze(n.array(self.dmarr)[loc[fixed_dt, 2]])   # seems to have superfluous axis...?
                dmsnr = snr[fixed_dt]
                dtdist = n.squeeze(n.array(self.timescales)[loc[fixed_dm][:, 0]])   # seems to have superfluous axis...?
                dtsnr = snr[fixed_dm]

                # find master index of candidate
                ww = n.where([n.all(mastercand == cand) for mastercand in self.masterloc[beam]])[0][0]

                # plot candidate info
                p.figure(figi)
                p.clf()

                p.subplot(221, axisbg='white')
                p.title('Candidate @ Tier 1')
                p.xticks([])
                p.yticks([])
                p.text(0.1, 0.8, self.datafile, fontname='sans-serif')
                beamra = n.round(beam, 3)[0]
                beamdec = n.round(beam, 3)[1]
                p.text(0.1, 0.6, 'Beam: ' + str(beamra) + ', ' + str(beamdec) + ', dt: ' + str(self.timescales[cand[0]]), fontname='sans-serif')
                p.text(0.1, 0.4, 'Integration: ' + str(cand[1]) + ', DM: ' + str(self.dmarr[cand[2]]), fontname='sans-serif')
                p.text(0.1, 0.2, 'SNR: ' + str(n.round(self.masterprop[beam][ww][0], 1)), fontname='sans-serif')

                p.subplot(222)
                p.plot(dmdist, dmsnr, 'b.', clip_on=False, label='DM at peak dt')
                p.xlabel('DM (pc/cm3)')
                p.ylabel('SNR')
                p.twiny()
                p.plot(dtdist, dtsnr, 'r+', clip_on=False, label='dt at peak DM')
                p.xlabel('dt (ints)')
                p.subplot(223)
                p.plot(self.masterdata[beam][ww][0], 'b.', label='Mean B')
                p.xlabel('Integration')
                p.ylabel('Mean, Std of Bispectra')
                p.twinx()
                p.plot(self.masterdata[beam][ww][1], 'r.', label='Std B')
                p.subplot(224)
                dataph = n.rot90(self.masterdata[beam][ww][2])
                sh = dataph.shape
                im = p.imshow(dataph, aspect='auto', origin='upper', interpolation='nearest', extent=(0, sh[1], 0, sh[0]))
                p.colorbar()
                p.plot(self.obs.dmtrack0[cand[2]][0], self.obs.dmtrack0[cand[2]][1],'k.')  # reference dispersed track
                p.xlabel('Integration')
                p.ylabel('Channel')
                if self.datatype == 'mir':   # casapy doesn't get along with recent matplotlib stuff
                    p.tight_layout()
                if save:
                    p.savefig(self.fileroot + '_sc' + str(self.scan) + 'sp' + str(self.spw[0]) + 'i' + str(self.startints[0]) + '_tier1_' + str(figi) + '.png')
                figi += 1
Ejemplo n.º 6
0
    maxrange = max(mid - yl, yh - mid)
    yl = mid - maxrange
    yh = mid + maxrange*0.8

    # 
    targettime = slope**(target_depth + diff)
    print('Exposure time to hit nominal depth:', targettime)
    plt.axvline(targettime, color='k', alpha=0.1)
    plt.text(targettime, (yl+mid)/2, '%.1f s' % targettime, color='k', ha='left', va='center')
    
    plt.xscale('log')
    xt = [10, 20, 50, 100, 200, 300, 400, 500]
    plt.xticks(xt, ['%i'%t for t in xt])
    plt.axis([xl,xh,yl,yh])
    
    plt.twiny()
    bins = np.arange(20., 25., 0.05)
    n,b,p = plt.hist(extdepth[notbad], bins=bins, orientation='horizontal',
                     histtype='step', color='b')
    #plt.xlim(0, np.max(n)*4)
    plt.xlim(np.max(n)*4, 0)
    plt.ylim(yl,yh)
    plt.xticks([])
    
    plt.legend([p2[0]], ['+- 0.05 mag'], loc='lower right')
    plt.title(tt)
    ps.savefig()



    plt.clf()
Ejemplo n.º 7
0
def plotPhotometry(imgsources,
                   refsources,
                   matches,
                   prefix,
                   band=None,
                   zp=None,
                   delta=False,
                   referrs=None,
                   refstargal=None,
                   title=None,
                   saveplot=True,
                   format='png'):
    print('%i ref sources' % len(refsources))
    print('%i image sources' % len(imgsources))
    print('%i matches' % len(matches))

    # In the "matches" list:
    #    m.first  is catalog
    #    m.second is image

    # In this function, the "m" prefix stands for "matched",
    # "u" stands for "unmatched".

    # *sigh*, turn these into Python lists, so we have the "index" function.
    refsources = [s for s in refsources]
    imgsources = [s for s in imgsources]

    # Now we build numpy int arrays for indexing into the "refsources" and
    # "imgsources" arrays.
    MR = []
    MI = []
    for m in matches:
        try:
            i = refsources.index(m.first)
        except ValueError:
            print('Match list reference source ID', m.first.getSourceId(),
                  'was not in the list of reference stars')
            continue
        try:
            j = imgsources.index(m.second)
        except ValueError:
            print('Match list source ID', m.second.getSourceId(),
                  'was not in the list of image sources')
            continue
        MR.append(i)
        MI.append(j)
    MR = np.array(MR)
    MI = np.array(MI)

    # Build numpy boolean arrays for indexing the unmatched stars.
    UR = np.ones(len(refsources), bool)
    UR[MR] = False
    UI = np.ones(len(imgsources), bool)
    UI[MI] = False

    def flux2mag(f):
        return -2.5 * np.log10(f)

    refmag = np.array([flux2mag(s.getPsfInstFlux()) for s in refsources])
    imgflux = np.array([s.getPsfInstFlux() for s in imgsources])
    imgfluxerr = np.array([s.getPsfInstFluxErr() for s in imgsources])

    # Cut to fluxes that aren't silly and get mags of matched sources.
    okflux = (imgflux[MI] > 1)
    MI = MI[okflux]
    MR = MR[okflux]

    mimgflux = imgflux[MI]
    mimgmag = flux2mag(mimgflux)
    mimgmagerr = abs(2.5 / np.log(10.) * imgfluxerr[MI] / mimgflux)
    mrefmag = refmag[MR]

    # Get mags of unmatched sources.
    uimgflux = imgflux[UI]
    okflux = (uimgflux > 1)
    uimgmag = flux2mag(uimgflux[okflux])
    urefmag = refmag[UR]

    # Legend entries:
    pp = []
    pl = []

    plt.clf()
    imag = np.append(mimgmag, uimgmag)

    mrefmagerr = None
    if referrs is not None:
        referrs = np.array(referrs)
        mrefmagerr = referrs[MR]

    if refstargal:
        assert (len(refstargal) == len(refsources))
        refstargal = np.array(refstargal).astype(bool)
        ptsets = [(np.logical_not(refstargal[MR]), 'g', 'Matched galaxies',
                   10), (refstargal[MR], 'b', 'Matched stars', 12)]

    else:
        ptsets = [(np.ones_like(mrefmag).astype(bool), 'b', 'Matched sources',
                   10)]

    for I, c, leg, zo in ptsets:
        if delta:
            dm = mimgmag[I] - mrefmag[I] + zp
            xi = mrefmag[I]
            yi = dm
            dx = mrefmagerr
            dy = mimgmagerr
        else:
            xi = mimgmag[I]
            yi = mrefmag[I]
            dx = mimgmagerr
            dy = mrefmagerr

        p1 = plt.plot(xi, yi, '.', color=c, mfc=c, mec=c, alpha=0.5, zorder=zo)
        if dx is None or dy is None:
            # errorbars
            xerr, yerr = None, None
            if dx is not None:
                xerr = dx[I]
            if dy is not None:
                yerr = dy[I]
            plt.errorbar(xi,
                         yi,
                         xerr=xerr,
                         yerr=yerr,
                         ecolor=c,
                         fmt=None,
                         zorder=zo)
        else:
            # get the current axis
            ca = plt.gca()
            # add error ellipses
            for j, i in enumerate(np.flatnonzero(I)):
                a = Ellipse(xy=np.array([xi[j], yi[j]]),
                            width=dx[i] / 2.,
                            height=dy[i] / 2.,
                            alpha=0.5,
                            fill=True,
                            ec=c,
                            fc=c,
                            zorder=zo)
                ca.add_artist(a)
        pp.append(p1)
        pl.append(leg)

    if delta:
        m = max(abs(dm))
        plt.axis([np.floor(min(refmag)) - 0.5, np.ceil(max(refmag)), -m, m])
    else:
        plt.axis([
            np.floor(min(imag)) - 0.5,
            np.ceil(max(imag)),
            np.floor(min(refmag)) - 0.5,
            np.ceil(max(refmag))
        ])
    ax = plt.axis()

    if not delta:
        # Red tick marks show unmatched img sources
        dy = (ax[3] - ax[2]) * 0.05
        y1 = np.ones_like(uimgmag) * ax[3]
        p2 = plt.plot(np.vstack((uimgmag, uimgmag)),
                      np.vstack((y1, y1 - dy)),
                      'r-',
                      alpha=0.5)
        p2 = p2[0]
        # Blue tick marks show matched img sources
        y1 = np.ones_like(mimgmag) * ax[3]
        p3 = plt.plot(np.vstack((mimgmag, mimgmag)),
                      np.vstack((y1 - (0.25 * dy), y1 - (1.25 * dy))),
                      'b-',
                      alpha=0.5)
        p3 = p3[0]
        # Red ticks for unmatched ref sources
        dx = (ax[1] - ax[0]) * 0.05
        x1 = np.ones_like(urefmag) * ax[1]
        p4 = plt.plot(np.vstack((x1, x1 - dx)),
                      np.vstack((urefmag, urefmag)),
                      'r-',
                      alpha=0.5)
        p4 = p4[0]
        # Blue ticks for matched ref sources
        x1 = np.ones_like(mrefmag) * ax[1]
        p5 = plt.plot(np.vstack((x1 - (0.25 * dx), x1 - (1.25 * dx))),
                      np.vstack((mrefmag, mrefmag)),
                      'b-',
                      alpha=0.5)
        p5 = p5[0]

    if zp is not None:
        if delta:
            pzp = plt.axhline(0, linestyle='--', color='b')
        else:
            X = np.array([ax[0], ax[1]])
            pzp = plt.plot(X, X + zp, 'b--')
        pp.append(pzp)
        pl.append('Zeropoint')

    # reverse axis directions.
    if delta:
        plt.axis([ax[1], ax[0], ax[2], ax[3]])
    else:
        plt.axis([ax[1], ax[0], ax[3], ax[2]])

    if band is not None:
        reflabel = 'Reference catalog: %s band (mag)' % band
    else:
        reflabel = 'Reference catalog mag'

    if delta:
        plt.xlabel(reflabel)
        plt.ylabel('Instrumental - Reference (mag)')
        fn = prefix + '-dphotom.' + format

        if zp is not None:
            # Make the plot area smaller to fit the twin axis
            pos = plt.gca().get_position()
            ll = pos.min
            sz = pos.size
            plt.gca().set_position(pos=[ll[0], ll[1], sz[0], sz[1] - 0.05])
            # Put the title up top (otherwise it follows the axis)
            if title is not None:
                plt.figtext(0.5,
                            0.96,
                            title,
                            ha='center',
                            va='top',
                            fontsize='large')
                title = None

            plt.twiny()

            # Red tick marks show unmatched img sources
            if zp is not None:
                dy = (ax[3] - ax[2]) * 0.05
                y1 = np.ones_like(uimgmag) * ax[3]
                p2 = plt.plot(np.vstack((uimgmag, uimgmag)) + zp,
                              np.vstack((y1, y1 - dy)),
                              'r-',
                              alpha=0.5)
                p2 = p2[0]
                # Blue tick marks show matched img sources
                y1 = np.ones_like(mimgmag) * ax[3]
                p3 = plt.plot(np.vstack((mimgmag, mimgmag)) + zp,
                              np.vstack((y1 - (0.25 * dy), y1 - (1.25 * dy))),
                              'b-',
                              alpha=0.5)
                p3 = p3[0]
            # Red ticks for unmatched ref sources
            y1 = np.ones_like(urefmag) * ax[2]
            p4 = plt.plot(np.vstack((urefmag, urefmag)),
                          np.vstack((y1, y1 + dy)),
                          'r-',
                          alpha=0.5)
            p4 = p4[0]
            # Blue ticks for matched ref sources
            y1 = np.ones_like(mrefmag) * ax[2]
            p5 = plt.plot(np.vstack((mrefmag, mrefmag)),
                          np.vstack((y1 + (0.25 * dy), y1 + (1.25 * dy))),
                          'b-',
                          alpha=0.5)
            p5 = p5[0]

            plt.xlim(ax[1] - zp, ax[0] - zp)
            plt.xlabel('Instrumental mag')

        legloc = 'lower right'

    else:
        plt.ylabel(reflabel)
        plt.xlabel('Image instrumental mag')
        fn = prefix + '-photom.' + format
        legloc = 'center right'

    if title is not None:
        plt.title(title)

    pp += [p3, p2]
    pl += ['Matched sources', 'Unmatched sources']
    plt.figlegend(pp,
                  pl,
                  legloc,
                  numpoints=1,
                  prop=FontProperties(size='small'))

    P1 = _output(fn, format, saveplot)

    if delta:
        plt.ylim(-0.5, 0.5)
        fn = prefix + '-dphotom2.' + format
        P2 = _output(fn, format, saveplot)
        if not saveplot:
            P1.update(P2)

    return P1
Ejemplo n.º 8
0
    l0 = ax.axvline(x=0.1, color='k', linestyle=':', linewidth=1.5)
    ax.set_xlim(0., 0.635)
    ax.set_xlabel('Frequency (Hz)')
    
    # setup colorbar axes instance.
    l,b,w,h = ax.get_position().bounds
    cax = fig.add_axes([l+w+0.025, b-0.06, 1.0*w, 0.03])
    
    cb = colorbar(pc, cax=cax, orientation='horizontal') # draw colorbar
    cb.set_label('Spectral Density (m2/Hz/deg)')
    cb.ax.xaxis.set_label_position('top')
    # cb.ax.set_xticks([0.1, 0.3, 0.5, 0.7, 0.9])
    # cb.ax.set_xticklabels([-0.4, -0.2, 0, 0.2, 0.4])

    # top scale wave period
    ax2 = twiny(ax)
    ax2.set_xlim(0., 0.635)
    ax2.xaxis.tick_top()
    # convert (bottom) Hertz to (top scale) seconds (1/Hz)
    Hertz = ax.get_xticks()
    Hertz = [val for val in Hertz if val!=0 ]
    ax2.set_xticks(Hertz)
    s = [round(1./val,2) for val in Hertz]
    ax2.set_xticklabels(s)
    ax2.set_xlabel('Wave Period (sec)')
    
    #######################################
    # print ' ... all, swell, and wind labels'
    ax = fig.add_axes((.1,.875,.4,.10))
    axs.append(ax)
    
Ejemplo n.º 9
0
for i in xrange(40,600,chunk):
    print i, n.average(lsts[i:i+chunk])
    lst_hr = int(n.around(n.average(lsts[i:i+chunk])))
    Tsys_avg = n.sqrt(n.average(Tsys[i:i+chunk]**2, axis=0))
    valid = n.where(Tsys_avg > 213, 1, 0)
    #p.plot(1e3*fqs.compress(valid), Tsys_avg.compress(valid), label='LST = %02dh00'%lst_hr)
    p.plot(chans.compress(valid), Tsys_avg.compress(valid), label='LST = %02dh00'%lst_hr)

if VLINE:
    nums=opts.chan.split('_')
    vlines=[float(v) for v in nums]
    p.vlines(vlines,200,2000,linestyles='dashed')
p.legend(loc='best', fontsize='medium')
p.xlabel(r'${\rm Channel}$', fontsize=16)
if FREQ_AXIS:
    ax=p.twiny()
    ax.plot(freqs,n.ones(len(freqs*1e3)))
    ax.cla()
    ax.set_xlabel(r'${\rm Frequency\ [MHz]}$', fontsize=16)
#p.xlim(125,175)
p.ylim(200,2000)
p.grid()
p.ylabel(r'${\rm T}_{\rm sys}$', fontsize=16)
p.subplots_adjust(0.12, 0.15, .95, .85)

fig_file='Tsys_chan_'+opts.chan
if not opts.output == '':
    fig_file= opts.output + '/' + fig_file
p.savefig(fig_file)
p.show()
Ejemplo n.º 10
0
def plotPhotometry(imgsources, refsources, matches, prefix, band=None,
                   zp=None, delta=False, referrs=None, refstargal=None,
                   title=None,
                   saveplot=True, format='png'):
    print '%i ref sources' % len(refsources)
    print '%i image sources' % len(imgsources)
    print '%i matches' % len(matches)

    # In the "matches" list:
    #    m.first  is catalog
    #    m.second is image

    # In this function, the "m" prefix stands for "matched",
    # "u" stands for "unmatched".

    # *sigh*, turn these into Python lists, so we have the "index" function.
    refsources = [s for s in refsources]
    imgsources = [s for s in imgsources]
    
    # Now we build numpy int arrays for indexing into the "refsources" and
    # "imgsources" arrays.
    MR = []
    MI = []
    for m in matches:
        try:
            i = refsources.index(m.first)
        except ValueError:
            print 'Match list reference source ID', m.first.getSourceId(), 'was not in the list of reference stars'
            continue
        try:
            j = imgsources.index(m.second)
        except ValueError:
            print 'Match list source ID', m.second.getSourceId(), 'was not in the list of image sources'
            continue
        MR.append(i)
        MI.append(j)
    MR = np.array(MR)
    MI = np.array(MI)

    # Build numpy boolean arrays for indexing the unmatched stars.
    UR = np.ones(len(refsources), bool)
    UR[MR] = False
    UI = np.ones(len(imgsources), bool)
    UI[MI] = False

    def flux2mag(f):
        return -2.5*np.log10(f)

    refmag = np.array([flux2mag(s.getPsfFlux()) for s in refsources])
    imgflux = np.array([s.getPsfFlux() for s in imgsources])
    imgfluxerr = np.array([s.getPsfFluxErr() for s in imgsources])

    # Cut to fluxes that aren't silly and get mags of matched sources.
    okflux = (imgflux[MI] > 1)
    MI = MI[okflux]
    MR = MR[okflux]

    mimgflux = imgflux[MI]
    mimgmag  = flux2mag(mimgflux)
    mimgmagerr = abs(2.5 / np.log(10.) * imgfluxerr[MI] / mimgflux)
    mrefmag  = refmag[MR]

    # Get mags of unmatched sources.
    uimgflux = imgflux[UI]
    okflux = (uimgflux > 1)
    uimgmag = flux2mag(uimgflux[okflux])
    urefmag = refmag[UR]

    if False:
        unmatched = [imgsources[i] for i in np.flatnonzero(uimg)]
        uflux = np.array([s.getPsfFlux() for s in unmatched])
        I = np.argsort(-uflux)
        print 'Unmatched image sources, by psf flux:'
        print '# FLUX, X, Y, RA, DEC'
        for i in I:
            u = unmatched[i]
            print u.getPsfFlux(), u.getXAstrom(), u.getYAstrom(), u.getRa(), u.getDec()

        print 'Matched image sources, by psf flux:'
        print '# FLUX, X, Y, RA, DEC'
        for i in mimgi:
            m = imgsources[i]
            print m.getPsfFlux(), m.getXAstrom(), m.getYAstrom(), m.getRa(), m.getDec()

    # Legend entries:
    pp = []
    pl = []

    plt.clf()
    imag = np.append(mimgmag, uimgmag)

    mrefmagerr = None
    if referrs is not None:
        referrs = np.array(referrs)
        mrefmagerr = referrs[MR]

    if refstargal:
        assert(len(refstargal) == len(refsources))
        refstargal = np.array(refstargal).astype(bool)
        ptsets = [ (np.logical_not(refstargal[MR]), 'g', 'Matched galaxies', 10),
                   (refstargal[MR],                 'b', 'Matched stars',    12) ]

    else:
        ptsets = [ (np.ones_like(mrefmag).astype(bool), 'b', 'Matched sources', 10) ]


    for I,c,leg,zo in ptsets:
        if delta:
            dm = mimgmag[I] - mrefmag[I] + zp
            xi = mrefmag[I]
            yi = dm
            dx = mrefmagerr
            dy = mimgmagerr
        else:
            xi = mimgmag[I]
            yi = mrefmag[I]
            dx = mimgmagerr
            dy = mrefmagerr

        p1 = plt.plot(xi, yi, '.', color=c, mfc=c, mec=c, alpha=0.5, zorder=zo)
        if dx is None or dy is None:
            # errorbars
            xerr,yerr = None,None
            if dx is not None:
                xerr = dx[I]
            if dy is not None:
                yerr = dy[I]
            plt.errorbar(xi, yi, xerr=xerr, yerr=yerr, ecolor=c, fmt=None, zorder=zo)
        else:
            # get the current axis
            ca = plt.gca()
            # add error ellipses
            for j,i in enumerate(np.flatnonzero(I)):
                a = Ellipse(xy=np.array([xi[j], yi[j]]),
                            width=dx[i]/2., height=dy[i]/2.,
                            alpha=0.5, fill=True, ec=c, fc=c, zorder=zo)
                ca.add_artist(a)
        pp.append(p1)
        pl.append(leg)

    if delta:
        m = max(abs(dm))
        plt.axis([np.floor(min(refmag))-0.5, np.ceil(max(refmag)),
              -m, m])
    else:
        plt.axis([np.floor(min(imag))-0.5,   np.ceil(max(imag)),
                  np.floor(min(refmag))-0.5, np.ceil(max(refmag))])
    ax = plt.axis()

    if not delta:
        # Red tick marks show unmatched img sources
        dy = (ax[3]-ax[2]) * 0.05
        y1 = np.ones_like(uimgmag) * ax[3]
        p2 = plt.plot(np.vstack((uimgmag, uimgmag)), np.vstack((y1, y1-dy)), 'r-', alpha=0.5)
        p2 = p2[0]
        # Blue tick marks show matched img sources
        y1 = np.ones_like(mimgmag) * ax[3]
        p3 = plt.plot(np.vstack((mimgmag, mimgmag)), np.vstack((y1-(0.25*dy), y1-(1.25*dy))), 'b-', alpha=0.5)
        p3 = p3[0]
        # Red ticks for unmatched ref sources
        dx = (ax[1]-ax[0]) * 0.05
        x1 = np.ones_like(urefmag) * ax[1]
        p4 = plt.plot(np.vstack((x1, x1-dx)), np.vstack((urefmag, urefmag)), 'r-', alpha=0.5)
        p4 = p4[0]
        # Blue ticks for matched ref sources
        x1 = np.ones_like(mrefmag) * ax[1]
        p5 = plt.plot(np.vstack((x1-(0.25*dx), x1-(1.25*dx))), np.vstack((mrefmag, mrefmag)), 'b-', alpha=0.5)
        p5 = p5[0]

    if zp is not None:
        if delta:
            pzp = plt.axhline(0, linestyle='--', color='b')
        else:
            X = np.array([ax[0], ax[1]])
            pzp = plt.plot(X, X+zp, 'b--')
        pp.append(pzp)
        pl.append('Zeropoint')

    # reverse axis directions.
    if delta:
        plt.axis([ax[1],ax[0], ax[2], ax[3]])
    else:
        plt.axis([ax[1],ax[0], ax[3], ax[2]])

    if band is not None:
        reflabel = 'Reference catalog: %s band (mag)' % band
    else:
        reflabel = 'Reference catalog mag'

    if delta:
        plt.xlabel(reflabel)
        plt.ylabel('Instrumental - Reference (mag)')
        fn = prefix + '-dphotom.' + format

        if zp is not None:
            # Make the plot area smaller to fit the twin axis
            pos = plt.gca().get_position()
            ll = pos.min
            sz = pos.size
            plt.gca().set_position(pos=[ll[0], ll[1], sz[0], sz[1]-0.05])
            # Put the title up top (otherwise it follows the axis)
            if title is not None:
                plt.figtext(0.5, 0.96, title, ha='center', va='top', fontsize='large')
                title = None
                
            ax2 = plt.twiny()

            # Red tick marks show unmatched img sources
            if zp is not None:
                dy = (ax[3]-ax[2]) * 0.05
                y1 = np.ones_like(uimgmag) * ax[3]
                p2 = plt.plot(np.vstack((uimgmag, uimgmag)) + zp, np.vstack((y1, y1-dy)), 'r-', alpha=0.5)
                p2 = p2[0]
                # Blue tick marks show matched img sources
                y1 = np.ones_like(mimgmag) * ax[3]
                p3 = plt.plot(np.vstack((mimgmag, mimgmag)) + zp, np.vstack((y1-(0.25*dy), y1-(1.25*dy))), 'b-', alpha=0.5)
                p3 = p3[0]
            # Red ticks for unmatched ref sources
            y1 = np.ones_like(urefmag) * ax[2]
            p4 = plt.plot(np.vstack((urefmag, urefmag)), np.vstack((y1, y1+dy)), 'r-', alpha=0.5)
            p4 = p4[0]
            # Blue ticks for matched ref sources
            y1 = np.ones_like(mrefmag) * ax[2]
            p5 = plt.plot(np.vstack((mrefmag, mrefmag)), np.vstack((y1+(0.25*dy), y1+(1.25*dy))), 'b-', alpha=0.5)
            p5 = p5[0]

            plt.xlim(ax[1]-zp, ax[0]-zp)
            plt.xlabel('Instrumental mag')

        legloc = 'lower right'

    else:
        plt.ylabel(reflabel)
        plt.xlabel('Image instrumental mag')
        fn = prefix + '-photom.' + format
        legloc = 'center right'

    if title is not None:
        plt.title(title)

    pp += [p3, p2]
    pl += ['Matched sources', 'Unmatched sources']
    plt.figlegend(pp, pl, legloc, numpoints=1, prop=FontProperties(size='small'))

    P1 = _output(fn, format, saveplot)

    if delta:
        plt.ylim(-0.5, 0.5)
        fn = prefix + '-dphotom2.' + format
        P2 = _output(fn, format, saveplot)
        if not saveplot:
            P1.update(P2)

    return P1
Ejemplo n.º 11
0
    def intensityRatio(self, wvlRange=None, wvlRanges=None, top=10):
        """
        Plot the ratio of 2 lines or sums of lines.
        Shown as a function of density and/or temperature.
        For a single wavelength range, set wvlRange = [wMin, wMax]
        For multiple wavelength ranges, set wvlRanges = [[wMin1,wMax1],[wMin2,wMax2], ...]
        A plot of relative emissivities is shown and then a dialog appears for the user to
        choose a set of lines.
        """
        #
        #        self.Emiss={"temperature":temperature,"density":density,"wvl":wvl,"emiss":em,
        #        "plotLabels":plotLabels}
        #
        #
        if not hasattr(self, 'Intensity'):
            try:
                self.intensity()
            except:
                print(
                    ' intensities not calculated and emiss() is unable to calculate them'
                )
                print(' perhaps the temperature and/or eDensity are not set')
                return
        #
        # everything in self.Intensity should be a numpy array
        #
#        intens = copy.copy(self.Intensity)
#        intensity = intens['intensity']
#
#
        fontsize = 14
        #
        #        temperature = self.Temperature
        eDensity = self.EDensity
        temperature = self.Temperature
        #        intensity = intens['intensity']
        #
        #        temp=np.asarray(temperature,'Float32')
        ntemp = temperature.size
        if ntemp > 0:
            if temperature[0] == temperature[-1]:
                ntemp = 1
        #
        ndens = eDensity.size
        if ndens > 0:
            if eDensity[0] == eDensity[-1]:
                ndens = 1
        #
        print(' ndens = %5i ntemp = %5i' % (ndens, ntemp))

        ionS = self.Intensity['ionS']
        #  see if we are dealing with more than a single ion
        ionSet = set(ionS)
        ionNum = len(ionSet)
        wvl = self.Intensity["wvl"]
        #        plotLabels = intens["plotLabels"]
        #        xLabel = plotLabels["xLabel"]
        #        yLabel = plotLabels["yLabel"]
        #
        # find which lines are in the wavelength range if it is set
        #
        #
        if wvlRange:
            igvl = util.between(wvl, wvlRange)
            if len(igvl) == 0:
                print('no lines in wavelength range %12.2f - %12.2f' %
                      (wvlRange[0], wvlRange[1]))
                return
        elif wvlRanges:
            igvl = []
            for awvlRange in wvlRanges:
                igvl.extend(util.between(wvl, awvlRange))
            if len(igvl) == 0:
                print('no lines in wavelength ranges specified ')
                return
        else:
            igvl = range(len(wvl))
        #
        nlines = len(igvl)
        #
        #        print ' nlines = ',nlines
        #        print ' iglv = ',igvl
        igvl = np.take(igvl, wvl[igvl].argsort())
        # find the top most intense lines
        #
        if top > nlines:
            top = nlines
            #
        intensity = self.Intensity['intensity']
        maxIntens = np.zeros(nlines, 'Float64')
        for iline in range(nlines):
            maxIntens[iline] = intensity[:, igvl[iline]].max()
        for iline in range(nlines):
            if maxIntens[iline] == maxIntens.max():
                maxAll = intensity[:, igvl[iline]]
#        line=range(nlines)
        igvlsort = np.take(igvl, np.argsort(maxIntens))
        #        print 'igvlsort = ', igvlsort
        topLines = igvlsort[-top:]
        #        print ' topLines = ', topLines
        maxWvl = '%5.3f' % wvl[topLines[-1]]
        #        maxline=topLines[-1]
        #
        topLines = topLines[wvl[topLines].argsort()]
        #
        #
        # need to make sure there are no negative values before plotting
        good = intensity > 0.
        intensMin = intensity[good].min()
        bad = intensity <= 0.
        intensity[bad] = intensMin
        #
        #
        #        ntemp=self.Temperature.size
        #
        #        ndens=self.EDensity.size
        #
        ylabel = 'Intensity relative to ' + maxWvl
        if ionNum == 1:
            title = self.Spectroscopic
        else:
            title = ''
        #
        #
        if ndens == 1 and ntemp == 1:
            print(' only a single temperature and eDensity')
            return
        elif ndens == 1:
            xlabel = 'Temperature (K)'
            xvalues = self.Temperature
            outTemperature = self.Temperature
            #            outDensity=np.zeros(ntemp,'Float64')
            #            outDensity.fill(self.EDensity[0])
            outDensity = self.EDensity
            desc_str = ' Density = %10.2e (cm)$^{-3}$' % self.EDensity[0]
        elif ntemp == 1:
            xvalues = self.EDensity
            #            outTemperature=np.zeros(ndens,'Float64')
            #            outTemperature.fill(self.Temperature[0])
            outTemperature = self.Temperature
            outDensity = self.EDensity
            xlabel = r'$\rm{Electron Density (cm)^{-3}}$'
            desc_str = ' Temp = %10.2e (K)' % self.Temperature[0]
        else:
            outTemperature = self.Temperature
            outDensity = self.EDensity
            xlabel = 'Temperature (K)'
            xvalues = self.Temperature
            desc_str = ' Variable Density'
        #
        # put all actual plotting here
        #
        pl.ion()
        #        if chInteractive:
        #            pl.ion()
        #        else:
        #            pl.ioff()
        #
        #  maxAll is an array
        ymax = np.max(intensity[:, topLines[0]] / maxAll)
        ymin = ymax
        pl.figure()
        ax = pl.subplot(111)
        nxvalues = len(xvalues)
        for iline in range(top):
            tline = topLines[iline]
            pl.loglog(xvalues, intensity[:, tline] / maxAll)
            if np.min(intensity[:, tline] / maxAll) < ymin:
                ymin = np.min(intensity[:, tline] / maxAll)
            if np.max(intensity[:, tline] / maxAll) > ymax:
                ymax = np.max(intensity[:, tline] / maxAll)
            skip = 2
            start = divmod(iline, nxvalues)[1]
            for ixvalue in range(start, nxvalues, nxvalues // skip):
                if ionNum == 1:
                    text = '%10.4f' % (wvl[tline])
                else:
                    text = '%s %10.4f' % (ionS[tline], wvl[tline])
                pl.text(xvalues[ixvalue],
                        intensity[ixvalue, tline] / maxAll[ixvalue], text)
        pl.xlim(xvalues.min(), xvalues.max())
        #        pl.ylim(ymin, ymax)
        pl.xlabel(xlabel, fontsize=fontsize)
        pl.ylabel(ylabel, fontsize=fontsize)
        if ndens == ntemp and ntemp > 1:
            pl.text(0.07,
                    0.5,
                    title,
                    horizontalalignment='left',
                    verticalalignment='center',
                    fontsize=fontsize,
                    transform=ax.transAxes)
            #
            ax2 = pl.twiny()
            xlabelDen = r'Electron Density (cm$^{-3}$)'
            pl.xlabel(xlabelDen, fontsize=fontsize)
            pl.loglog(eDensity,
                      intensity[:, topLines[top - 1]] / maxAll,
                      visible=False)
            ax2.xaxis.tick_top()
            pl.ylim(ymin / 1.2, 1.2 * ymax)
        else:
            pl.ylim(ymin / 1.2, 1.2 * ymax)
            pl.title(title + desc_str, fontsize=fontsize)
        pl.draw()
        #  need time to let matplotlib finish plotting
        time.sleep(0.5)
        #
        # get line selection
        #
        selectTags = []
        for itop in topLines:
            if ionNum == 1:
                selectTags.append(str(wvl[itop]))
            else:
                selectTags.append(ionS[itop] + ' ' + str(wvl[itop]))
        #
#        numden = chGui.gui.choice2Dialog(wvl[topLines])
        numden = chGui.gui.choice2Dialog(selectTags)
        #
        # num_idx and den_idx are tuples
        #
        num_idx = numden.numIndex
        if len(num_idx) == 0:
            print(' no numerator lines were selected')
            return
        #
        den_idx = numden.denIndex
        if len(den_idx) == 0:
            print(' no denominator lines were selected')
            return
        #
        numIntens = np.zeros(len(xvalues), 'Float64')
        for aline in num_idx:
            numIntens += intensity[:, topLines[aline]]
        #
        denIntens = np.zeros(len(xvalues), 'Float64')
        for aline in den_idx:
            denIntens += intensity[:, topLines[aline]]
        #
        # plot the desired ratio
        #  maxAll is an array
        pl.figure()
        ax = pl.subplot(111)
        pl.loglog(xvalues, numIntens / denIntens)
        pl.xlim(xvalues.min(), xvalues.max())
        pl.xlabel(xlabel, fontsize=fontsize)
        pl.ylabel('Ratio (' + self.Defaults['flux'] + ')', fontsize=fontsize)
        if ionNum == 1:
            desc = ionS[0]
        else:
            desc = ''
        for aline in num_idx:
            if ionNum == 1:
                desc += ' ' + str(wvl[topLines[aline]])
            else:
                desc += ' ' + ionS[topLines[aline]] + ' ' + str(
                    wvl[topLines[aline]])
        desc += ' / '
        for aline in den_idx:
            if ionNum == 1:
                desc += ' ' + str(wvl[topLines[aline]])
            else:
                desc += ' ' + ionS[topLines[aline]] + ' ' + str(
                    wvl[topLines[aline]])
        if ndens == ntemp and ntemp > 1:
            pl.text(0.07,
                    0.5,
                    desc,
                    horizontalalignment='left',
                    verticalalignment='center',
                    fontsize=fontsize,
                    transform=ax.transAxes)
            #
            ax2 = pl.twiny()
            xlabelDen = r'Electron Density (cm$^{-3}$)'
            pl.xlabel(xlabelDen, fontsize=fontsize)
            pl.loglog(eDensity, numIntens / denIntens, visible=False)
            ax2.xaxis.tick_top()
        else:
            #            pl.ylim(ymin, ymax)
            pl.title(desc, fontsize=fontsize)
#       desc=title+' '+str(wvl[num_line])+' / '+str(wvl[den_line])+' '+desc_str
#        pl.title(desc, fontsize=fontsize)
#       pl.title(title+' '+str(wvl[num_line])+' / '+str(wvl[den_line])+' '+desc_str,fontsize=fontsize)
#        pl.draw()
#        pl.ioff()
#        pl.show()
#
#        intensityRatioFileName=self.IonStr
#        for aline in num_idx:
#            intensityRatioFileName+= '_%3i'%(wvl[topLines[aline]])
#        intensityRatioFileName+='_2'
#        for aline in den_idx:
#            intensityRatioFileName+= '_%3i'%(wvl[topLines[aline]])
        cnt = desc.count(' ')
        intensityRatioFileName = desc.replace(' ', '_', cnt) + '.rat'
        intensityRatioFileName = intensityRatioFileName.lstrip('_').replace(
            '_/_', '-')
        self.IntensityRatio = {
            'ratio': numIntens / denIntens,
            'desc': desc,
            'temperature': outTemperature,
            'eDensity': outDensity,
            'filename': intensityRatioFileName,
            'numIdx': num_idx,
            'denIdx': den_idx
        }
Ejemplo n.º 12
0
    def intensityRatio(self,wvlRange=None, wvlRanges=None,top=10):
        """
        Plot the ratio of 2 lines or sums of lines.
        Shown as a function of density and/or temperature.
        For a single wavelength range, set wvlRange = [wMin, wMax]
        For multiple wavelength ranges, set wvlRanges = [[wMin1,wMax1],[wMin2,wMax2], ...]
        A plot of relative emissivities is shown and then a dialog appears for the user to
        choose a set of lines.
        """
        #
        #        self.Emiss={"temperature":temperature,"density":density,"wvl":wvl,"emiss":em,
        #        "plotLabels":plotLabels}
        #
        #
        if not hasattr(self, 'Intensity'):
            try:
                self.intensity()
            except:
                print(' intensities not calculated and emiss() is unable to calculate them')
                print(' perhaps the temperature and/or eDensity are not set')
                return
        #
        # everything in self.Intensity should be a numpy array
        #
#        intens = copy.copy(self.Intensity)
#        intensity = intens['intensity']
        #
        #
        fontsize=14
        #
#        temperature = self.Temperature
        eDensity = self.EDensity
        temperature = self.Temperature
#        intensity = intens['intensity']
        #
#        temp=np.asarray(temperature,'Float32')
        ntemp = temperature.size
        if ntemp > 0:
            if temperature[0] == temperature[-1]:
                ntemp = 1
        #
        ndens = eDensity.size
        if ndens > 0:
            if eDensity[0] == eDensity[-1]:
                ndens = 1
        #
        print(' ndens = %5i ntemp = %5i'%(ndens, ntemp))
        
        ionS = self.Intensity['ionS']
        #  see if we are dealing with more than a single ion
        ionSet = set(ionS)
        ionNum = len(ionSet)
        wvl = self.Intensity["wvl"]
#        plotLabels = intens["plotLabels"]
#        xLabel = plotLabels["xLabel"]
#        yLabel = plotLabels["yLabel"]
        #
        # find which lines are in the wavelength range if it is set
        #
        #
        if wvlRange:
            igvl=util.between(wvl,wvlRange)
            if len(igvl) == 0:
                print('no lines in wavelength range %12.2f - %12.2f'%(wvlRange[0], wvlRange[1]))
                return
        elif wvlRanges:
            igvl = []
            for awvlRange in wvlRanges:
                igvl.extend(util.between(wvl,awvlRange))
            if len(igvl) == 0:
                print('no lines in wavelength ranges specified ')
                return
        else:
            igvl=range(len(wvl))
        #
        nlines=len(igvl)
        #
#        print ' nlines = ',nlines
#        print ' iglv = ',igvl
        igvl=np.take(igvl,wvl[igvl].argsort())
        # find the top most intense lines
        #
        if top > nlines:
            top=nlines
            #
        intensity = self.Intensity['intensity']
        maxIntens = np.zeros(nlines,'Float64')
        for iline in range(nlines):
            maxIntens[iline] = intensity[:, igvl[iline]].max()
        for iline in range(nlines):
            if maxIntens[iline]==maxIntens.max():
                maxAll=intensity[:, igvl[iline]]
#        line=range(nlines)
        igvlsort=np.take(igvl,np.argsort(maxIntens))
#        print 'igvlsort = ', igvlsort
        topLines=igvlsort[-top:]
#        print ' topLines = ', topLines
        maxWvl='%5.3f' % wvl[topLines[-1]]
#        maxline=topLines[-1]
        #
        topLines=topLines[wvl[topLines].argsort()]
        #
        #
        # need to make sure there are no negative values before plotting
        good = intensity > 0.
        intensMin = intensity[good].min()
        bad = intensity <= 0.
        intensity[bad] = intensMin
        #
        #
#        ntemp=self.Temperature.size
        #
#        ndens=self.EDensity.size
        #
        ylabel='Intensity relative to '+maxWvl
        if ionNum == 1:
            title=self.Spectroscopic
        else:
            title = ''
        #
        #
        if ndens==1 and ntemp==1:
            print(' only a single temperature and eDensity')
            return
        elif ndens == 1:
            xlabel='Temperature (K)'
            xvalues=self.Temperature
            outTemperature=self.Temperature
#            outDensity=np.zeros(ntemp,'Float64')
#            outDensity.fill(self.EDensity[0])
            outDensity = self.EDensity
            desc_str=' Density = %10.2e (cm)$^{-3}$' % self.EDensity[0]
        elif ntemp == 1:
            xvalues=self.EDensity
#            outTemperature=np.zeros(ndens,'Float64')
#            outTemperature.fill(self.Temperature[0])
            outTemperature = self.Temperature
            outDensity=self.EDensity
            xlabel=r'$\rm{Electron Density (cm)^{-3}}$'
            desc_str=' Temp = %10.2e (K)' % self.Temperature[0]
        else:
            outTemperature=self.Temperature
            outDensity=self.EDensity
            xlabel='Temperature (K)'
            xvalues=self.Temperature
            desc_str=' Variable Density'
        #
        # put all actual plotting here
        #
        pl.ion()
#        if chInteractive:
#            pl.ion()
#        else:
#            pl.ioff()
        #
        #  maxAll is an array
        ymax = np.max(intensity[:, topLines[0]]/maxAll)
        ymin = ymax
        pl.figure()
        ax = pl.subplot(111)
        nxvalues=len(xvalues)
        for iline in range(top):
            tline=topLines[iline]
            pl.loglog(xvalues,intensity[:, tline]/maxAll)
            if np.min(intensity[:, tline]/maxAll) < ymin:
                ymin = np.min(intensity[:, tline]/maxAll)
            if np.max(intensity[:, tline]/maxAll) > ymax:
                ymax = np.max(intensity[:, tline]/maxAll)
            skip=2
            start=divmod(iline,nxvalues)[1]
            for ixvalue in range(start,nxvalues,nxvalues//skip):
                if ionNum == 1:
                    text = '%10.4f'%(wvl[tline])
                else:
                    text = '%s %10.4f'%(ionS[tline], wvl[tline])
                pl.text(xvalues[ixvalue], intensity[ixvalue, tline]/maxAll[ixvalue], text)
        pl.xlim(xvalues.min(),xvalues.max())
#        pl.ylim(ymin, ymax)
        pl.xlabel(xlabel,fontsize=fontsize)
        pl.ylabel(ylabel,fontsize=fontsize)
        if ndens == ntemp and ntemp > 1:
            pl.text(0.07, 0.5,title, horizontalalignment='left', verticalalignment='center', fontsize=fontsize,  transform = ax.transAxes)
            #
            ax2 = pl.twiny()
            xlabelDen=r'Electron Density (cm$^{-3}$)'
            pl.xlabel(xlabelDen, fontsize=fontsize)
            pl.loglog(eDensity,intensity[:, topLines[top-1]]/maxAll, visible=False)
            ax2.xaxis.tick_top()
            pl.ylim(ymin/1.2, 1.2*ymax)
        else:
            pl.ylim(ymin/1.2, 1.2*ymax)
            pl.title(title+desc_str,fontsize=fontsize)
        pl.draw()
        #  need time to let matplotlib finish plotting
        time.sleep(0.5)
        #
        # get line selection
        #
        selectTags = []
        for itop in topLines:
            if ionNum == 1:
                selectTags.append(str(wvl[itop]))
            else:
                selectTags.append(ionS[itop]+ ' '+ str(wvl[itop]))
        #
#        numden = chGui.gui.choice2Dialog(wvl[topLines])
        numden = chGui.gui.choice2Dialog(selectTags)
        #
        # num_idx and den_idx are tuples
        #
        num_idx=numden.numIndex
        if len(num_idx) == 0:
            print(' no numerator lines were selected')
            return
        #
        den_idx=numden.denIndex
        if len(den_idx) == 0:
            print(' no denominator lines were selected')
            return
        #
        numIntens=np.zeros(len(xvalues),'Float64')
        for aline in num_idx:
            numIntens += intensity[:, topLines[aline]]
        #
        denIntens = np.zeros(len(xvalues),'Float64')
        for aline in den_idx:
            denIntens += intensity[:, topLines[aline]]
        #
        # plot the desired ratio
        #  maxAll is an array
        pl.figure()
        ax = pl.subplot(111)
        pl.loglog(xvalues,numIntens/denIntens)
        pl.xlim(xvalues.min(),xvalues.max())
        pl.xlabel(xlabel,fontsize=fontsize)
        pl.ylabel('Ratio ('+self.Defaults['flux']+')',fontsize=fontsize)
        if ionNum == 1:
            desc = ionS[0]
        else:
            desc = ''
        for aline in num_idx:
            if ionNum == 1:
                desc += ' ' + str(wvl[topLines[aline]])
            else:
                desc += ' ' + ionS[topLines[aline]] + ' ' + str(wvl[topLines[aline]]) 
        desc += ' / '
        for aline in den_idx:
            if ionNum == 1:
                desc += ' ' + str(wvl[topLines[aline]])
            else:
                desc += ' ' + ionS[topLines[aline]] + ' ' + str(wvl[topLines[aline]]) 
        if ndens == ntemp and ntemp > 1:
            pl.text(0.07, 0.5,desc, horizontalalignment='left', verticalalignment='center', fontsize=fontsize,  transform = ax.transAxes)
            #
            ax2 = pl.twiny()
            xlabelDen=r'Electron Density (cm$^{-3}$)'
            pl.xlabel(xlabelDen, fontsize=fontsize)
            pl.loglog(eDensity,numIntens/denIntens, visible=False)
            ax2.xaxis.tick_top()
        else:
#            pl.ylim(ymin, ymax)
            pl.title(desc,fontsize=fontsize)
#       desc=title+' '+str(wvl[num_line])+' / '+str(wvl[den_line])+' '+desc_str
#        pl.title(desc, fontsize=fontsize)
#       pl.title(title+' '+str(wvl[num_line])+' / '+str(wvl[den_line])+' '+desc_str,fontsize=fontsize)
#        pl.draw()
#        pl.ioff()
#        pl.show()
        #
#        intensityRatioFileName=self.IonStr
#        for aline in num_idx:
#            intensityRatioFileName+= '_%3i'%(wvl[topLines[aline]])
#        intensityRatioFileName+='_2'
#        for aline in den_idx:
#            intensityRatioFileName+= '_%3i'%(wvl[topLines[aline]])
        cnt = desc.count(' ')
        intensityRatioFileName = desc.replace(' ', '_', cnt) + '.rat'
        intensityRatioFileName = intensityRatioFileName.lstrip('_').replace('_/_','-')
        self.IntensityRatio={'ratio':numIntens/denIntens,'desc':desc,
                'temperature':outTemperature,'eDensity':outDensity,'filename':intensityRatioFileName, 'numIdx':num_idx, 'denIdx':den_idx}
Ejemplo n.º 13
0
    lst_hr = int(n.around(n.average(lsts[i:i + chunk])))
    Tsys_avg = n.sqrt(n.average(Tsys[i:i + chunk]**2, axis=0))
    valid = n.where(Tsys_avg > 213, 1, 0)
    #p.plot(1e3*fqs.compress(valid), Tsys_avg.compress(valid), label='LST = %02dh00'%lst_hr)
    p.plot(chans.compress(valid),
           Tsys_avg.compress(valid),
           label='LST = %02dh00' % lst_hr)

if VLINE:
    nums = opts.chan.split('_')
    vlines = [float(v) for v in nums]
    p.vlines(vlines, 200, 2000, linestyles='dashed')
p.legend(loc='best', fontsize='medium')
p.xlabel(r'${\rm Channel}$', fontsize=16)
if FREQ_AXIS:
    ax = p.twiny()
    ax.plot(freqs, n.ones(len(freqs * 1e3)))
    ax.cla()
    ax.set_xlabel(r'${\rm Frequency\ [MHz]}$', fontsize=16)
#p.xlim(125,175)
p.ylim(200, 2000)
p.grid()
p.ylabel(r'${\rm T}_{\rm sys}$', fontsize=16)
p.subplots_adjust(0.12, 0.15, .95, .85)

fig_file = 'Tsys_chan_' + opts.chan
if not opts.output == '':
    fig_file = opts.output + '/' + fig_file
p.savefig(fig_file)
p.show()