Exemple #1
0
def plt_twin( axis, tick0=None, tick=None ) : 
	'''
	Add x-top or y-right axis

	axis:
		['x' | 'y']

	tick0:
		Must between [0, 1]
	'''
	if (str(axis).lower() not in ['x', 'y']) : Raise(Warning, "axis='"+str(axis)+"' not in ['x', 'y']. Do nothing !")
	axis = str(axis).lower()
	#--------------------------------------------------
	if (tick0 is not None and tick is not None) : 
		tick0 = npfmt(tick0, float)
		if (tick0.min()<0 or tick0.max()>1) : 
			Raise(Warning, 'tick0.(min,max)=(%.1f, %.1f) out of [0, 1]. Do nothing !' % (tick0.min(), tick0.max()))
		else : 
			if   (axis == 'x') : 
				plt.twiny()
				plt.xticks(tick0, tick)
			elif (axis == 'y') : 
				plt.twinx()
				plt.yticks(tick0, tick)
	#--------------------------------------------------
	elif (tick0 is None and tick is None) : 
		if   (axis == 'x') : plt.tick_params(axis='x', which='both', labeltop='on', labelbottom='on')
		elif (axis == 'y') : plt.tick_params(axis='y', which='both', labelleft='on', labelright='on')
	#--------------------------------------------------
	else : Raise(Warning, 'tick0, tick must both ==None or !=None, now one is None but the other is not. Do nothing !')
Exemple #2
0
def graphMembersOverTimeWithPlusMinusText(membertimedata, memberinfos, membership):
    ydates, yvalues = zip(*membertimedata)
    ydates = list(ydates)
    #yvalues = map(lambda x:x[0],yvalues)
    plotlabel = [u"Number of members over time","Membership Income over time"]
    plt.plot(ydates, yvalues, 'o',linewidth=2, markevery=1)
    plt.ylabel("#Members")
    plt.xlabel("Month")
    plt.grid(True)
    plt.legend(plotlabel,loc='upper left')
    plt.twiny()
    plt.ylabel("Euro")
    #plt.title(plotlabel)
    ## label with +x-y members per month
    membersinmonth = dict(membertimedata)
    #print "\n".join([ "%s:%s" % (x[0],str(x[1])) for x in extractPlusMinusFromMemberships(membership).items()])
    pm_dates, pm_fee_dates = extractPlusMinusFromMemberships(membership)
    for astrdate, tpl in pm_dates.items():
        adate = datetime.datetime.strptime(astrdate, dateformat_monthonly_).date()
        assert(adate.day==1)
        if adate in membersinmonth:
            xy = (adate, membersinmonth[adate][0])
            xytext = (xy[0], xy[1]+1)
            plt.annotate(str(tpl), xy=xy, xytext=xytext,arrowprops=dict(facecolor='gray', shrink=0.5))
    for astrdate, tpl in pm_fee_dates.items():
        adate = datetime.datetime.strptime(astrdate, dateformat_monthonly_).date()
        assert(adate.day==1)
        if adate in membersinmonth:
            xy = (adate, membersinmonth[adate][1])
            xytext = (xy[0], xy[1]+30)
            plt.annotate(str(tpl), xy=xy, xytext=xytext,arrowprops=dict(facecolor='gray', shrink=0.5))
    plt.subplots_adjust(left=0.06, bottom=0.05, right=0.99, top=0.95)
Exemple #3
0
def classificate(X, bins=None, n_components=5, verbose=True,
        histogram_ylabel='X',
        histogram_xlabel='Frequency',
        gaussian_xlabel='Probability',
        scatter_xlabel='Point No.'):
    # create histogram data
    hist, bins = statistics_histogram.histogram(X, bins=bins)
    # create gaussian mixture model
    model, AIC, BIC = clustering_gaussian.fit(X, n_components)

    # plot histogram
    pl.subplot(121)
    plot_histogram.histogram(hist, bins, transposition=True, color='k', alpha=0.7)
    pl.xlabel(histogram_xlabel)
    pl.ylabel(histogram_ylabel)
    pl.grid()

    # plot gaussian
    pl.twiny()
    plot_gaussian.gaussian(X, model, transposition=True)
    pl.xlabel(gaussian_xlabel)
    pl.legend()

    # reverse y axis
    ymin, ymax = pl.ylim()
    pl.ylim(ymax, ymin)

    # plot classified scatter
    pl.subplot(122)
    plot_gaussian.gaussian_scatter(X, model)
    pl.ylim(ymax, ymin)
    pl.xlabel(scatter_xlabel)
    pl.ylabel(histogram_ylabel)
    pl.minorticks_on()
    pl.legend()
    pl.grid(which='major', alpha=0.5)
    pl.grid(which='minor', alpha=0.2)

    # print result in stdout if verbose
    if verbose:
        print histogram_xlabel
        print "N = %d, Bins = %d" % (len(X), len(bins))
        # individual fitting curve
        properties = zip(model.weights_, model.means_, model._get_covars())
        properties = sorted(properties, key=lambda x: x[1])
        for (weight, mean, covar) in properties:
            var = np.diag(covar)[0]
            # create formula of normal deviation
            formula_label = textutils.gaussian_formula(len(X), mean, var)
            formula_label = "%.1f%%: %s" % (weight * 100, formula_label)
            print formula_label.encode('utf-8')

    # show figure
    pl.show()
Exemple #4
0
    def align_pulses(self, samples=768):
        #record single probe tone signal and plot
        samples = int(samples / 32) * 16
        self._sample.mspec.spec_stop()
        self._sample.mspec.set_segments(2)
        self._sample.mspec.set_averages(1e4)
        self._sample.mspec.set_spec_trigger_delay(0)
        self._sample.mspec.set_samples(samples * 2)
        self._sample.mspec._dacq.set_post_trigger(samples)

        self._sample.qubit_mw_src.set_frequency(
            self._sample.readout_mw_src.get_frequency())
        sr = self._sample.mspec.get_samplerate() / 1e9
        pwr = self._sample.qubit_mw_src.get_power()
        self._sample.qubit_mw_src.set_power(5)
        self._load_awg_square([0, 50e-9])
        self._sample.qubit_mw_src.set_status(1)
        msp = self._sample.mspec.acquire()
        self._sample.qubit_mw_src.set_status(0)
        plt.figure(figsize=(15, 5))
        plt.plot(np.arange(-samples + 32, samples + 32), msp[:, :, 1])
        plt.plot(np.arange(-samples + 32, samples + 32), msp[:, :, 0], '--k')
        plt.xlim((-samples + 32, samples + 32))
        plt.grid()
        plt.xlabel('samples (%.0fMHz samplerate: 1 sample = %.3gns)' %
                   (sr * 1e3, 1. / sr))
        plt.ylabel('amplitude')
        plt.twiny()
        plt.xlabel('nano seconds')
        duration = float(samples) / sr
        plt.xticks(np.arange(-round(duration, -2), round(duration, -2), 100))
        plt.xlim(-duration + 32 / sr, +duration + 32 / sr)
        plt.grid(axis='x')
        self._sample.qubit_mw_src.set_power(pwr)

        print(
            "You can now change the self._sample.readout_delay parameter to align the two pulses. The readout pulse should start when the manipulation ends."
        )
        print(
            "If you are satisfied just press <Enter> or tell me the new delay."
        )
        plt.show()
        inp = raw_input("readout_delay ({:g}s) = ".format(
            self._sample.readout_delay))
        if inp == '':
            return
        if np.abs(float(inp)) > 1e-3:
            raise ValueError(
                "Your delay is more than a mili second. I guess you are wrong."
            )
        self._sample.readout_delay = float(inp)
        self.update_timings()
        self.align_pulses()
Exemple #5
0
 def record_single_trace(self):
     #record single probe tone signal and plot
     self._sample.qubit_mw_src.set_status(0)
     self._sample.mspec.set_window(0, 1024)
     self._sample.mspec.set_averages(1)
     self._sample.mspec.set_segments(5)
     samples = self._sample.mspec.acquire()
     plt.figure(figsize=(15, 5))
     plt.plot(samples[:, :, 0])
     plt.xticks(np.arange(0, self._sample.mspec.get_samples(), 32))
     plt.xlim((0, self._sample.mspec.get_samples()))
     plt.grid()
     plt.xlabel('samples (%.0fMHz samplerate: 1sample = %.3gns)' %
                (self._sample.mspec.get_samplerate() / 1e6,
                 1. / self._sample.mspec.get_samplerate() * 1e9))
     plt.ylabel('amplitude')
     plt.twiny()
     plt.xlabel('nanoseconds')
     plt.xticks(
         np.arange(
             0,
             float(self._sample.mspec.get_samples()) /
             self._sample.mspec.get_samplerate() * 1e9, 100))
     plt.xlim(
         0,
         float(self._sample.mspec.get_samples()) /
         self._sample.mspec.get_samplerate() * 1e9)
     plt.ylim(-128, 127)
     clips = np.size(
         np.where(np.array(samples).flatten() == 127)) + np.size(
             np.where(np.array(samples).flatten() == -128))
     if clips > 50:
         logging.error(
             "Clipping detected, please reduce amplifier voltage (%r Clips)"
             % clips)
     elif clips > 0:
         print(
             "In 5 measurements, only %i points had the maximum amplitude. This sounds good, go on."
         ) % clips
     elif np.max(samples) < 15:
         raise ValueError("No signal detected. Check your wiring!")
     elif np.max(np.abs(samples)) < 64:
         print(
             "The amplitude never reached half of the maximum of the card. Think about adding an amplifier and check that you are using the smallest spec_input_level."
         )
     else:
         print(
             "The amplitude seems reasonable. Check the image nevertheless."
         )
     self._sample.mspec.set_window(*self._sample.acqu_window)
Exemple #6
0
    def draw_std_outliers(self, x, y, title=None, xtitle=None, ytitle=None):
        plot.scatter(x, y)
        # the top title will be set seperatly
        # this must be called before ax2 initiation
        self.add_title(title, xtitle = xtitle, ytitle = ytitle)

        # add vertical lines for each std to easly see outliers
        x_std = std(x)
        lines = range(-1* self.STD_LINES_SYMMETRIC_LIMIT, self.STD_LINES_SYMMETRIC_LIMIT + 1)
        lines.remove(0) 
        lines.remove(1) 
        lines.remove(-1) 
        
        # draw the lines
        [plot.axvline(x=x_std*i, color='r',linestyle='-') for i in  lines]
        
        # set lines titles on second x axis
        # this is a patch that works (I dont understand why)
        
        left,right = plot.xlim()   # xlim must be taken before calling plot.twiny(), since calling to twiny() changes the limit
        ax2 = plot.twiny()         # set another x axis
        ax2.set_xlim(left, right)  # set xlim to the one before duplicatin x-axis: that line is what causes the std-lines title to adjust window size changing
        
        ax2.set_xticks([x_std*i for i in  lines])           # set ticks in the std places (dont show them with grid since this grid is wrong, that is why we use axvlines above)
        ax2.set_xticklabels(["%dsd"%i for i in lines])    # set title for each tick
Exemple #7
0
def left_graph(plot_data):
    left = plt.subplot(121)
    dataset_names = []
    for plot in plot_data:
        dataset_names.append(plot['name'])
        this_plot = plt.plot(plot['x'],
                             plot['y'],
                             color=plot['color'],
                             marker=plot['marker'],
                             markersize=5)
        plt.setp(this_plot, markevery=25)

    # Axes
    plt.axis([0, 500000, 0.6, 1.0])
    plt.xlabel('Rozegranych gier')
    plt.ylabel('Odsetek wygranych gier')
    left.tick_params(labelsize="small")
    plt.xticks(rotation=20)

    # Legend
    legend = plt.legend(dataset_names, loc='lower right', scatterpoints=12)

    # Generation axis
    gen_axis = plt.twiny()
    plt.xlabel('Pokolenie')
    gen_axis.set_xticks([0, 40, 80, 120, 160, 200])
    gen_axis.tick_params(labelsize="small")

    pass
Exemple #8
0
 def dualLIFPlot(self, y = None):
     '''
         Makes a vertical LIF photon / s rate plot using internal lif
         averages.
     '''
     if y is None:
         y = self.dye_v - self.diode_v
     l1 = plt.plot(np.array([np.mean(x) for x in self.lif_avgs1]), y,
             color='red', label='PMT1')
     plt.xticks(color='red')
     plt.xlabel('ave photons / demod sample (photon kHz)', color='red')
     plt.title('PMT1 & 2 LIF Signal', y=1.08)
     plt.ylim(np.min(y), np.max(y))
     plt.twiny()
     l2 = plt.plot(np.array([np.mean(x) for x in self.lif_avgs2]), y,
             color='red', label='PMT2')
Exemple #9
0
 def makePlot(self):
     minx = np.min(self.powers)
     maxx = np.max(self.powers)
     xvals = np.linspace(minx, maxx, self.powers.size * 100)
     yvals = self.fitfunc(xvals)
     pyplot.figure()
     pyplot.plot(self.powers, self.dataFluor, 'o', markersize=4)
     pyplot.plot(xvals, yvals)
     pyplot.ylim(ymin=0)
     s = "Pulsed Axial Power Scan {}\n".format(self.name)
     s = s + "Detuning {0:.2f} Gamma\n".format(self.detuning)
     maxsat = maxx / self.xscalefit
     s = s + "Max Saturation {0:.0f}\n".format(maxsat)
     s = s + "Power for s = 1 : {0:.2f} microwatt\n".format(
         1000 * self.xscalefit)
     Isat = 4.33 * 10**-7  #mW / micron^2, #see e.g aarhus phd peter staanum
     waist = np.sqrt(self.xscalefit / Isat) / 2.0
     s = s + "Waist of ~{0:.0f} micron".format(waist)
     pyplot.text(0.5, 10000.0, s)  #,  verticalalignment='top')
     pyplot.xlabel('397 Power mW')
     pyplot.ylabel('Fluorescence Counts/Sec')
     ax = pyplot.twiny()
     pyplot.xlabel("Saturation =  Omega / Gamma")
     pyplot.xlim(xmin=minx / self.xscalefit, xmax=maxx / self.xscalefit)
     pyplot.show()
def plot_age(p, form, fof_np, age_labels, symbls):
    lims = 10. ** np.linspace(9, 15, (15.25-9) / .25) #These are the limits for the mass bins
    for (i, form_i) in enumerate(form):
        (avg, med) = binning(fof_np[i], form_i, lims)
        plt.semilogx(avg[0], avg[1], marker = symbls[i], subsx = [2, 3, 4, 5, 6, 7, 8, 9], \
                     label = 'Average {0}'.format(age_labels[i]))
        plt.semilogx(med[0], med[1], linestyle = 'dashed', label = 'Median {0}'.format(age_labels[i]))
    #MS = 13.5795 - 10.3112 * np.arcsinh(0.0504329 * avg[0] ** 0.08445)
    #plt.semilogx(avg[0], MS, 'r', label = 'MS Curve')
    plt.legend()
    plt.xlabel('M [M_sun / h]')
    plt.ylabel('Formation Age Lookback time [Gyr]')
    ##Create Second x axis
    xlims = plt.xlim()
    x2 = plt.twiny()
    x2.set_xscale('log')
    x2.set_xlim((xlims[0] / .73, xlims[1] / .73))
    x2.set_xlabel('M [M_sun]')
    
    ##Create second y axis
    
    ylims = plt.ylim()
    yt = plt.yticks()[0]
    y2 = plt.twinx()
    y2.set_ylim(ylims)
    y2.set_yticks(yt)
    yl = []
    for j in yt:
        if j < 13.5795:
            yl.append('{:5.2f}'.format(1.44224957031 / mth.sinh(0.0969815 * (13.5795 - j))**(2./3.)))
        else:
            yl.append('')
    y2.set_yticklabels(yl)
    y2.set_ylabel('z + 1')
def iord_bhacc_plot(iord_df,
                    time,
                    bins=300,
                    save=False,
                    filename='plots/accretion_rates/iord_%s_accRates.png'):
    '''send individual iord dataframe, time array'''
    plt.clf()
    iord_id = iord_df.loc[0, 'iord']

    plt.plot(iord_df['time'],
             weights=iord_df['accRate'],
             color='k',
             linewidth=.9)
    plt.title('BH %s Accretion Rates' % (iord_id), y=1.14)
    plt.ylabel('Accretion Rate [M$_\odot$ yr$^{-1}$]]', fontsize='large')
    plt.xlabel('Time [Gyr]', fontsize='large')
    plt.xlim(-.25, 14)
    plt.yscale('log')

    x0, x1 = plt.gca().get_xlim()
    old_axis = plt.gca()
    pz = plt.twiny()
    labelz = time_axis['z'][-6:]
    times = time_axis['time[Gyr]'][-6:]
    pz.set_xticks(times)
    pz.set_xticklabels([str(x) for x in labelz])
    pz.set_xlim(x0, x1)
    pz.set_xlabel('$z$')
    plt.sca(old_axis)

    plt.tight_layout()
    plt.subplots_adjust(top=1)
    if save == True:
        plt.savefig(filename % (iord_id), bbox_inches='tight', dpi=200)
def iord_r_plot(iord_df,
                time,
                bins=150,
                lc='best',
                htype='bar',
                halo_label=False,
                save=False,
                filename='plots/galaxy_masses/iord_%s_masses.png'):
    '''send individual iord dataframe, iord_id, timearray(time['time[Gyr]'])'''
    plt.clf()
    iord_id = iord_df.name

    plt.plot(time['time[Gyr]'], iord_df['r[kpc]'], color='k', linewidth=.9)
    #plt.hist(iord_df['time'], weights=iord_df['r'], bins=bins, histtype='step', color='k', linewidth=.9);
    plt.title('BH %s Radial Distance' % (iord_id), y=1.14)
    plt.ylabel('R [kpc]', fontsize='large')
    plt.xlabel('Time [Gyr]', fontsize='large')
    plt.xlim(-.25, 14)
    #plt.yscale('log')

    x0, x1 = plt.gca().get_xlim()
    old_axis = plt.gca()
    pz = plt.twiny()
    labelz = time_axis['z'][-6:]
    times = time_axis['time[Gyr]'][-6:]
    pz.set_xticks(times)
    pz.set_xticklabels([str(x) for x in labelz])
    pz.set_xlim(x0, x1)
    pz.set_xlabel('$z$')
    plt.sca(old_axis)

    plt.tight_layout()
    plt.subplots_adjust(top=1)
    if save == True:
        plt.savefig(filename % (iord_id), bbox_inches='tight', dpi=200)
Exemple #13
0
def plot_area_pnl(pnlcs, save=False, title=None, legend=False, filter=None):
    '''
    Plot area chart of cumulative PNL
    :param pnlcs: A list of cumulative pnls saved in numpy. First element should
    be the baseline pnl series
    :param filter: List representing the index to keep in pnlcs for attribution
    :return: None. Figure saved locally
    '''
    if filter is not None:
        to_plot = [pnlcs[i] for i in filter]
        labels = ['Factor ' + str(x) for x in filter]
    else:
        to_plot = pnlcs[1:]
        labels = ['Factor ' + str(x) for x in range(1, len(pnlcs) + 1)]
    x = [x for x in range(len(pnlcs[0]))]
    plt.stackplot(x, to_plot, labels=labels)
    plt.ylabel("PNL")
    plt.xlabel("Trading Day")
    if legend:
        plt.legend(bbox_to_anchor=(0., 1.02, 1., .102),
                   loc=3,
                   ncol=4,
                   mode="expand",
                   borderaxespad=0.)
    axis2 = plt.twiny()
    axis2.set_xticks([])
    axis2.plot(x, pnlcs[0], color='black', label='Total PNL')
    if title is not None:
        plt.title(title)
    if legend:
        plt.legend()
    if save:
        plt.savefig('pnl_explain.png')
    plt.show()
Exemple #14
0
def plotBoundaries (tranNames, blocks):
    '''Plot exon boundaries as vertical lines.'''

    ticksStart  = list()     # x-axis tick positions in phony space
    ticksEnd    = list()
    labelsStart = list()     # x-axis labels are real genomic coordinates of block start
    labelsEnd   = list()

    tickSep = blocks[-1].boundary / MAX_LABELS     # separation required to avoid label overlap

    frompos = 0
    for bound in blocks:

        plt.vlines (bound.boundary, 0, len(tranNames)+1, linewidth=0.5, colors='red')    # block boundary

        if not bound.annot:            # if block does not include annotation exon(s), make it blush
            plt.axvspan(frompos, bound.boundary, facecolor='Pink', alpha=0.4)

        if len(ticksStart) == 0 or frompos - ticksStart[-1] > tickSep:     # add tick only if there's room for the label
            ticksStart.append(frompos)
            labelsStart.append(str(bound.start))
        if len(ticksEnd) == 0 or bound.boundary - ticksEnd[-1] > tickSep:
            ticksEnd.append(bound.boundary)
            labelsEnd.append(str(bound.end))

        frompos = bound.boundary           # new block start

    numberedNames = list()                 # cluster name + line number
    for ix, name in enumerate(tranNames):
        numberedNames.append('%s %3d' % (name, ix+1))

    plt.grid(axis='y')                     # turn on horizontal dotted lines
    plt.xlim (0, blocks[-1].boundary)
    plt.ylim (len(tranNames)+1, 0)
    plt.xticks (ticksStart, labelsStart, fontsize='xx-small')
    plt.yticks (xrange(1,len(tranNames)+2), numberedNames, fontsize='xx-small')

    # These lines came from an obscure posting on StackOverflow. They
    # create a second X axis at the bottom of the figure. I haven't
    # got a clue how they work, but they do.

    x2 = plt.twiny()
    x2.set_frame_on(True)
    x2.patch.set_visible(False)
    x2.xaxis.set_ticks_position('bottom')
    x2.xaxis.set_label_position('bottom')
    x2.spines['bottom'].set_position(('outward', 20))

    plt.axes(x2)

    plt.grid(axis='y')
    plt.xlim (0, blocks[-1].boundary)
    plt.ylim (len(tranNames)+1, 0)
    plt.xticks (ticksEnd, labelsEnd, fontsize='xx-small')
    plt.yticks (xrange(1,len(tranNames)+2), numberedNames, fontsize='xx-small')

    return
Exemple #15
0
def plotBoundaries (tranNames, blocks):
    '''Plot exon boundaries as vertical lines.'''

    ticksStart  = list()     # x-axis tick positions in phony space
    ticksEnd    = list()
    labelsStart = list()     # x-axis labels are real genomic coordinates of block start
    labelsEnd   = list()

    tickSep = blocks[-1].boundary / MAX_LABELS     # separation required to avoid label overlap

    frompos = 0
    for bound in blocks:

        plt.vlines (bound.boundary, 0, len(tranNames)+1, linewidth=0.5, colors='red')    # block boundary

        if not bound.annot:            # if block does not include annotation exon(s), make it blush
            plt.axvspan(frompos, bound.boundary, facecolor='Pink', alpha=0.4)

        if len(ticksStart) == 0 or frompos - ticksStart[-1] > tickSep:     # add tick only if there's room for the label
            ticksStart.append(frompos)
            labelsStart.append(str(bound.start))
        if len(ticksEnd) == 0 or bound.boundary - ticksEnd[-1] > tickSep:
            ticksEnd.append(bound.boundary)
            labelsEnd.append(str(bound.end))

        frompos = bound.boundary           # new block start

    numberedNames = list()                 # cluster name + line number
    for ix, name in enumerate(tranNames):
        numberedNames.append('%s %3d' % (name, ix+1)) 

    plt.grid(axis='y')                     # turn on horizontal dotted lines
    plt.xlim (0, blocks[-1].boundary)
    plt.ylim (len(tranNames)+1, 0)
    plt.xticks (ticksStart, labelsStart, fontsize='xx-small')
    plt.yticks (xrange(1,len(tranNames)+2), numberedNames, fontsize='xx-small')

    # These lines came from an obscure posting on StackOverflow. They
    # create a second X axis at the bottom of the figure. I haven't
    # got a clue how they work, but they do.

    x2 = plt.twiny()
    x2.set_frame_on(True)
    x2.patch.set_visible(False)
    x2.xaxis.set_ticks_position('bottom')
    x2.xaxis.set_label_position('bottom')
    x2.spines['bottom'].set_position(('outward', 20))

    plt.axes(x2)

    plt.grid(axis='y')
    plt.xlim (0, blocks[-1].boundary)
    plt.ylim (len(tranNames)+1, 0)
    plt.xticks (ticksEnd, labelsEnd, fontsize='xx-small')
    plt.yticks (xrange(1,len(tranNames)+2), numberedNames, fontsize='xx-small')

    return
Exemple #16
0
def plotPatternBeyondRepeat(genomeSource1,genomeSource2,  start1,  start2, plotRange):
    f1 = open(genomeSource1,'r')
    f2 = open(genomeSource2,'r')
    
    pointerLocation1 = start1
    pointerLocation2 = start2
    
    windowSize = 10
    
    defaultsize = 24
    distanceList = []
    plotRange = plotRange/windowSize
    
    for index in range(plotRange):
        f1.seek(pointerLocation1)
        f2.seek(pointerLocation2)
    
        str1 = f1.read(windowSize)
        str2 = f2.read(windowSize)
        
        pointerLocation1 = pointerLocation1 + windowSize
        pointerLocation2 = pointerLocation2 + windowSize
        
        distance = hammingDistance(str1, str2, min(windowSize,len(str1),len(str2)))
        distanceList.append(distance)        
        
    
    #plt.subplot(111)
    plt.plot(range(0,len(distanceList)*windowSize, windowSize), distanceList)
    
    plt.tick_params(axis='both', which='major', labelsize=defaultsize)
    plt.tick_params(axis='both', which='minor', labelsize=defaultsize)
    
    plt.xlabel("Genomics location of Copy 1 ( unit : base )", fontsize=defaultsize)    
    plt.ylabel("Hamming distance within a window of length 10 ",fontsize=defaultsize)
    
    #print plt.xticks()
    locs =range(0,len(distanceList)*windowSize+1, len(distanceList)*windowSize/4)
    tick_lbls =  range(start1, start1+plotRange*windowSize+1, plotRange*windowSize/4)
    plt.xticks(locs, tick_lbls, fontsize=defaultsize)
    
    ax2 = plt.twiny()
    plt.tick_params(axis='both', which='major', labelsize=defaultsize)
    plt.tick_params(axis='both', which='minor', labelsize=defaultsize)
    
    plt.xlabel("Genomics location of Copy 2 ( unit : base )", fontsize=defaultsize)    
    plt.ylabel("Hamming distance within a window of length 10 ",fontsize=defaultsize)
    
    tick_locs = range(0, plotRange*windowSize+1, plotRange*windowSize/4)
    tick_lbls = range(start2, start2+plotRange*windowSize+1, plotRange*windowSize/4)
    plt.xticks(tick_locs, tick_lbls,fontsize=defaultsize)
  
    plt.show()

    f1.close()
    f2.close()
Exemple #17
0
def graphMembersOverTimeWithPlusMinusText(membertimedata, memberinfos,
                                          membership):
    ydates, yvalues = zip(*membertimedata)
    ydates = list(ydates)
    #yvalues = map(lambda x:x[0],yvalues)
    plotlabel = [u"Number of members over time", "Membership Income over time"]
    plt.plot(ydates, yvalues, 'o', linewidth=2, markevery=1)
    plt.ylabel("#Members")
    plt.xlabel("Month")
    plt.grid(True)
    plt.legend(plotlabel, loc='upper left')
    plt.twiny()
    plt.ylabel("Euro")
    #plt.title(plotlabel)
    ## label with +x-y members per month
    membersinmonth = dict(membertimedata)
    #print "\n".join([ "%s:%s" % (x[0],str(x[1])) for x in extractPlusMinusFromMemberships(membership).items()])
    pm_dates, pm_fee_dates = extractPlusMinusFromMemberships(membership)
    for astrdate, tpl in pm_dates.items():
        adate = datetime.datetime.strptime(astrdate,
                                           dateformat_monthonly_).date()
        assert (adate.day == 1)
        if adate in membersinmonth:
            xy = (adate, membersinmonth[adate][0])
            xytext = (xy[0], xy[1] + 1)
            plt.annotate(str(tpl),
                         xy=xy,
                         xytext=xytext,
                         arrowprops=dict(facecolor='gray', shrink=0.5))
    for astrdate, tpl in pm_fee_dates.items():
        adate = datetime.datetime.strptime(astrdate,
                                           dateformat_monthonly_).date()
        assert (adate.day == 1)
        if adate in membersinmonth:
            xy = (adate, membersinmonth[adate][1])
            xytext = (xy[0], xy[1] + 30)
            plt.annotate(str(tpl),
                         xy=xy,
                         xytext=xytext,
                         arrowprops=dict(facecolor='gray', shrink=0.5))
    plt.subplots_adjust(left=0.06, bottom=0.05, right=0.99, top=0.95)
    def heatMap(self):
        errors = self.errors.copy()
        pe = self.APE.copy()
        errors[
            'min_from_midnight'] = errors.index.hour * 60 + errors.index.minute
        pe['min_from_midnight'] = errors.index.hour * 60 + errors.index.minute

        plt.rcParams.update({'font.size': 24})
        time_errors = []

        newarray = np.zeros((96, 96 * 2))

        for i in range(0, 96):
            newdata = (pe.loc[(errors['min_from_midnight'] >= i * 15)
                              & (pe['min_from_midnight'] <= i * 15 + 14)])
            newdata = newdata.drop(columns=['min_from_midnight'])

            mape = newdata.mean(axis=0)
            print(mape)
            for j in range(0, 96):
                newarray[i][j + i] = (mape[j]) * 100

        for i in range(7):
            x = [i * 16, 96 + i * 16]
            y = [0, 96]
            plt.plot(x, y, c='grey')

        # fel som både tid på dygn och tid framåt.
        plt.imshow(newarray,
                   cmap=self.get_continuous_cmap(
                       ['#FFFFFF', '#F6D55C', '#000000']),
                   aspect='auto')
        plt.ylabel("Tid för prognos [hh:mm]")
        plt.yticks([0, 12, 24, 36, 48, 60, 72, 84], [
            '00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00',
            '21:00'
        ])
        plt.xlabel("Tid prognos gäller för [hh:mm]")
        plt.xticks([0, 24, 48, 72, 96, 120, 144, 168], [
            '00:00', '06:00', '12:00', '18:00', '24:00', '06:00', '12:00',
            '18:00'
        ],
                   rotation=45)
        plt.grid()
        cbar = plt.colorbar()
        cbar.ax.set_ylabel('MAPE [\%]')

        ax2 = plt.twiny()
        ax2.set_xlabel("Prognoshorisont [h]")
        ax2.set_xticks([0, 16, 32, 48, 64, 80, 96, 192])
        ax2.set_xticklabels(['', '4', '8', '12', '16', '20', '24', ''])
        plt.tight_layout()
        plt.show()
Exemple #19
0
def make_twiny():
    """
    """

    ax3 = plt.twiny()
    ax3.xaxis.set_ticks_position('bottom')
    ax3.spines['bottom'].set_position(('axes', -0.35))
    ax3.set_frame_on(True)
    ax3.patch.set_visible(False)
    ax3.spines["bottom"].set_visible(True)

    return ax3
Exemple #20
0
def make_twiny(offset):
    """
    """
    
    ax3 = plt.twiny()
    ax3.xaxis.set_ticks_position('bottom')
    ax3.spines['bottom'].set_position(('axes',-offset))
    ax3.set_frame_on(True)
    ax3.patch.set_visible(False)
    ax3.spines["bottom"].set_visible(True)
    
    return ax3
Exemple #21
0
    def loss_plotMytime(self, loss_type):
        #iters = self.mytime[loss_type] - self.mytime[loss_type][0];
        iters = np.array(self.mytime[loss_type])
        myiters = iters - iters[0]
        allepochs = range(len(self.losses[loss_type]))
        fig = plt.figure(figsize=(20, 15))
        ax1 = fig.add_subplot(111)
        # acc
        ax1.plot(allepochs, self.accuracy[loss_type], 'r', label='train acc')
        # loss
        ax1.plot(allepochs, self.losses[loss_type], 'g', label='train loss')
        ax1.lines.pop(0)
        ax1.lines.pop(0)

        ax2 = plt.twiny()
        # 顶上X轴为时间信息
        # acc
        ax2.plot(myiters, self.accuracy[loss_type], 'r', label='train acc')
        # loss
        ax2.plot(myiters, self.losses[loss_type], 'g', label='train loss')

        if loss_type == 'epoch':
            # val_acc
            ax1.plot(allepochs, self.val_acc[loss_type], 'b', label='val acc')
            # val_loss
            ax1.plot(allepochs,
                     self.val_loss[loss_type],
                     'k',
                     label='val loss')
            ax1.lines.pop(0)
            ax1.lines.pop(0)

            # val_acc
            ax2.plot(myiters, self.val_acc[loss_type], 'b', label='val acc')
            # val_loss
            ax2.plot(myiters, self.val_loss[loss_type], 'k', label='val loss')

        ax1.set_xlabel(loss_type, fontsize=25)
        ax2.set_xlabel('time(s)', fontsize=25)
        ax2.legend(loc="upper right", ncol=2, fontsize=24)
        ax1.set_ylabel('acc-loss', fontsize=25)
        ax1.locator_params("x", nbins=20)
        ax2.locator_params("x", nbins=20)

        ax1.grid(True)

        ax = plt.gca()
        ax.set_ylim(0, 1.2)
        plt.setp(ax1.get_xticklabels(), fontsize=20)
        plt.setp(ax2.get_xticklabels(), fontsize=20)
        plt.setp(ax1.get_yticklabels(), fontsize=20)
        plt.savefig('trainprocess.png')
        plt.show()
def plot_feature(feature):
    plt.plot(mavgmemcache.index, mavgmemcache[feature], label='modified memcache')
    plt.plot(oavgmemcache.index, oavgmemcache[feature], label='original memcache')
    plt.legend()
    plt.axvline(x = 120, color  = "red", linestyle = "dashed")
    plot_top = plt.twiny()

    top_stick = [120]
    top_label = ["restart"]
    plot_top.set_xticks(top_stick)
    plot_top.set_xticklabels(top_label)
    plt.title(feature + " comparison")
    plt.show()
Exemple #23
0
def case_three(filename):
    with open(filename) as f:
        data = map(lambda line: map(int, line.split(',')), f.readlines())

    plots = {}
    for d in data:
        lock = d[3]
        if lock in plots:
            plots[lock][0].append(d[2])  # c
            plots[lock][1].append(d[4])  # time
        else:
            plots[lock] = [[d[2]], [d[4]]]

    for (lock, (x, y)) in plots.items():
        if lock == 1:
            lock_name = 'Pthread Mutex Lock'
        elif lock == 2:
            lock_name = 'Pthread Spin Lock'
        elif lock == 3:
            lock_name = 'TAS Spin Lock'
        elif lock == 4:
            lock_name = 'TTAS Spin Lock'
        elif lock == 5:
            lock_name = 'Exponential Backoff Lock'
        else:
            lock_name = 'Queue Lock'
        pyplot.plot(range(len(x)), y, label='%s' % lock_name)

    pyplot.legend(loc='best')
    pyplot.xticks(range(11), (1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 0))
    pyplot.xlabel('Operations Inside Critical Section')
    pyplot.twiny()
    pyplot.xticks(range(11), (0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000))
    pyplot.xlabel('Operations Outside Critical Section')
    pyplot.ylabel('Running Time (ms)')
    pyplot.savefig('case_three.png')
    pyplot.clf()
Exemple #24
0
def addModifiedXAxis(xs, func,  label):
    import numpy as np
    dummy = [1. for _ in xs]
    lims = plt.xlim()
    lims = np.array(lims)
    xs = np.array(xs)
    ax = plt.twiny()
    ax.plot(func(xs),dummy)
    #ax.xlabel(label)
    ax.cla()
    ax.set_xlim(func(lims))
    ax.set_xlabel(label)
    return ax
    
    
Exemple #25
0
    def setup_axes(self):
        self.ax = plt.subplot(111)

        # Second Y axis on the right for the ZHR 
        self.ax_zhr = plt.twinx(ax=self.ax)
        self.ax_zhr.set_ylabel("ZHR (r={0:.1f}, $\gamma$={1:.2f})".format(
                                                self.profile.popindex,
                                                self.profile.gamma))
        self.ax_zhr.yaxis.set_major_formatter(plt.FuncFormatter(self.zhr_formatter))
        
        # Second X axis as top for the solar longitude
        self.ax2 = plt.twiny(ax=self.ax)
        self.ax2.set_xlabel("Solar longitude (J2000.0)")
        self.ax2.xaxis.set_major_formatter(plt.FuncFormatter(self.sollon_formatter))
          
        self.ax.grid(which="both")
Exemple #26
0
def labelnai(color='gray', zorder=1, twins=True, **kwargs):
    importmpl()
    import gbm
    for (i, (detp, dett)) in enumerate(gbm.naipt.T):
        plt.text(detp, dett, gbm.nlist[i], horizontalalignment='center', verticalalignment='center', color=color, zorder=zorder, *kwargs)
    plt.xlabel(r'spacecraft $\phi$ [rad]')
    plt.ylabel(r'spacecraft $\theta$ [rad]')
    # plt.subplots_adjust(top=0.875)
    plt.setp(plt.gca(), xlim=[0, 2*np.pi], ylim=[np.pi, 0])
    plt.gca().xaxis.tick_bottom()
    plt.gca().yaxis.tick_left()
    if twins:
        ax2 = plt.twinx()
        plt.setp(ax2, ylim=[180, 0])
        ay2 = plt.twiny()
        plt.setp(ay2, xlim=[0, 360])
Exemple #27
0
 def _create_figure():
     # create the figure with four subplots with different size
     # - 1st is for the predominant melody and performed notes
     # - 2nd is the pitch distribution and note models, it shares the y
     # axis with the 1st
     # - 3rd is the melodic progression, it shares the x axis with the 1st
     # - 4th is for the sections, it is on top the 3rd
     fig = plt.figure()
     gs = gridspec.GridSpec(2, 2, width_ratios=[6, 1], height_ratios=[4, 1])
     ax1 = fig.add_subplot(gs[0])  # pitch and notes
     ax2 = fig.add_subplot(gs[1], sharey=ax1)  # pitch dist. and note models
     ax4 = fig.add_subplot(gs[2])  # sections
     ax5 = fig.add_subplot(gs[3])  # makam, tempo, tonic, ahenk annotations
     ax3 = plt.twiny(ax4)  # melodic progression
     ax1.get_shared_x_axes().join(ax1, ax3)
     fig.subplots_adjust(hspace=0, wspace=0)
     return fig, ax1, ax2, ax3, ax4, ax5
Exemple #28
0
    def setup_axes(self):
        self.ax = plt.subplot(111)

        # Second Y axis on the right for the ZHR
        self.ax_zhr = plt.twinx(ax=self.ax)
        self.ax_zhr.set_ylabel("ZHR (r={0:.1f}, $\gamma$={1:.2f})".format(
            self.profile.popindex, self.profile.gamma))
        self.ax_zhr.yaxis.set_major_formatter(
            plt.FuncFormatter(self.zhr_formatter))

        # Second X axis as top for the solar longitude
        self.ax2 = plt.twiny(ax=self.ax)
        self.ax2.set_xlabel("Solar longitude (J2000.0)")
        self.ax2.xaxis.set_major_formatter(
            plt.FuncFormatter(self.sollon_formatter))

        self.ax.grid(which="both")
Exemple #29
0
 def _create_figure():
     # create the figure with four subplots with different size
     # - 1st is for the predominant melody and performed notes
     # - 2nd is the pitch distribution and note models, it shares the y
     # axis with the 1st
     # - 3rd is the melodic progression, it shares the x axis with the 1st
     # - 4th is for the sections, it is on top the 3rd
     fig = plt.figure()
     gs = gridspec.GridSpec(2, 2, width_ratios=[6, 1], height_ratios=[4, 1])
     ax1 = fig.add_subplot(gs[0])  # pitch and notes
     ax2 = fig.add_subplot(gs[1], sharey=ax1)  # pitch dist. and note models
     ax4 = fig.add_subplot(gs[2])  # sections
     ax5 = fig.add_subplot(gs[3])  # makam, tempo, tonic, ahenk annotations
     ax3 = plt.twiny(ax4)  # melodic progression
     ax1.get_shared_x_axes().join(ax1, ax3)
     fig.subplots_adjust(hspace=0, wspace=0)
     return fig, ax1, ax2, ax3, ax4, ax5
def main():


	plt.figure(figsize=(6, 5), dpi=80)
	
	wyk1 = plt.subplot(121)
	
	rysowanie('rsel.csv', 'b')
	rysowanie('cel-rs.csv', 'g')
	rysowanie('2cel-rs.csv', 'r')
	rysowanie('cel.csv', 'k')
	rysowanie('2cel.csv', 'm')  

	plt.grid(linewidth=0.5, color='grey')
	plt.axis((0,500,60,100), size="small")
	wyk1.tick_params(labelsize="small")

	plt.xlabel('Rozegranych gier (x1000)', size="small")
	plt.ylabel('Odsetek wygranych gier [%]', size="small")	

	legenda = plt.legend(['1-Evol-RS','1-Coev-RS','2-Coev-RS','1-Coev','2-Coev'], loc="lower right", prop={'size':'x-small'}, fancybox=True)

	legenda.get_frame().set_alpha(0.75)
	legenda.get_frame().set_linewidth(0.5)

	wyk2 = plt.twiny()
	plt.axis([0,200,60,100], size="small")
	wyk2.set_xticks([0,40,80,120,160,200])
	wyk2.tick_params(labelsize="small")
	plt.xlabel('Pokolenie', size="small")


	names_list=['1-Evol-RS','1-Coev-RS','2-Coev-RS','1-Coev','2-Coev']
	
	plt.subplot(122)
	#plt.boxplot(box_list, notch = True, labels = names_list, showmeans=True, meanprops=dict(marker='o'))
	frame = plt.gca()
	plt.grid()
	frame.axes.get_yaxis().set_visible(False)
	plt.twinx()
	plt.grid()
	plt.axis([0,6,60,100])
	
	
	plt.savefig('myplot.jpg')
	plt.close()
Exemple #31
0
def plot_(axes, phi,t,Ecombined_i,rate_0pi,p_final_0pi,N0p):
    '''just a funtion to plot it'''
    axes.plot(t,Ecombined_i,'b',lw=2)
    axes.fill(t,rate_0pi/np.max(rate_0pi)*0.05*np.sign(p_final_0pi),'k',alpha=.2)
    axes.set_title(r'{0}$\pi$'.format(phi), y=1.05)
    axes.set_xlabel('time/a.u.')
    axes.set_ylabel('electric field/a.u.(blue)')
    axes.set_xlim(-110,110)
    ax2 = plt.twinx(axes)
    # ax2.plot(t,p_final_SMM,'g')
    ax2.plot(t,p_final_0pi,'r')
    ax2.set_xlim(-110,110)
    ax2.set_ylabel('final momentum/a.u.(red)')
    ax3 = plt.twiny(ax2)
    plt.hist(p_final_0pi, bins=50, weights=rate_0pi*N0p, color='r', alpha=.5, label='0pi',
                            orientation='horizontal', fill=True, histtype='bar') #
    ax3.invert_xaxis()
    ax3.set_xlim(0.01,0)
Exemple #32
0
def draw_left(m_list, ox_list, series):
    s1 = plt.subplot(1, 2, 1)
    [i.set_linewidth(0.5) for i in s1.spines.itervalues()]
    plt.xlim(xmax=500)
    plt.axis(siez='small')
    plt.grid(True, alpha=0.5, linewidth=0.3)
    plt.tick_params(labelsize='x-small')
    i = 0
    for c, l, mark in series:
        plt.plot(ox_list[i], m_list[i], color=c, label=l, marker=mark, markersize=5, markevery=25, alpha=0.8)
        i += 1
    legend = plt.legend(loc = 'lower right', framealpha=0.5, fontsize='small', fancybox=True, prop={'size': 'x-small'})
    legend.get_frame().set_linewidth(0.5)
    plt.xlabel('Rozegranych gier ($\\times$ 1000)', size='x-small')
    plt.ylabel('Odsetek wygranych gier [$\%$]', size='x-small')
    s2 = plt.twiny()
    plt.xlabel('Pokolenie', size='x-small')
    s2.set_xticks([0, 40, 80, 120, 160, 200])
    s2.tick_params(labelsize='x-small')
def make_plot(ratio_grids, significant_indices, plot_title, column_titles,
              pop_pair_names):
    combined_grids = np.hstack(ratio_grids)
    r = max(1 - np.min(combined_grids), np.max(combined_grids) - 1)
    plt.pcolor(np.hstack(ratio_grids), vmin=1 - r, vmax=1 + r, cmap='seismic')
    plt.colorbar()

    xtick_values = len(ratio_grids) * list('ACGT')
    xtick_values[0] = "3'-A"
    plt.xticks(np.arange(.5, 4 * len(ratio_grids)), xtick_values, rotation=90)
    plt.yticks(ypos, ylabel)

    for k in range(len(ratio_grids)):
        plt.axvline(x=4 * k, color='black')

    for k in range(0, len(ratio_grids[0]), 4):
        plt.axhline(y=k, color='black', linestyle='dashed')

    top_x_axis = plt.twiny()  # Create a twin Axes sharing the yaxis, lol
    top_x_axis.set_xticks(np.arange(2, 4 * len(ratio_grids), 4))
    top_x_axis.set_xticklabels(column_titles)

    combined_x_positions = []
    combined_y_positions = []
    for i, (x_positions, y_positions) in enumerate(significant_indices):
        for x, y in zip(x_positions, y_positions):
            combined_x_positions.append(x + 4 * i)
            combined_y_positions.append(y)
    plt.scatter(combined_x_positions,
                combined_y_positions,
                marker='.',
                color='white')

    plt.xlim(0, len(combined_grids[0]))
    plt.ylim(0, len(combined_grids))

    plt.title(plot_title + '\n')

    plt.gcf()
    pop_pair_names = '_'.join(pop_pair_names)
    plt.savefig('heatmap_{}.pdf'.format(pop_pair_names), format='pdf')
    plt.clf()
def plot_age(p, form, fof_np, age_labels, symbls):
    lims = 10.**np.linspace(9, 15, (15.25 - 9) /
                            .25)  #These are the limits for the mass bins
    for (i, form_i) in enumerate(form):
        (avg, med) = binning(fof_np[i], form_i, lims)
        plt.semilogx(avg[0], avg[1], marker = symbls[i], subsx = [2, 3, 4, 5, 6, 7, 8, 9], \
                     label = 'Average {0}'.format(age_labels[i]))
        plt.semilogx(med[0],
                     med[1],
                     linestyle='dashed',
                     label='Median {0}'.format(age_labels[i]))
    #MS = 13.5795 - 10.3112 * np.arcsinh(0.0504329 * avg[0] ** 0.08445)
    #plt.semilogx(avg[0], MS, 'r', label = 'MS Curve')
    plt.legend()
    plt.xlabel('M [M_sun / h]')
    plt.ylabel('Formation Age Lookback time [Gyr]')
    ##Create Second x axis
    xlims = plt.xlim()
    x2 = plt.twiny()
    x2.set_xscale('log')
    x2.set_xlim((xlims[0] / .73, xlims[1] / .73))
    x2.set_xlabel('M [M_sun]')

    ##Create second y axis

    ylims = plt.ylim()
    yt = plt.yticks()[0]
    y2 = plt.twinx()
    y2.set_ylim(ylims)
    y2.set_yticks(yt)
    yl = []
    for j in yt:
        if j < 13.5795:
            yl.append('{:5.2f}'.format(1.44224957031 /
                                       mth.sinh(0.0969815 *
                                                (13.5795 - j))**(2. / 3.)))
        else:
            yl.append('')
    y2.set_yticklabels(yl)
    y2.set_ylabel('z + 1')
Exemple #35
0
 def figure1(self, count=50):
   tha = self.theta_a
   thc = self.theta_c
   plt.xlabel(r'$t_c \mathrm{[nm]}$', size=15)
   plt.ylabel(r'$I_a/I_c$', size=15)
   plt.ylim(0, 60)
   plt.text(0.05, 50,
            '$T_{\mathrm{Fix}}=$'+str(self.T)+' $\mathrm{nm}$',
            horizontalalignment='left',
            verticalalignment='bottom',
            fontsize=20)
   ta = np.linspace(0, self.T, count)
   x = ta
   y = []
   for t1 in ta:
     val = self._get_I(t1, self.T-t1, tha, thc)
     y.append(val)
   plt.plot(x, y)
   ax = plt.twiny()
   ax.set_xlabel(r'$t_a \mathrm{[nm]}$', size=15)
   ax.set_xlim(self.T, 0)
   plt.show()
Exemple #36
0
def labelnai(color='gray', zorder=1, twins=True, **kwargs):
    importmpl()
    import gbm
    for (i, (detp, dett)) in enumerate(gbm.naipt.T):
        plt.text(detp,
                 dett,
                 gbm.nlist[i],
                 horizontalalignment='center',
                 verticalalignment='center',
                 color=color,
                 zorder=zorder,
                 *kwargs)
    plt.xlabel(r'spacecraft $\phi$ [rad]')
    plt.ylabel(r'spacecraft $\theta$ [rad]')
    # plt.subplots_adjust(top=0.875)
    plt.setp(plt.gca(), xlim=[0, 2 * np.pi], ylim=[np.pi, 0])
    plt.gca().xaxis.tick_bottom()
    plt.gca().yaxis.tick_left()
    if twins:
        ax2 = plt.twinx()
        plt.setp(ax2, ylim=[180, 0])
        ay2 = plt.twiny()
        plt.setp(ay2, xlim=[0, 360])
Exemple #37
0
 def makePlot(self):
     minx = np.min(self.powers)
     maxx = np.max(self.powers)
     xvals = np.linspace(minx, maxx, self.powers.size*100)
     yvals = self.fitfunc(xvals)
     pyplot.figure()
     pyplot.plot(self.powers, self.dataFluor, 'o', markersize=4)
     pyplot.plot(xvals,yvals)
     pyplot.ylim(ymin = 0)
     s = "Pulsed Axial Power Scan {}\n".format(self.name)
     s = s + "Detuning {0:.2f} Gamma\n".format(self.detuning)
     maxsat = maxx / self.xscalefit
     s = s +  "Max Saturation {0:.0f}\n".format(maxsat)
     s = s + "Power for s = 1 : {0:.2f} microwatt\n".format(1000 * self.xscalefit)
     Isat = 4.33*10**-7 #mW / micron^2, #see e.g aarhus phd peter staanum
     waist = np.sqrt(self.xscalefit/ Isat) / 2.0
     s = s + "Waist of ~{0:.0f} micron".format(waist)
     pyplot.text(0.5, 10000.0 , s )#,  verticalalignment='top')
     pyplot.xlabel('397 Power mW')
     pyplot.ylabel('Fluorescence Counts/Sec')
     ax = pyplot.twiny()
     pyplot.xlabel("Saturation =  Omega / Gamma")
     pyplot.xlim(xmin = minx / self.xscalefit, xmax = maxx/ self.xscalefit)
     pyplot.show()
def iord_bhmass_plot(iord_df,
                     time,
                     bins=300,
                     save=False,
                     filename='plots/distance/iord_%s_distance.png'):
    '''send individual iord dataframe, time array'''
    plt.clf()
    iord_id = iord_df.loc[0, 'iord']

    plt.hist(iord_df['time'],
             weights=iord_df['mass'],
             bins=bins,
             histtype='step',
             color='k',
             linewidth=.9)
    plt.title('BH %s Mass' % (iord_id), y=1.14)
    plt.ylabel('Mass [M$_\odot$]', fontsize='large')
    plt.xlabel('Time [Gyr]', fontsize='large')
    plt.xlim(-.25, 14)
    #plt.yscale('log')

    x0, x1 = plt.gca().get_xlim()
    old_axis = plt.gca()
    pz = plt.twiny()
    labelz = time_axis['z'][-6:]
    times = time_axis['time[Gyr]'][-6:]
    pz.set_xticks(times)
    pz.set_xticklabels([str(x) for x in labelz])
    pz.set_xlim(x0, x1)
    pz.set_xlabel('$z$')
    plt.sca(old_axis)

    plt.tight_layout()
    plt.subplots_adjust(top=1)
    if save == True:
        plt.savefig(filename % (iord_id), bbox_inches='tight', dpi=200)
Exemple #39
0
def add_at_risk_counts(*fitters, **kwargs):
    '''
    Add counts showing how many individuals were at risk at each time point in
    survival/hazard plots.

    Arguments:
      One or several fitters, for example KaplanMeierFitter,
      NelsonAalenFitter, etc...

    Keyword arguments (all optional):
      ax: The axes to add the labels to. Default is the current axes.
      fig: The figure of the axes. Default is the current figure.
      labels: The labels to use for the fitters. Default is whatever was
              specified in the fitters' fit-function. Giving 'None' will
              hide fitter labels.

    Returns:
      ax: The axes which was used.

    Examples:
        # First train some fitters and plot them
        fig = plt.figure()
        ax = plt.subplot(111)

        f1 = KaplanMeierFitter()
        f1.fit(data)
        f1.plot(ax=ax)

        f2 = KaplanMeierFitter()
        f2.fit(data)
        f2.plot(ax=ax)

        # There are equivalent
        add_at_risk_counts(f1, f2)
        add_at_risk_counts(f1, f2, ax=ax, fig=fig)
        # This overrides the labels
        add_at_risk_counts(f1, f2, labels=['fitter one', 'fitter two'])
        # This hides the labels
        add_at_risk_counts(f1, f2, labels=None)
    '''
    from matplotlib import pyplot as plt

    # Axes and Figure can't be None
    ax = kwargs.get('ax', None)
    if ax is None:
        ax = plt.gca()

    fig = kwargs.get('fig', None)
    if fig is None:
        fig = plt.gcf()

    if 'labels' not in kwargs:
        labels = [f._label for f in fitters]
    else:
        # Allow None, in which case no labels should be used
        labels = kwargs['labels']
        if labels is None:
            labels = [None] * len(fitters)
    # Create another axes where we can put size ticks
    ax2 = plt.twiny(ax=ax)
    # Move the ticks below existing axes
    # Appropriate length scaled for 6 inches. Adjust for figure size.
    ax2_ypos = -0.15 * 6.0 / fig.get_figheight()
    move_spines(ax2, ['bottom'], [ax2_ypos])
    # Hide all fluff
    remove_spines(ax2, ['top', 'right', 'bottom', 'left'])
    # Set ticks and labels on bottom
    ax2.xaxis.tick_bottom()
    # Match tick numbers and locations
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(ax.get_xticks())
    # Remove ticks, need to do this AFTER moving the ticks
    remove_ticks(ax2, x=True, y=True)
    # Add population size at times
    ticklabels = []
    for tick in ax2.get_xticks():
        lbl = ""
        for f, l in zip(fitters, labels):
            # First tick is prepended with the label
            if tick == ax2.get_xticks()[0] and l is not None:
                if is_latex_enabled():
                    s = "\n{}\\quad".format(l) + "{}"
                else:
                    s = "\n{}   ".format(l) + "{}"
            else:
                s = "\n{}"
            lbl += s.format(f.durations[f.durations >= tick].shape[0])
        ticklabels.append(lbl.strip())
    # Align labels to the right so numbers can be compared easily
    ax2.set_xticklabels(ticklabels, ha='right')

    # Add a descriptive headline.
    ax2.xaxis.set_label_coords(0, ax2_ypos)
    ax2.set_xlabel('At risk')

    plt.tight_layout()
    return ax
Exemple #40
0
def plot(ocd,
        calib,
        file_name = "test.jpg",
        use_model = True):

    fig = plt.figure(figsize=(8,2))
    ax1 = plt.subplot(111)
    plt.ylabel("C14 age (BP)", fontsize=11)

    plt.text(-0.14, -0.11,"Date (BC)",
         horizontalalignment='left',
         verticalalignment='bottom',
         transform = ax1.transAxes,
         size=11)

    plt.text(0.0, 0.97,"pyC14 v0.1; Xtof; Ard-team",
         horizontalalignment='left',
         verticalalignment='bottom',
         transform = ax1.transAxes,
         size=7,
         bbox=dict(facecolor='white', alpha=1, lw=0))

    comments = ""
    comments += ocd.ref + "\n"
    comments += calib.ref + "\n"

    plt.text(0.55, 0.85,'{}'.format(comments),
         horizontalalignment='left',
         verticalalignment='center',
         transform = ax1.transAxes,
         size=8,
         bbox=dict(facecolor='white', alpha=0.9, lw=0))


    alphaY = 8
    if(ocd.posterior.used and use_model):
        calibrated = ocd.posterior
        alphaY = 6
    else:
        calibrated = ocd.likelihood

    # Calendar Age
    # imitate OxCal
    ax2 = plt.twinx()

    ax2.fill(
        calibrated.calibAxis,
        calibrated.prob + max(calibrated.prob)*0.3,
        'k',
        alpha=0.3
        )
    ax2.plot(
        calibrated.calibAxis,
        calibrated.prob + max(calibrated.prob)*0.3,
        'k',
        alpha=0.8
        )

    ax2.set_ybound(min(calibrated.prob),max(calibrated.prob)*1.7)
    tl = len(calibrated.calibAxis)
    ax2.set_xbound(calibrated.array[0,0],calibrated.array[-1,0])
    ax2.set_axis_off()

    # Radiocarbon Age
    sample_interval = np.arange(ocd.date-4*ocd.error, ocd.date+4*ocd.error,1.)
    sample_curve = normpdf(sample_interval, ocd.date, ocd.error)
    line_x = np.array([0, 1])
    line_y = np.array([ocd.date, ocd.date])

    ax3 = plt.twiny(ax1)
    for i in range(-1,2,1):
        ax3.plot(
            line_x,
            line_y+i*ocd.error,
            'k--',
            alpha=0.5-0.2*abs(i),
            lw=1.5-abs(i)
            )
    ax3.fill(
        sample_curve,
        sample_interval,
        'r',
        alpha=0.3
        )
    ax3.plot(
        sample_curve,
        sample_interval,
        'r',
        alpha=0.3,
        label='Radiocarbon determination (BP)'
        )
    ax3.set_xbound(0,max(sample_curve)*4)
    ax3.set_axis_off()

    # Calibration Curve
    xs, ys = mlab.poly_between(calib.array[:,0],
                               calib.array[:,1] - calib.array[:,2],
                               calib.array[:,1] + calib.array[:,2])
    ax1.fill(xs, ys, 'b', alpha=0.3)

    # Confidence intervals
    ymin=[0.14, 0.10, 0.06]

    for j in range(2,-1,-1):
        for i in calibrated.range[j]:
            ax1.axvspan(
                i[0], i[1],
                ymin=ymin[j],
                ymax=ymin[j]+0.07,
                facecolor='none',
                alpha=0.8)
            ax1.axvspan(
                i[0], i[1],
                ymin=ymin[j]+0.03,
                ymax=ymin[j]+0.07,
                facecolor='w',
                edgecolor='w',
                lw=2)

    # FIXME the following values 10 and 5 are arbitrary and could be probably
    # drawn from the f_m value itself, while preserving their ratio
    detla_BP = ocd.likelihood.mean - calibrated.mean
    ax1.set_ybound(ocd.date - ocd.error*alphaY + detla_BP, ocd.date + ocd.error*alphaY + detla_BP)
    ax1.set_xbound(calibrated.array[0,0],calibrated.array[-1,0])

    #plt.savefig('image_%d±%d.pdf' %(f_m, sigma_m))
    plt.savefig(file_name)
    fig = plt.gcf()
    fig.clear()
#'right'        : 5,
#'center left'  : 6,
#'center right' : 7,
#'lower center' : 8,
#'upper center' : 9,
#'center'       : 10,
plt.legend(loc=3,title='Time [y]')
# xx-small, x-small, small, medium, large, x-large, xx-large, 12, 14
plt.setp(plt.gca().get_legend().get_texts(),fontsize='small')
#plt.setp(plt.gca().get_legend().get_texts(),linespacing=0.)
plt.setp(plt.gca().get_legend().get_frame().set_fill(False))
plt.setp(plt.gca().get_legend().draw_frame(False))
plt.setp(plt.gca().get_legend().get_texts(),fontsize='small')
#plt.gca().yaxis.get_major_formatter().set_powerlimits((-1,1))

plt.twiny()
plt.xlabel('Saturation [-]')
plt.xlim(0.,1.05)
data = pft.Dataset(filenames[ifile],5,3)
plt.plot(data.get_array('x'),data.get_array('y'), \
         label='Saturation',color='black',ls='--')
plt.legend(loc=1)
# xx-small, x-small, small, medium, large, x-large, xx-large, 12, 14
plt.setp(plt.gca().get_legend().get_texts(),fontsize='small')
#plt.setp(plt.gca().get_legend().get_texts(),linespacing=0.)
plt.setp(plt.gca().get_legend().get_frame().set_fill(False))
plt.setp(plt.gca().get_legend().draw_frame(False))

f.subplots_adjust(hspace=0.2,wspace=0.2,
                  bottom=.12,top=.85,
                  left=.12,right=.9)
Exemple #42
0
 def _createPlot(self):
     bins = self._fluxdata.getBins()
     
     self._fig = plt.figure(figsize=(11,6), dpi=80) # 11*80 = 880 pixels wide !
     ax = plt.subplot(111)
     self._fig.subplots_adjust(0.1,0.17,0.92,0.87)
                    
     ax_zhr = plt.twinx(ax=ax)
     ax_zhr.set_ylabel("ZHR (r=%.1f, $\gamma$=%.2f)" % (self._fluxdata._popindex, self._fluxdata._gamma), fontsize=16)
     ax_zhr.yaxis.set_major_formatter(plt.FuncFormatter(self.zhr_formatter))
     
     ax2 = plt.twiny(ax=ax)
     ax2.set_xlabel("Solar longitude (J2000.0)", fontsize=16)
     ax2.xaxis.set_major_formatter(plt.FuncFormatter(self.sollon_formatter))
       
     ax.grid(which="both")
     
     if len(bins) > 0 and len(bins['time']) > 0:
         ax.errorbar(bins['time'], bins['flux'], yerr=bins['e_flux'], fmt="s", ms=4, lw=1.0, c='red' )    #fmt="+", ms=8    
     
     ax.set_xlim([self._begin, self._end])
     ax2.set_xlim([self._begin, self._end])
     ax_zhr.set_xlim([self._begin, self._end])
     
     # Determine the limit of the Y axis
     if self._ymax:
         my_ymax = self._ymax
     elif len(bins) == 0 or len(bins['time']) == 0:
     	my_ymax = 100
     else:
         my_ymax = 1.1*max(bins['flux']+bins['e_flux'])
     
     if len(bins) > 0:
         ax.set_ylim([0, my_ymax])
         ax2.set_ylim([0, my_ymax])
         ax_zhr.set_ylim([0, my_ymax])        
     
     
     if self._timespan > 90*24*3600: # 90 days
         """ More than 5 days: only show dates """
         majorLocator = mpl.dates.AutoDateLocator(maxticks=10)
         sollonLocator = majorLocator
         majorFormatter = mpl.dates.DateFormatter('%d %b')
         xlabel = "Date (UT, %s)" % self._begin.year   
                 
     elif self._timespan > 5*24*3600: # 5 days
         """ More than 5 days: only show dates """
         majorLocator = mpl.dates.AutoDateLocator(maxticks=10)
         sollonLocator = majorLocator
         majorFormatter = mpl.dates.DateFormatter('%d %b')
         xlabel = "Date (UT, %s)" % self._begin.year   
     
     elif self._timespan > 1*24*3600:
         """ Between 1 and 5 days: show hours """
         majorLocator = mpl.dates.HourLocator(byhour=[0])
         majorFormatter = mpl.dates.DateFormatter('%d %b')
         
         if self._timespan > 3*24*3600:
             t = 12
         elif self._timespan > 1.5*24*3600:
             t = 6
         else:
             t = 3
         byhour = np.arange(t, 24, t)
         
         minorLocator = mpl.dates.HourLocator(byhour=byhour)
         ax.xaxis.set_minor_locator(minorLocator)
         sollonLocator = mpl.dates.HourLocator(byhour=np.append(0, byhour))
         fmt2 = mpl.dates.DateFormatter('%H:%M')        
         ax.xaxis.set_minor_formatter(plt.FuncFormatter(fmt2))
         xlabel = "Date (UT, %s)" % self._begin.year   
         
     else:
         if self._timespan > 18*3600:
             majorLocator = mpl.dates.HourLocator( np.arange(0, 24, 3) ) 
             minorLocator = mpl.dates.HourLocator( np.arange(0, 24, 1) ) 
         elif self._timespan > 12*3600:
             majorLocator = mpl.dates.HourLocator( np.arange(0, 24, 2) ) 
             minorLocator = mpl.dates.HourLocator( np.arange(1, 24, 2) ) 
         elif self._timespan > 6*3600:
             majorLocator = mpl.dates.HourLocator( np.arange(0, 24, 1) ) 
             minorLocator = mpl.dates.MinuteLocator(  np.arange(0,60,30)  )
         elif self._timespan > 3*3600:
             majorLocator = mpl.dates.MinuteLocator(  np.arange(0,60,30)  )
             minorLocator = mpl.dates.MinuteLocator(  np.arange(0,60,15)  )
         elif self._timespan > 1*3600:
             majorLocator = mpl.dates.MinuteLocator( np.arange(0,60,15) ) 
             minorLocator = mpl.dates.MinuteLocator(  np.arange(0,60,5) )
         else:
             majorLocator = mpl.dates.MinuteLocator( np.arange(0,60,10) ) 
             minorLocator = mpl.dates.MinuteLocator(  np.arange(0,60,2) )
             
         
         majorFormatter = mpl.dates.DateFormatter('%H:%M')  
         ax.xaxis.set_minor_locator(minorLocator)
         sollonLocator = majorLocator
         xlabel = "Time (UT, %s)" % self._begin.strftime('%d %b %Y')
     
     ax.xaxis.set_major_formatter(plt.FuncFormatter(majorFormatter))    
     ax2.xaxis.set_major_locator(sollonLocator)
     ax.xaxis.set_major_locator(majorLocator)
     
     
             
     ax.set_ylabel("Meteoroids / 1000$\cdot$km$^{2}\cdot$h", fontsize=18)
     ax.set_xlabel(xlabel, fontsize=18)
     
     labels = ax.get_xmajorticklabels()
     plt.setp(labels, rotation=45, fontsize=14) 
     labels = ax.get_xminorticklabels()
     plt.setp(labels, rotation=45, fontsize=12)
Exemple #43
0
    def _PlotLC(self,folded=False):
        self.info("Reading files produced by enrico")
        LcOutPath = self.LCfolder + self.config['target']['name']

        #Result are stored into list. This allow to get rid of the bin which failled
        Time = []
        TimeErr = []
        Flux = []
        FluxErr = []
        # FluxErrChi2 = []
        Index = []
        IndexErr = []
        Cutoff = []
        CutoffErr = []
        FluxForNpred = []
        # FluxErrForNpred = []
        Npred = []
        Npred_detected_indices = []
        TS = []
        uplim = []

        # Find name used for index parameter
        if (self.config['target']['spectrum'] == 'PowerLaw' or
                self.config['target']['spectrum'] == 'PowerLaw2'):
                IndexName = 'Index'
                CutoffName = None
        elif (self.config['target']['spectrum'] == 'PLExpCutoff' or
                self.config['target']['spectrum'] == 'PLSuperExpCutoff'):
            IndexName = 'Index1'
            CutoffName = 'Cutoff'
            CutoffErrName = 'dCutoff'
        else:
            IndexName = 'alpha'
            CutoffName = None
        IndexErrName = 'd' + IndexName

        Nfail = 0
        for i in xrange(self.Nbin):
            CurConfig = get_config(self.configfile[i])
            #Read the result. If it fails, it means that the bins has not bin computed. A warning message is printed
            try :
                ResultDic = utils.ReadResult(CurConfig)
                if ResultDic == {}:
                    raise(ValueError)
            except :
                self._errorReading("Fail reading config file",i)
                Nfail+=1
                continue

            #Update the time and time error array
            Time.append((ResultDic.get("tmax")+ResultDic.get("tmin"))/2.)
            TimeErr.append((ResultDic.get("tmax")-ResultDic.get("tmin"))/2.)
            #Check is an ul have been computed. The error is set to zero for the TGraph.
            if ResultDic.has_key('Ulvalue') :
                uplim.append(1)
                Flux.append(ResultDic.get("Ulvalue"))
                # FluxErr.append(0)
                # FluxErrChi2.append(ResultDic.get("dFlux"))
                # Index.append(ResultDic.get(IndexName))
                # IndexErr.append(0)
            else :
                uplim.append(0)
                Flux.append(ResultDic.get("Flux"))
            FluxErr.append(ResultDic.get("dFlux"))
            # FluxErrChi2.append(ResultDic.get("dFlux"))
            Index.append(ResultDic.get(IndexName))
            IndexErr.append(ResultDic.get(IndexErrName))
                # if CutoffName is not None:
                    # Cutoff.append(ResultDic.get(CutoffName))
                    # CutoffErr.append(ResultDic.get(CutoffErrName))
            # FluxErrForNpred.append(ResultDic.get("dFlux"))
            FluxForNpred.append(ResultDic.get("Flux"))
            #Get the Npred and TS values
            Npred.append(ResultDic.get("Npred"))
            TS.append(ResultDic.get("TS"))
            if (CurConfig['LightCurve']['TSLightCurve']<float(ResultDic.get("TS"))):
                Npred_detected_indices.append(i-Nfail)

        # #change the list into np array
        # TS = np.array(TS)
        Npred = np.asarray(Npred)
        Npred_detected = np.asarray(Npred[Npred_detected_indices])
        Time = np.asarray(Time)
        TimeErr = np.asarray(TimeErr)
        Flux = np.asarray(Flux)
        FluxErr = np.asarray(FluxErr)
        # Index = np.array(Index)
        # IndexErr = np.array(IndexErr)
        # Cutoff = np.array(Cutoff)
        # CutoffErr = np.array(CutoffErr)
        FluxForNpred = np.asarray(FluxForNpred)
        # FluxErrForNpred = np.array(FluxErrForNpred)
        uplim = np.asarray(uplim,dtype=bool)
        #Plots the diagnostic plots is asked
        # Plots are : Npred vs flux
        #             TS vs Time
        if self.config['LightCurve']['DiagnosticPlots'] == 'yes' and len(Npred)>0:
            #plot Npred vs flux
            plt.figure()
            NdN = np.asarray(Npred) /np.sqrt(Npred)
            FdF = np.asarray(FluxForNpred) / (np.asarray(FluxErr) + 1e-20)
            plt.errorbar(NdN, FdF,fmt='+',color='black')

            if len(Npred_detected)>0:
                NdN = np.asarray(Npred_detected) /np.sqrt(Npred_detected)
                FdF = np.asarray(FluxForNpred[Npred_detected_indices]) / (np.asarray(FluxErr[Npred_detected_indices]) + 1e-20)
                plt.errorbar(NdN, FdF,fmt='+',color='red')

                popt,_ = scipy.optimize.curve_fit(pol1, NdN, FdF, p0=[0,1])#, sigma=dydata)


                for i in xrange(len(FluxForNpred)):
                    if FluxForNpred[i]/FluxErr[i]>2*pol1(sqrt(Npred[i]),popt[0],popt[1]):
                        self._errorReading("problem in errors calculation for",i)
                        print "Flux +/- error = ",FluxForNpred[i]," +/- ",FluxErr[i]
                        print "V(Npred) = ",sqrt(Npred[i])
                        print 

                plt.plot(np.array([0,max(NdN)]),pol1(np.array([0,max(NdN)]),popt[0],popt[1]),'--',color='black')
                plt.xlabel(r"${\rm Npred/\sqrt{Npred}}$")
                plt.ylabel(r"${\rm Flux/\Delta Flux}$")
                plt.savefig(LcOutPath+"_Npred.png", dpi=150, facecolor='w', edgecolor='w',
                    orientation='portrait', papertype=None, format=None,
                    transparent=False, bbox_inches=None, pad_inches=0.1,
                    frameon=None)
            else :
                print "No Npred Plot produced"

            #plot TS vs Time
            plt.figure()
            plt.xlabel(r"Time (s)")
            plt.ylabel(r"Test Statistic")
            plt.errorbar(x=Time,y=TS,xerr=TimeErr,fmt='+',color='black',ls='None')
            plt.ylim(ymin=min(TS)*0.8,ymax=max(TS)*1.2)
            plt.xlim(xmin=max(plt.xlim()[0],1.02*min(Time)-0.02*max(Time)),xmax=min(plt.xlim()[1],1.02*max(Time)-0.02*min(Time)))
            
            # Move the offset to the axis label
            ax = plt.gca()
            ax.get_yaxis().get_major_formatter().set_useOffset(False)
            offset_factor = int(np.mean(np.log10(np.abs(ax.get_ylim()))))
            if (offset_factor != 0):
                ax.set_yticklabels([float(round(k,5)) for k in ax.get_yticks()*10**(-offset_factor)])
                ax.yaxis.set_label_text(ax.yaxis.get_label_text() + r" [${\times 10^{%d}}$]" %offset_factor)
            
            # Secondary axis with MJD
            mjdaxis = plt.twiny()
            mjdaxis.set_xlim([utils.met_to_MJD(k) for k in ax.get_xlim()])
            mjdaxis.set_xlabel(r"Time (MJD)")
            plt.tight_layout()
            
            plt.savefig(LcOutPath+"_TS.png", dpi=150, facecolor='w', edgecolor='w',
                    orientation='portrait', papertype=None, format=None,
                    transparent=False, bbox_inches=None, pad_inches=0.1,
                    frameon=None)


#    Plot the LC itself. This function return a TH2F for a nice plot
#    a TGraph and a list of TArrow for the ULs
        # if folded:
        #     phase = np.linspace(0,1,self.Nbin+1)
        #     Time = (phase[1:]+phase[:-1])/2.
        #     TimeErr = (phase[1:]-phase[:-1])/2.
        #     gTHLC,TgrLC,ArrowLC = plotting.PlotFoldedLC(Time,TimeErr,Flux,FluxErr)
        #     gTHIndex,TgrIndex,ArrowIndex = plotting.PlotFoldedLC(Time,TimeErr,Index,IndexErr)
        #     if CutoffName is not None:
        #         gTHCutoff,TgrCutoff,ArrowCutoff = plotting.PlotFoldedLC(Time,TimeErr,Cutoff,CutoffErr)
        # else :
        #     gTHLC,TgrLC,ArrowLC = plotting.PlotLC(Time,TimeErr,Flux,FluxErr)
        #     gTHIndex,TgrIndex,ArrowIndex = plotting.PlotLC(Time,TimeErr,Index,IndexErr)
        #     if CutoffName is not None:
        #         gTHCutoff,TgrCutoff,ArrowCutoff = plotting.PlotFoldedLC(Time,TimeErr,Cutoff,CutoffErr)

        # xmin = min(Time) - max(TimeErr) * 10
        # xmax = max(Time) + max(TimeErr) * 10
        # ymin = min(Flux) - max(FluxErr) * 1.3
        # ymax = max(Flux) + max(FluxErr) * 1.3
        plt.figure()
        plt.xlabel(r"Time (s)")
        plt.ylabel(r"${\rm Flux\ (photon\ cm^{-2}\ s^{-1})}$")
        # plt.ylim(ymin=ymin,ymax=ymax)
        # plt.xlim(xmin=xmin,xmax=xmax)
        #plt.errorbar(Time,Flux,xerr=TimeErr,yerr=FluxErr,fmt='o',color='black',ls='None',uplims=uplim)
        plot_errorbar_withuls(Time,TimeErr,TimeErr,Flux,FluxErr,FluxErr,uplim,bblocks=True)
        plt.ylim(ymin=max(plt.ylim()[0],np.percentile(Flux[~uplim],1)*0.1),
                 ymax=min(plt.ylim()[1],np.percentile(Flux[~uplim],99)*2.0))
        plt.xlim(xmin=max(plt.xlim()[0],1.02*min(Time)-0.02*max(Time)),
                 xmax=min(plt.xlim()[1],1.02*max(Time)-0.02*min(Time)))
        
        # Move the offset to the axis label
        ax = plt.gca()
        ax.get_yaxis().get_major_formatter().set_useOffset(False)
        offset_factor = int(np.mean(np.log10(np.abs(ax.get_ylim()))))
        if (offset_factor != 0):
            ax.set_yticklabels([float(round(k,5)) for k in ax.get_yticks()*10**(-offset_factor)])
            ax.yaxis.set_label_text(ax.yaxis.get_label_text() + r" [${\times 10^{%d}}$]" %offset_factor)
        
        # Secondary axis with MJD
        mjdaxis = plt.twiny()
        mjdaxis.set_xlim([utils.met_to_MJD(k) for k in ax.get_xlim()])
        mjdaxis.set_xlabel(r"Time (MJD)")
        plt.tight_layout()
 
        plt.savefig(LcOutPath+"_LC.png", dpi=150, facecolor='w', edgecolor='w',
                orientation='portrait', papertype=None, format=None,
                transparent=False, bbox_inches=None, pad_inches=0.1,
                frameon=None)

        if self.config["LightCurve"]["SpectralIndex"] == 0 :
            plt.figure()
            plt.xlabel(r"Time (s)")
            plt.ylabel(r"${\rm Index}$")
            Index = np.asarray(Index)
            IndexErr = np.asarray(IndexErr)
            uplimIndex = uplim + Index<0.55
            plot_errorbar_withuls(Time[~uplimIndex],TimeErr[~uplimIndex],TimeErr[~uplimIndex],
                                  Index[~uplimIndex],IndexErr[~uplimIndex],IndexErr[~uplimIndex],
                                  uplimIndex[~uplimIndex],bblocks=True)
            
            plt.ylim(ymin=max(plt.ylim()[0],np.percentile(Index[~uplimIndex],1)*0.1),ymax=min(plt.ylim()[1],np.percentile(Index[~uplimIndex],99)*2.0))
            plt.xlim(xmin=max(plt.xlim()[0],1.02*min(Time)-0.02*max(Time)),xmax=min(plt.xlim()[1],1.02*max(Time)-0.02*min(Time)))
            
            plt.savefig(LcOutPath+"_Index.png", dpi=150, facecolor='w', edgecolor='w',
                orientation='portrait', papertype=None, format=None,
                transparent=False, bbox_inches=None, pad_inches=0.1,
                frameon=None)
        

        # compute Fvar and probability of being cst

        self.info("Flux vs Time: infos")
        self.FitWithCst(Time,Flux,FluxErr)
        self.Fvar(Flux,FluxErr)

        # ### plot and save the Index LC
        # CanvIndex = ROOT.TCanvas()
        # gTHIndex.Draw()
        # TgrIndex.Draw('zP')

        # #plot the ul as arrow
        # for i in xrange(len(ArrowIndex)):
        #     ArrowIndex[i].Draw()

        # #Save the canvas in the LightCurve subfolder
        # if self.config["LightCurve"]["SpectralIndex"] == 0 :
        #     self.info("Index vs Time")
        #     self.FitWithCst(Time,Index,IndexErr)
        #     CanvIndex.Print(LcOutPath+'_Index.png')
        #     CanvIndex.Print(LcOutPath+'_Index.eps')
        #     CanvIndex.Print(LcOutPath+'_Index.C')


        #Dump into ascii
        lcfilename = LcOutPath+"_results.dat"
        self.info("Write to Ascii file : "+lcfilename)
        WriteToAscii(Time,TimeErr,Flux,FluxErr,Index,IndexErr,Cutoff,CutoffErr,TS,Npred,lcfilename)

        if self.config["LightCurve"]['ComputeVarIndex'] == 'yes':
             self.VariabilityIndex()
		ax3 = plt.axes([left, bottom+height, width, height-0.3])
		ax3.set_title(str, fontsize=fs, ha='left', x=0, y=1.2)
		ax3.xaxis.set_major_formatter(NullFormatter())
		for label in ax3.get_yticklabels(): label.set_fontsize(fs)
		plt.ylabel('ACF', fontsize=fs)
		freqlag = np.arange(fwin)
		freqlag = freqlag - fwin/2. + 1.
		freqlag *= chan_bw
		ax3.plot(freqlag, tcut)
		ax3.grid()
		halfpower = np.median(tcut)
		halfpower = halfpower + (np.max(tcut) - halfpower) / 2.
		ax3.plot(freqlag, halfpower * np.ones(fwin, dtype=float),'g--')
		ax3.set_xlim(xmin=-fwin*chan_bw/2.+chan_bw,xmax=fwin*chan_bw/2.)
		ax3.set_ylim(ymin=np.min(tcut), ymax=np.max(tcut))
		axb3 = plt.twiny()
		axb3.xaxis.tick_top()
		axb3.xaxis.set_label_position("top")
		axb3.set_xlim(xmin=-fwin*chan_bw/2.+chan_bw,xmax=fwin*chan_bw/2.)
		for label in axb3.get_xticklabels(): label.set_fontsize(fs)

		# fcut
		ax4 = plt.axes([left-0.14, bottom+0.165, width-0.25, width-0.005])
		for label in ax4.get_xticklabels(): label.set_fontsize(fs)
		plt.xlabel('ACF', fontsize=fs)
		timelag = np.arange(twin)
		timelag = timelag - twin/2. + 1.
		timelag *= tsubint
		ax4.plot(fcut, timelag)
		ax4.grid()
		halfpower = np.min(fcut) + (np.max(fcut) - np.min(fcut)) / math.e 
Exemple #45
0
def sfh(sim, filename=None, massform=True, clear=False, legend=False,
        subplot=False, trange=False, bins=100, **kwargs):
    '''
    star formation history

    **Optional keyword arguments:**

       *trange*: list, array, or tuple
         size(t_range) must be 2. Specifies the time range.

       *bins*: int
         number of bins to use for the SFH

       *massform*: bool
         decides whether to use original star mass (massform) or final star mass

       *subplot*: subplot object
         where to plot SFH

       *legend*: boolean
         whether to draw a legend or not

       *clear*: boolean
         if False (default), plot on the current axes. Otherwise, clear the figure first.

    By default, sfh will use the formation mass of the star.  In tipsy, this will be
    taken from the starlog file.  Set massform=False if you want the final (observed)
    star formation history

    **Usage:**

    >>> import pynbody.plot as pp
    >>> pp.sfh(s,linestyle='dashed',color='k')


    '''

    if subplot:
        plt = subplot
    else:
        import matplotlib.pyplot as plt

    if "nbins" in kwargs:
        bins = kwargs['nbins']

    if 'nbins' in kwargs:
        bins = kwargs['nbins']
        del kwargs['nbins']

    if ((len(sim.g)>0) | (len(sim.d)>0)): simstars = sim.star
    else: simstars = sim

    if trange:
        assert len(trange) == 2
    else:
        trange = [simstars['tform'].in_units(
            "Gyr").min(), simstars['tform'].in_units("Gyr").max()]
    binnorm = 1e-9 * bins / (trange[1] - trange[0])

    trangefilt = filt.And(filt.HighPass('tform', str(trange[0]) + ' Gyr'),
                          filt.LowPass('tform', str(trange[1]) + ' Gyr'))
    tforms = simstars[trangefilt]['tform'].in_units('Gyr')

    if massform:
        try:
            weight = simstars[trangefilt][
                'massform'].in_units('Msol') * binnorm
        except (KeyError, units.UnitsException):
            warnings.warn(
                "Could not load massform array -- falling back to current stellar masses", RuntimeWarning)
            weight = simstars[trangefilt]['mass'].in_units('Msol') * binnorm
    else:
        weight = simstars[trangefilt]['mass'].in_units('Msol') * binnorm

    if clear:
        plt.clf()
    sfhist, thebins, patches = plt.hist(tforms, weights=weight, bins=bins,
                                        histtype='step', **kwargs)
    if not subplot:
        # don't set the limits
        #plt.ylim(0.0, 1.2 * np.max(sfhist))
        plt.xlabel('Time [Gyr]', fontsize='large')
        plt.ylabel('SFR [M$_\odot$ yr$^{-1}$]', fontsize='large')
    else:
        plt.set_ylim(0.0, 1.2 * np.max(sfhist))

    # Make both axes have the same start and end point.
    if subplot:
        x0, x1 = plt.get_xlim()
    else:
        x0, x1 = plt.gca().get_xlim()


    # add a z axis on top if it has not been already done by an earlier plot:
    from pynbody.analysis import pkdgrav_cosmo as cosmo
    c = cosmo.Cosmology(sim=sim)
    old_axis = plt.gca()

    if len(plt.gcf().axes)<2:
        pz = plt.twiny()
        labelzs = np.arange(5, int(sim.properties['z']) - 1, -1)
        times = [13.7 * c.Exp2Time(1.0 / (1 + z)) / c.Exp2Time(1) for z in labelzs]
        pz.set_xticks(times)
        pz.set_xticklabels([str(x) for x in labelzs])
        pz.set_xlim(x0, x1)
        pz.set_xlabel('$z$')
        plt.sca(old_axis)

    if legend:
        plt.legend(loc=1)
    if filename:
        logger.info("Saving %s", filename)
        plt.savefig(filename)

    return array.SimArray(sfhist, "Msol yr**-1"), array.SimArray(thebins, "Gyr")
Exemple #46
0
def plot_fr_by_time(steps,
                    firingRates,
                    selected,
                    actLevels,
                    model,
                    ratio,
                    shuffled,
                    nbTrials,
                    simuTime,
                    reversedChans,
                    seeds,
                    save=None):
    print "Plotting the 2-channels action selection competition for #%d" % model
    cols = ["grey", "blue", "green", "red"]
    fig = plt.figure(figsize=(10, 10))
    # specifications of the plot
    plt.xlabel('Time Steps', fontsize=12)
    plt.ylabel('Firing Rates (Hz)', fontsize=12)
    shuffleStr = "shuffled inputs" if shuffled else "non-shuffled inputs"
    revStr = "channels reversed" if reversedChans else ""
    seedStr = "seeds=[" + ",".join(map(str, seeds)) + "]"
    plt.title(
        '2-channels action selection competition FR\n#%d (over %d trials with %s)\n[ratio=%.3f %s simuTime=%dms %s]\n\n'
        % (model, nbTrials, shuffleStr, ratio, seedStr, simuTime, revStr),
        fontsize=10)
    plt.grid()
    plt.xticks(steps, fontsize=10)
    ax2 = plt.twiny()
    actLevels = map(lambda x: "(" + str(x[0]) + ",\n" + str(x[1]) + ")",
                    actLevels)
    ax2.set_xticks(steps)
    ax2.set_xticklabels(actLevels, fontsize=7)
    #legend
    p1 = Rectangle((0, 0), 1, 1, fc=cols[0])
    p2 = Rectangle((0, 0), 1, 1, fc=cols[1])
    p3 = Rectangle((0, 0), 1, 1, fc=cols[2])
    p4 = Rectangle((0, 0), 1, 1, fc=cols[3])
    p5 = mlines.Line2D(range(1),
                       range(1),
                       color="white",
                       marker='o',
                       markersize=8,
                       markerfacecolor="black")
    plt.legend([p1, p2, p3, p4, p5],
               ["No selection", "Channel 1", "Channel 2", "Error", "Selected"],
               bbox_to_anchor=(1.1, 1.),
               fontsize='x-small')
    # plotting
    avgFR1 = list()
    avgFR2 = list()
    for st in steps:
        thisStep = [[], []]
        for sd in seeds:
            thisStep[0].append(firingRates[sd][0][st])
            thisStep[1].append(firingRates[sd][1][st])
        avgFR1.append(np.mean(thisStep[0]))
        avgFR2.append(np.mean(thisStep[1]))
    plt.plot(steps, avgFR1, color=cols[1])
    plt.plot(steps, avgFR2, color=cols[2])
    for st, pt in zip(steps, selected):
        plt.scatter([st], [0], s=500, c=cols[int(pt)], edgecolor='')

    # if the filename is not defined in save variable
    if save is None:
        print "\tShowing plot"
        plt.show()
    else:
        print "\tPlot saved under the name %s" % save
        fig.savefig(save)
Exemple #47
0
def main(myjckt,util=False,savefileroot=[],toscreen=True):

    #CJB+ Prepare utilization data to be plotted
    #TODO The arrays should be formatted in a dedicated module in jacketSE
    t_util_list=np.array([[1,1]])  #CJB+
    count_t=1  #CJB+
    for i in myjckt.LoadFrameOuts.jacket_utilization.t_util:  #CJB+
        if i>=1:  #CJB+
            step=np.array([count_t,'r'])  #CJB+
        elif .8<=i<1:  #CJB+
            step=np.array([count_t,'m'])  #CJB+
        elif .6<=i<.8:  #CJB+
            step=np.array([count_t,'y'])  #CJB+
        elif .4<=i<.6:  #CJB+
            step=np.array([count_t,'g'])  #CJB+
        elif .2<=i<.4:  #CJB+
            step=np.array([count_t,'b'])  #CJB+
        else:  #CJB+
            step=np.array([count_t,'k'])  #CJB+
        count_t+=1  #CJB+
        t_util_list=np.vstack((t_util_list, step))  #CJB+
    t_util_list=np.delete(t_util_list,0,0)  #CJB+
    #print t_util_list  #CJB+

    cb_util_list=np.array([[1,1]])  #CJB+
    count_cb=1  #CJB+
    for j in myjckt.LoadFrameOuts.jacket_utilization.cb_util:  #CJB+
        if j>=1:  #CJB+
            step=np.array([count_cb,'r'])  #CJB+
        elif .8<=j<1:  #CJB+
            step=np.array([count_cb,'m'])  #CJB+
        elif .6<=j<8:  #CJB+
            step=np.array([count_cb,'y'])  #CJB+
        elif .4<=j<6:  #CJB+
            step=np.array([count_cb,'g'])  #CJB+
        elif .2<=j<.4:  #CJB+
            step=np.array([count_cb,'b'])  #CJB+
        else:  #CJB+
            step=np.array([count_cb,'k'])  #CJB+
        count_cb+=1  #CJB+
        cb_util_list=np.vstack((cb_util_list, step))  #CJB+
    cb_util_list=np.delete(cb_util_list,0,0)  #CJB+
    #print cb_util_list  #CJB+

    tower_Stressutil_list=np.array([[1,1]])  #CJB+
    count_tower=1  #CJB+
    for k in myjckt.LoadFrameOuts.tower_utilization.StressUtil:  #CJB+
        if k>=1:  #CJB+
            step=np.array([count_tower,'r'])  #CJB+
        elif .8<=k<1:  #CJB+
            step=np.array([count_tower,'m'])  #CJB+
        elif .6<=k<.8:  #CJB+
            step=np.array([count_tower,'y'])  #CJB+
        elif .4<=k<.6:  #CJB+
            step=np.array([count_tower,'g'])  #CJB+
        elif .2<=k<.4:  #CJB+
            step=np.array([count_tower,'b'])  #CJB+
        else:  #CJB+
            step=np.array([count_tower,'k'])  #CJB+
        count_tower+=1  #CJB+
        tower_Stressutil_list=np.vstack((tower_Stressutil_list, step))  #CJB+
    tower_Stressutil_list=np.delete(tower_Stressutil_list,0,0)  #CJB+
    #print tower_Stressutil_list  #CJB+

    tower_GLutil_list=np.array([[1,1]])  #CJB+
    count_tower=1  #CJB+
    for k in myjckt.LoadFrameOuts.tower_utilization.GLUtil:  #CJB+
        if k>=1:  #CJB+
            step=np.array([count_tower,'r'])  #CJB+
        elif .8<=k<1:  #CJB+
            step=np.array([count_tower,'m'])  #CJB+
        elif .6<=k<.8:  #CJB+
            step=np.array([count_tower,'y'])  #CJB+
        elif .4<=k<.6:  #CJB+
            step=np.array([count_tower,'g'])  #CJB+
        elif .2<=k<.4:  #CJB+
            step=np.array([count_tower,'b'])  #CJB+
        else:  #CJB+
            step=np.array([count_tower,'k'])  #CJB+
        count_tower+=1  #CJB+
        tower_GLutil_list=np.vstack((tower_GLutil_list, step))  #CJB+
    tower_GLutil_list=np.delete(tower_GLutil_list,0,0)  #CJB+
    #print tower_GLutil_list  #CJB+

    tower_EUshutil_list=np.array([[1,1]])  #CJB+
    count_tower=1  #CJB+
    for k in myjckt.LoadFrameOuts.tower_utilization.EUshUtil:  #CJB+
        if k>=1:  #CJB+
            step=np.array([count_tower,'r'])  #CJB+
        elif .8<=k<1:  #CJB+
            step=np.array([count_tower,'m'])  #CJB+
        elif .6<=k<.8:  #CJB+
            step=np.array([count_tower,'y'])  #CJB+
        elif .4<=k<.6:  #CJB+
            step=np.array([count_tower,'g'])  #CJB+
        elif .2<=k<.4:  #CJB+
            step=np.array([count_tower,'b'])  #CJB+
        else:  #CJB+
            step=np.array([count_tower,'k'])  #CJB+
        count_tower+=1  #CJB+
        tower_EUshutil_list=np.vstack((tower_EUshutil_list, step))  #CJB+
    tower_EUshutil_list=np.delete(tower_EUshutil_list,0,0)  #CJB+
    #print tower_EUshutil_list  #CJB+

    t_condensed=np.array([[1,1]])  #CJB+
    for m in range(len(t_util_list)):  #CJB+
        counter=(m/8+1)  #CJB+
        if t_util_list[m][1]=='r':  #CJB+
            step=np.array([counter, 'r'])  #CJB+
        elif t_util_list[m][1]=='m':  #CJB+
            step=np.array([counter, 'm'])  #CJB+
        elif t_util_list[m][1]=='y':  #CJB+
            step=np.array([counter, 'y'])  #CJB+
        elif t_util_list[m][1]=='g':  #CJB+
            step=np.array([counter, 'g'])  #CJB+
        elif t_util_list[m][1]=='b':  #CJB+
            step=np.array([counter, 'b'])  #CJB+
        else:  #CJB+
            step=np.array([counter, 'k'])  #CJB+
        t_condensed=np.vstack((t_condensed,step))  #CJB+
    t_condensed=np.delete(t_condensed,0,0)  #CJB+
    t_condensed=t_condensed[0:-1:8]  #CJB+
    #print t_condensed  #CJB+

    cb_condensed=np.array([[1,1]])  #CJB+
    for m in range(len(cb_util_list)):  #CJB+
        counter=(m/4+1)  #CJB+
        if cb_util_list[m][1]=='r':  #CJB+
            step=np.array([counter, 'r'])  #CJB+
        elif cb_util_list[m][1]=='m':  #CJB+
            step=np.array([counter, 'm'])  #CJB+
        elif cb_util_list[m][1]=='y':  #CJB+
            step=np.array([counter, 'y'])  #CJB+
        elif cb_util_list[m][1]=='g':  #CJB+
            step=np.array([counter, 'g'])  #CJB+
        elif cb_util_list[m][1]=='b':  #CJB+
            step=np.array([counter, 'b'])  #CJB+
        else:  #CJB+
            step=np.array([counter, 'k'])  #CJB+
        cb_condensed=np.vstack((cb_condensed,step))  #CJB+
    cb_condensed=np.delete(cb_condensed,0,0)  #CJB+
    cb_condensed=cb_condensed[0:-1:4]  #CJB+
    #print cb_condensed  #CJB+

    jacket_check=np.array([[1,1]])  #CJB+
    for n in range(len(t_condensed)):  #CJB+
        counter=n+1  #CJB+
        if t_condensed[n][1]=='r' or cb_condensed[n][1]=='r':  #CJB+
            step=np.array([counter, 'r'])  #CJB+
        elif t_condensed[n][1]=='m' or cb_condensed[n][1]=='m':  #CJB+
            step=np.array([counter, 'm'])  #CJB+
        elif t_condensed[n][1]=='y' or cb_condensed[n][1]=='y':  #CJB+
            step=np.array([counter, 'y'])  #CJB+
        elif t_condensed[n][1]=='g' or cb_condensed[n][1]=='g':  #CJB+
            step=np.array([counter, 'g'])  #CJB+
        elif t_condensed[n][1]=='b' or cb_condensed[n][1]=='b':  #CJB+
            step=np.array([counter, 'b'])  #CJB+
        else:  #CJB+
            step=np.array([counter, 'k'])  #CJB+
        jacket_check=np.vstack((jacket_check,step))  #CJB+
    jacket_check=np.delete(jacket_check,0,0)  #CJB+
    #print jacket_check  #CJB+

    tower_check=np.array([[1,1]])  #CJB+
    for p in range(len(tower_Stressutil_list)):  #CJB+
        counter=p+len(jacket_check)+1  #CJB+
        if tower_Stressutil_list[p][1]=='r' or tower_GLutil_list[p][1]=='r' or tower_EUshutil_list[p][1]=='r':  #CJB+
            step=np.array([counter, 'r'])  #CJB+
        elif tower_Stressutil_list[p][1]=='m' or tower_GLutil_list[p][1]=='m' or tower_EUshutil_list[p][1]=='m':  #CJB+
            step=np.array([counter, 'm'])  #CJB+
        elif tower_Stressutil_list[p][1]=='y' or tower_GLutil_list[p][1]=='y' or tower_EUshutil_list[p][1]=='y':  #CJB+
            step=np.array([counter, 'y'])  #CJB+
        elif tower_Stressutil_list[p][1]=='g' or tower_GLutil_list[p][1]=='g' or tower_EUshutil_list[p][1]=='g':  #CJB+
            step=np.array([counter, 'g'])  #CJB
        elif tower_Stressutil_list[p][1]=='b' or tower_GLutil_list[p][1]=='b' or tower_EUshutil_list[p][1]=='b':  #CJB+
            step=np.array([counter, 'b'])  #CJB+
        else:  #CJB+
            step=np.array([counter, 'k'])  #CJB+
        tower_check=np.vstack((tower_check,step))  #CJB+
    tower_check=np.delete(tower_check,0,0)  #CJB+
    #print tower_check  #CJB+

    member_check=np.vstack((jacket_check,tower_check))  #CJB+
    #print member_check  #CJB+

    Kjnts_check=np.array([[1,1,1]])  #CJB+
    for i in myjckt.Build.KjntIDs:  #CJB+
        Kjnts_check=np.vstack((Kjnts_check,myjckt.JcktGeoOut.nodes[i-1]))  #CJB+
    Kjnts_check=np.delete(Kjnts_check,0,0)  #CJB+
    #print Kjnts_check  #CJB+
    #Kjnts_check=np.c_[Kjnts_check,myjckt.LoadFrameOuts.jacket_utilization.KjntUtil]  #CJB+
    #print Kjnts_check  #CJB+
    K_count=1  #CJB+
    K_joints_color=np.array([[1,1]])  #CJB+
    for i in myjckt.LoadFrameOuts.jacket_utilization.KjntUtil:  #CJB+
        if i>=1:  #CJB+
            step=np.array([K_count,'r^'])  #CJB+
        elif .8<=i<1:  #CJB+
            step=np.array([K_count,'mo'])  #CJB+
        elif .6<=i<.8:  #CJB+
            step=np.array([K_count,'yo'])  #CJB+
        elif .4<=i<.6:  #CJB+
            step=np.array([K_count,'go'])  #CJB+
        elif .2<=i<.4:  #CJB+
            step=np.array([K_count,'bo'])  #CJB+
        else:  #CJB+
            step=np.array([K_count,'ko'])  #CJB+
        K_count+=1  #CJB+
        K_joints_color=np.vstack((K_joints_color,step))  #CJB+
    K_joints_color=np.delete(K_joints_color,0,0)  #CJB+
    #print K_joints_color  #CJB+

    Xjnts_check=np.array([[1,1,1]])  #CJB+
    for i in myjckt.Build.XjntIDs:  #CJB+
        Xjnts_check=np.vstack((Xjnts_check,myjckt.JcktGeoOut.nodes[i-1]))  #CJB+
    Xjnts_check=np.delete(Xjnts_check,0,0)  #CJB+
    #print Xjnts_check  #CJB+

    X_count=1  #CJB+
    X_joints_color=np.array([[1,1]])  #CJB+
    for i in myjckt.LoadFrameOuts.jacket_utilization.XjntUtil:  #CJB+
        if i>=1:  #CJB+
            step=np.array([X_count,'r^'])  #CJB+
        elif .8<=i<1:  #CJB+
            step=np.array([X_count,'mo'])  #CJB+
        elif .6<=i<.8:  #CJB+
            step=np.array([X_count,'yo'])  #CJB+
        elif .4<=i<.6:  #CJB+
            step=np.array([X_count,'go'])  #CJB+
        elif .2<=i<.4:  #CJB+
            step=np.array([X_count,'bo'])  #CJB+
        else:  #CJB+
            step=np.array([X_count,'ko'])  #CJB+
        X_count+=1  #CJB+
        X_joints_color=np.vstack((X_joints_color,step))  #CJB+
    X_joints_color=np.delete(X_joints_color,0,0)  #CJB+
    #print X_joints_color  #CJB+

    KXcoords=np.vstack((Kjnts_check,Xjnts_check))  #CJB+
    KXcolors=np.vstack((K_joints_color,X_joints_color))  #CJB+
    #print KXcoords  #CJB+
    #print KXcolors  #CJB+

    #toscreen=False allows peregrine to work
    fig = plt.figure(1)
    ax = Axes3D(fig)
    nodes=myjckt.JcktGeoOut.nodes  #coordinates
    mems=myjckt.JcktGeoOut.mems
    XYZ1=nodes[mems[:,0]-1,:]
    XYZ2=nodes[mems[:,1]-1,:]
    #ax.scatter(nodes[:,0],nodes[:,1],nodes[:,2])
    x,y,z=zip(*nodes)
    #ax.scatter(x,y,z)
    Xs=np.vstack((XYZ1[:,0],XYZ2[:,0])).T
    Ys=np.vstack((XYZ1[:,1],XYZ2[:,1])).T
    Zs=np.vstack((XYZ1[:,2],XYZ2[:,2])).T
    #ax.plot([XYZ1[1:5,0],XYZ2[1:5,0]],[XYZ1[1:5,1],XYZ2[1:5,1]],[XYZ1[1:5,2],XYZ2[1:5,2]])
    for i in range(0,mems.shape[0]): #mems.shape[0])
        ax.plot([XYZ1[i,0],XYZ2[i,0]],[XYZ1[i,1],XYZ2[i,1]],[XYZ1[i,2],XYZ2[i,2]],member_check[i][1]) #CJBe Member check gives memebrs utilization colors
        #CJB TODO If RigidTop=False, then the code does not make the top member. However, the utilization plot (Figure 2) will still show the utiliazation of the top member. (There is a different number of tower members being plotted)
    axisEqual3D(ax)
#    ax.set_aspect('equal')
#    ax.auto_scale_xyz([min(XYZ1[:,0]),max(XYZ1[:,0])],[min(XYZ1[:,1]),max(XYZ1[:,1])],[min(XYZ1[:,2]),max(XYZ1[:,2])])

    if savefileroot:
        plt.savefig(savefileroot+'_config.png',format='png')
    elif toscreen:
        plt.show()

    #Plot utilization of Tower if requested
    if util:
        RigidTop=(myjckt.RNAinputs.CMoff[2] != 0.) and myjckt.Tower.RigidTop
        fig2=plt.figure(2);
        ax1 = fig2.add_subplot(111)
        twr_zs=myjckt.Tower.Twrouts.nodes[2,0:myjckt.Tower.Twrouts.nNodes-RigidTop]-myjckt.Tower.Twrouts.nodes[2,0]
        #Add one diameter at the very top since the tube object does not have the final D
        twr_D=np.hstack((myjckt.Tower.Twrouts.TwrObj.D,myjckt.Tower.Twrins.Dt))

        yrange=(np.min(twr_zs),np.max(twr_zs));
        #hh=plt.Axes(ox','off',\
        ##    'Ylim',yrange,'Nextplot','Add','Visible','On');
        ax1.set_xlabel('VonMises, GL, and EU Utilization Ratios');
        ax1.set_ylabel('z from base of tower (incl. AF) [m]');
        #ax1.set_ylabel('z from base of structure (incl. AF) [m]');
        ax1.set_title('Utilization Ratio');
        ax1.set_xlim([0,2]);
        ax1.set_ylim(yrange);
        #set(plt.gca(),'ylim',yrange)
        #ax1.plot([0, 2], [water_dict['wlevel'],water_dict['wlevel']],'.-r')
        #ax1.plot([0, 2], np.array([water_dict['wlevel']-water_dict['wdpth']]).repeat(2),':k')

        ax1.plot([],[],'k',label='Tower Profile') #CJB+
        ax1.plot(myjckt.LoadFrameOuts.tower_utilization.StressUtil,twr_zs , label='VonMises Util1')
        ax1.plot(myjckt.LoadFrameOuts.tower_utilization.GLUtil,twr_zs, label='GL Util1')
        ax1.plot(myjckt.LoadFrameOuts.tower_utilization.EUshUtil, twr_zs, label='EUsh Util1')
        if myjckt.LoadFrameOuts2.tower_utilization.StressUtil[0] != -9999.:
            ax1.plot([],[],'k',label='Tower Profile') #CJB+
            ax1.plot(myjckt.LoadFrameOuts2.tower_utilization.StressUtil,twr_zs , label='VonMises Util2')
            ax1.plot(myjckt.LoadFrameOuts2.tower_utilization.GLUtil,twr_zs, label='GL Util2')
            ax1.plot(myjckt.LoadFrameOuts2.tower_utilization.EUshUtil, twr_zs, label='EUsh Util2')

        ax1.grid()
        #ax1.legend(['0 m MSL','SeaBed','GL Global Buckling', 'EU Shell Buckling'])
        #ax1.legend(['GL Global Buckling', 'EU Shell Buckling'])
        ax1.legend(bbox_to_anchor=(0.6, 1.0), loc=2)

        ax2=plt.twiny(ax1)# .axes(ax1.get_position(),frameon=False)
        #hh2=plt.axes('Position', pos,'NextPlot','Add','XtickLabel','','Xtick',[],frameon=False);
        ax2.plot(twr_D/2,twr_zs,'k') #CJBe Add color
        ax2.plot(-twr_D/2,twr_zs, 'k') #CJBe Add color
        ax2.set_aspect('equal')
        ax2.set_frame_on(False)
        ax2.set_xticklabels('')
        ax2.set_xticks([])
        ax1.set_xlim([0,2]);
        #hh2.set_aspect('equal')
        ##ax2.axis('equal')

        if savefileroot:
            plt.savefig(savefileroot+'_util.png',format='png')
        elif toscreen:
            plt.show()


    fig3= plt.figure(3) #CJB+
    ax = Axes3D(fig3) #CJB+

    for i in range(myjckt.JcktGeoOut.nmems-len(myjckt.LoadFrameOuts.TPmems)-len(myjckt.LoadFrameOuts.Twrmems)): #CJB+
        #if count<=myjckt.JcktGeoOut.nmems:
        plt.plot([XYZ1[i,0],XYZ2[i,0]],[XYZ1[i,1],XYZ2[i,1]],[XYZ1[i,2],XYZ2[i,2]],'.75') #CJBe Member check gives memebrs utilization colors
    for i in range(0,KXcoords.shape[0]): #CJB+
        plt.plot([KXcoords[i,0]],[KXcoords[i,1]],[KXcoords[i,2]], KXcolors[i][1]) #CJB+
    axisEqual3D(ax) #CJB+
    plt.show() #CJB+
Exemple #48
0
import sys
from matplotlib.ticker import FuncFormatter
import matplotlib.pyplot as plt
import numpy as np

import matplotlib.cbook as cbook

filename = sys.argv[1]

data = cbook.get_sample_data(filename, asfileobj=False)
plt.plotfile(data, ('time', 'rss', 'storage_used', 'je_allocated', 'je_resident', 'reclaim_pending', 'queue_size'), subplots=False, delimiter=',')

plt.xlabel(r'seconds')
plt.ylabel(r'memory_used')
yaxis = plt.twiny()
yaxis.yaxis.set_major_formatter(FuncFormatter(lambda y,_: '%1.f' % (y/(1024*1024))))

plt.plotfile(data, ('time', 'mainrecord', 'docrecords'), subplots=False, delimiter=',')
plt.show()


Exemple #49
0
def am_plot(targets, observer, fig=None, ylim=[2.5, 1], **kwargs):
    """Generate a letter-sized, pretty airmass plot for a night.

    Parameters
    ----------
    targets : array of Target
      A list of targets to plot.
    observer : Observer
      The observer.
    fig : matplotlib Figure or None
      Figure: The matplotlib figure (number) to use.
      None: Use current figure.
    ylim : array
      Y-axis limits (airmass).
    **kwargs
      Keyword arguments for `Observer.plot_am`.

    Returns
    -------
    None

    Notes
    -----
    To change the x-axis limits, use:
      `plt.setp(fig.axes, xlim=[min, max])`

    """

    import itertools
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FuncFormatter
    from .. import graphics
    from ..util import dh2hms
    from .. import ephem

    linestyles = itertools.product(['-', ':', '--', '-.'], 'bgrcmyk')

    if fig is None:
        fig = plt.gcf()
        fig.clear()
        fig.set_size_inches(11, 8.5, forward=True)
        fig.subplots_adjust(left=0.06, right=0.94, bottom=0.1, top=0.9)

    ax = fig.gca()
    plt.minorticks_on()

    astro_twilight = ephem.getspiceobj('Sun', kernel='planets.bsp',
                                       name='Astro twilight')
    civil_twilight = ephem.getspiceobj('Sun', kernel='planets.bsp',
                                       name='Civil twilight')

    for target in targets:
        ls, color = linestyles.next()
        observer.plot_am(target, color=color, ls=ls, **kwargs)
        observer.rts(target, limit=25)

    print()
    for target, ls in zip((ephem.Sun, ephem.Moon), ('y--', 'k:')):
        observer.plot_am(target, color=ls[0], ls=ls[1:], **kwargs)
        observer.rts(target, limit=0)

    at_rts = observer.rts(astro_twilight, limit=-18)
    ct_rts = observer.rts(civil_twilight, limit=-6)

    y = [ylim[0], ylim[0], ylim[1], ylim[1]]
    c = (0.29, 0.64, 1.0, 0.1)
    for twilight in (at_rts, ct_rts):
        x = [-12, twilight[2].value - 24, twilight[2].value - 24, -12]
        ax.fill(x, y, color=c)

        x = [12, twilight[0].value, twilight[0].value, 12]
        ax.fill(x, y, color=c)

    plt.setp(ax, ylim=ylim, ylabel='Airmass',
             xlabel='Time (Civil Time)')

    # civil time labels
    def ctformatter(x, pos):
        return dh2hms(x % 24.0, '{:02d}:{:02d}')
    ax.xaxis.set_major_formatter(FuncFormatter(ctformatter))

    # LST labels
    def lstformatter(x, pos, lst0=observer.lst0.hour):
        return dh2hms(((x + lst0) % 24.0), '{:02d}:{:02d}')

    tax = plt.twiny()
    tax.xaxis.set_major_formatter(FuncFormatter(lstformatter))
    plt.minorticks_on()
    plt.setp(tax, xlabel='LST ' + str(observer))

    plt.sca(ax)
    graphics.niceplot(lw=1.6, tightlayout=False)

    fontprop = dict(family='monospace')
    graphics.nicelegend(frameon=False, loc='upper left', prop=fontprop)

    plt.draw()
Exemple #50
0
def auc(y_true,
        y_score,
        pos_label=1,
        plot=False,
        loc='lower right',
        max_fpr=1.0,
        figsize=[6, 4],
        plot_threshold=False):
    fpr, tpr, threshold = metrics.roc_curve(y_true,
                                            y_score,
                                            pos_label=pos_label)
    #%matplotlib inline
    import matplotlib.pyplot as plt
    # To avoid type 3 fonts. ACM Digital library complain about this
    # based on the recomendations here http://phyletica.org/matplotlib-fonts/
    plt.rcParams['pdf.fonttype'] = 42
    plt.rcParams['ps.fonttype'] = 42
    #    area = metrics.roc_auc_score(y_true, y_score, average="weighted")
    area = metrics.auc(fpr[fpr <= max_fpr], tpr[fpr <= max_fpr])

    if plot:
        plt.figure(figsize=figsize)
        plt.plot(fpr,
                 tpr,
                 label='(auc: {0:.{precision}})'.format(area, precision=2))
        plt.grid(True)
        plt.xlabel('FPR')
        plt.ylabel('TPR')
        plt.xlim([0., max_fpr])
        plt.legend(loc=loc)

        if plot_threshold:
            ax2 = plt.twiny()

            # Move twinned axis ticks and label from top to bottom
            ax2.xaxis.set_ticks_position("bottom")
            ax2.xaxis.set_label_position("bottom")

            # Offset the twin axis below the host
            ax2.spines["bottom"].set_position(("axes", -0.15))

            # Turn on the frame for the twin axis, but then hide all
            # but the bottom spine
            ax2.set_frame_on(True)
            ax2.patch.set_visible(False)
            for sp in ax2.spines.itervalues():
                sp.set_visible(False)
            ax2.spines["bottom"].set_visible(True)

            partitions = 11

            from bisect import bisect_left

            def find_lt(a, x):
                'Find rightmost value less than x'
                i = bisect_left(a, x)
                if i:
                    return i

                return 0

            t = []
            for f in np.linspace(0, max_fpr, partitions):
                idx = min(len(fpr) - 1, find_lt(fpr[fpr <= max_fpr], f))
                t.append('{0:5.3}'.format(float(threshold[idx])))

            ax2.set_xticks(np.arange(partitions))
            #             ax2.set_xticklabels(['{0:5.3}'.format(float(t)) for i, t in enumerate(threshold) \
            #                                  if i % (len(threshold) / partitions) == 0])
            ax2.set_xticklabels(t)
            ax2.set_xlabel("Threshold")

        plt.show()
    return area
Exemple #51
0
    def intensityRatio(self, wvlRange=None, wvlRanges=None, top=10):
        """
        Plot the intensity 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.

        Parameters
        -----------
        wvlRange : array-like
            Wavelength range, i.e. min and max
        wvlRanges: a tuple, list or array that contains at least 2
            2 element tuples, lists or arrays so that multiple
            wavelength ranges can be specified
        top : `int`
            specifies to plot only the top strongest lines, default = 10
        """

        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
        fontsize=14
        eDensity = self.EDensity
        temperature = self.Temperature
        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"]
        # 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)
        igvl=np.take(igvl,wvl[igvl].argsort())
        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]]
        igvlsort=np.take(igvl,np.argsort(maxIntens))
        topLines=igvlsort[-top:]
        maxWvl='%5.3f' % wvl[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

        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 = self.EDensity
            desc_str=' Density = %10.2e (cm)$^{-3}$' % self.EDensity[0]
        elif ntemp == 1:
            xvalues=self.EDensity
            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
        plt.ion()
        #  maxAll is an array
        ymax = np.max(intensity[:, topLines[0]]/maxAll)
        ymin = ymax
        plt.figure()
        ax = plt.subplot(111)
        nxvalues=len(xvalues)
        # reversing is necessary - otherwise, get a ymin=ymax and a matplotlib error
        for iline in range(top-1, -1, -1):
            tline=topLines[iline]
            plt.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])
                plt.text(xvalues[ixvalue], intensity[ixvalue, tline]/maxAll[ixvalue], text)
        plt.xlim(xvalues.min(),xvalues.max())
        plt.xlabel(xlabel,fontsize=fontsize)
        plt.ylabel(ylabel,fontsize=fontsize)
        if ndens == ntemp and ntemp > 1:
            plt.text(0.07, 0.5,title, horizontalalignment='left', verticalalignment='center', fontsize=fontsize,  transform = ax.transAxes)
            ax2 = plt.twiny()
            xlabelDen=r'Electron Density (cm$^{-3}$)'
            plt.xlabel(xlabelDen, fontsize=fontsize)
            plt.loglog(eDensity,intensity[:, topLines[top-1]]/maxAll, visible=False)
            ax2.xaxis.tick_top()
            plt.ylim(ymin/1.2, 1.2*ymax)
        else:
            plt.ylim(ymin/1.2, 1.2*ymax)
            plt.title(title+desc_str,fontsize=fontsize)
        plt.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(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
        plt.figure()
        ax = plt.subplot(111)
        plt.loglog(xvalues,numIntens/denIntens)
        plt.xlim(xvalues.min(),xvalues.max())
        plt.xlabel(xlabel,fontsize=fontsize)
        plt.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:
            plt.text(0.07, 0.5,desc, horizontalalignment='left', verticalalignment='center', fontsize=fontsize,  transform = ax.transAxes)
            #
            ax2 = plt.twiny()
            xlabelDen=r'Electron Density (cm$^{-3}$)'
            plt.xlabel(xlabelDen, fontsize=fontsize)
            plt.loglog(eDensity,numIntens/denIntens, visible=False)
            ax2.xaxis.tick_top()
        else:
            plt.title(desc,fontsize=fontsize)

        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}
Exemple #52
0
def daily(start_date,
          PosCorErrRec=None,
          width=10,
          show=False,
          save_to=None,
          phase_lin=None,
          aimstars=None,
          title="",
          y_label="Count per Minute",
          cor_label="Correct freq",
          err_label="Error freq"):

    # Definition of a, b and c of the exponential function y = ab^(x/c).
    a = 0.001  # y-intercept.
    b = 2  # y-increase factor.
    c = 7  # x-increase per y-increase factor.
    angle = 34  # desired visual slope of the function graph, in degrees.
    xmin = 0  # x-axis minimum value.
    xmax = 140  # x-axis maximum value.
    ymin = 0.00069  # y-axis minimum value.
    ymax = 1000  # y-axis maximum value.
    x = np.arange(xmin, xmax)
    y = a * pow(b, x / c)  # Calculate y-values for visual angle testing.
    font = "Arial"

    # Calculate and set height of the figure based on referenced width.
    height = width * np.tan(angle / 180 * np.pi) * np.log10(
        ymax / ymin) / (xmax - xmin) * c / np.log10(b)
    fig, ax = plt.subplots(figsize=(width, height))

    plt.subplots_adjust(left=0.15, right=0.85, bottom=0.15,
                        top=0.85)  # Surround plot with more white space

    # Define axis ticks and labels
    left_y_ticks = [
        10**e for e in [
            np.log10(i) for i in
            [0.001, 0.005, 0.01, 0.05, 0.1, 1, 5, 10, 50, 100, 500, 1000]
        ]
    ]
    left_y_labels = [
        "0.001", "0.005", "0.01", "0.05", "0.1", "1", "5", "10", "50", "100",
        "500", "1000"
    ]
    right_y_ticks = [
        1 / m for m in [
            10 / 60, 15 / 60, 20 / 60, 30 / 60, 1, 2, 5, 10, 20, 60, 60 *
            2, 60 * 4, 60 * 8, 60 * 16
        ]
    ]
    right_y_labels = [
        '10" sec', '15"', '20"', '30"', "1' min", "2'", "5'", "10'", "20'",
        "1 - h", "2 - h", "4 - h", "8 - h", "16 - h"
    ]
    if width < 8:
        bottom_x_inc = 14
        top_x_inc = 28
    else:
        bottom_x_inc = 7
        top_x_inc = 7
    bottom_x_ticks = np.arange(0, 141, bottom_x_inc)
    top_x_ticks = np.arange(0, 141, top_x_inc)

    start_date = pd.to_datetime(
        start_date)  # Convert to pandas datetime format.
    first_sunday = start_date - pd.Timedelta(start_date.dayofweek + 1,
                                             unit="D")  # Find last Sunday.
    dates = pd.date_range(first_sunday, periods=21, freq="W").strftime(
        "%d-%m-%y")  # Get date labels for top x-axis.

    # Set up up top x-axis.
    ax2 = plt.twiny()
    ax2.set_xticks(top_x_ticks)
    ax2.set_xticklabels(dates, rotation=45, fontsize=9, fontname=font)
    ax2.tick_params(axis='both', which='both', length=0)
    plt.setp(ax2.xaxis.get_majorticklabels(),
             ha="left",
             rotation_mode="anchor")

    # Set up right y-axis.
    ax3 = plt.twinx()
    ax3.set_ylim(ymin, ymax)
    ax3.set_yscale("log")
    ax3.set_yticks(right_y_ticks)
    ax3.set_yticklabels(right_y_labels, fontsize=8, fontname=font)
    ax3.tick_params(axis='both', which='minor', length=0)

    # Move bottom x-axis down slightly for ax and remove bottom spine for ax2 and ax3.
    ax.spines["bottom"].set_position(("axes", -0.03))  # Move down.
    ax2.spines["bottom"].set_visible(False)  # Delete ax2 spine.
    ax3.spines["bottom"].set_visible(False)  # Delete ax3 spine.

    # Set up main axes: left y and bottom x.
    ax.set_yscale("log")
    ax.set_ylim(0.00069, 1000)
    ax.tick_params(axis='both', which='minor', length=0)
    ax.set_xlim(0, 140)
    ax.set_xticks(bottom_x_ticks)
    ax.set_xticklabels([str(tick) for tick in bottom_x_ticks],
                       fontsize=9,
                       fontname=font)
    ax.set_yticks(left_y_ticks)
    ax.set_yticklabels(left_y_labels, fontsize=9, fontname=font)

    # Draw grid lines.
    custom_grid_color = "turquoise"
    ax.grid(which="both", color=custom_grid_color, linewidth=0.3)
    for sun in [i for i in range(7, 141, 7)]:
        ax.axvline(sun, color=custom_grid_color, linewidth=1)
    for power in [0.001, 0.01, 0.1, 1, 10, 100, 1000]:
        ax.axhline(power, color=custom_grid_color, linewidth=1)

    # Color spines (the frame around the plot). The axes all have their own spines, so we have to color each.
    color = "teal"
    for position in ax.spines.keys():
        ax.spines[position].set_color(color)
        ax2.spines[position].set_color(color)
        ax3.spines[position].set_color(color)

    # Set axis labels and title
    ax.set_ylabel(y_label, fontname=font, fontsize=13)
    ax.set_xlabel("Successive Calendar Days", fontname=font, fontsize=13)
    plt.title(title)
    ax.text(0.05,
            0.05,
            'By SJV',
            transform=plt.gcf().transFigure,
            fontname=font,
            fontsize=7)

    # Calculate frequency based on count and record floor.
    if PosCorErrRec:
        position, correct_freq, error_freq, record_floor_freq = freq_calc(
            PosCorErrRec)

        ax.plot(position, correct_freq, "ko", markersize=3, label=cor_label)
        ax.plot(position, error_freq, "kx", markersize=5, label=err_label)
        ax.plot(position,
                record_floor_freq,
                marker="_",
                markersize=5,
                color="k",
                linestyle="",
                label="Record floor",
                markeredgewidth=3)
        # ax.plot(x, y, 'r', label="34 degree angle")  # Uncomment to test for a 34 degree visual angle.)

        if aimstars:
            for aim in aimstars:
                if type(aim) is not tuple:
                    raise Warning("Aimstar must be a list of tuples.")
                x_aim, y_aim = aim
                ax.plot(x_aim,
                        y_aim,
                        label="Aim",
                        marker="*",
                        markersize=9,
                        color="firebrick",
                        linestyle="")

        if phase_lin:
            for phase in phase_lin:
                if type(phase) is not tuple:
                    raise Warning("Phase_lin must be a list of tuples.")
                x_cor, y_cor, text = phase
                ax.axvline(x_cor, color="k", linestyle="--")
                ax.text(x_cor + 2,
                        y_cor,
                        text,
                        fontname=font,
                        bbox=dict(facecolor='white', edgecolor='black'))

        ax.legend(loc="upper right")

    if save_to:
        plt.savefig(save_to + "\\" + title)
    if show:
        plt.show()
    plt.close()
Exemple #53
0
def plot_psd(plotfilename):
    data= apread.rcsample()
    if _ADDLLOGGCUT:
        data= data[data['ADDL_LOGG_CUT'] == 1]
    #Cut
    indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.)
    print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx)
    data= data[indx]
    #Get residuals
    dx= _RCDX
    binsize= .8#.765
    pix= pixelize_sample.pixelXY(data,
                                 xmin=_RCXMIN,xmax=_RCXMAX,
                                 ymin=_RCYMIN,ymax=_RCYMAX,
                                 dx=dx,dy=dx)
    resv= pix.plot(lambda x: dvlosgal(x,vtsun=220.+22.5),
                   returnz=True,justcalc=True)
    resvunc= pix.plot('VHELIO_AVG',
                      func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)),
                      returnz=True,justcalc=True)
    psd1d= bovy_psd.psd1d(resv,dx,binsize=binsize)
    print psd1d
    #Simulations for constant 3.25 km/s
    nnoise= _NNOISE
    noisepsd= numpy.empty((nnoise,len(psd1d[0])-4))
    for ii in range(nnoise):
        newresv= numpy.random.normal(size=resv.shape)*3.25
        noisepsd[ii,:]= bovy_psd.psd1d(newresv,dx,binsize=binsize)[1][1:-3]
    scale= 4.*numpy.pi#3.25/numpy.median(numpy.sqrt(noisepsd))
    print scale
    #Simulations for the actual noise
    nnoise= _NNOISE
    noisepsd= numpy.empty((nnoise,len(psd1d[0])-4))
    for ii in range(nnoise):
        newresv= numpy.random.normal(size=resv.shape)*resvunc
        noisepsd[ii,:]= bovy_psd.psd1d(newresv,dx,binsize=binsize)[1][1:-3]
    ks= psd1d[0][1:-3]
    if _ADDGCS:
        xrange=[.03,110.]
    else:
        xrange= [0.,1.]
    yrange= [0.,11.9]
    if _PROPOSAL:
        bovy_plot.bovy_print(fig_width=7.5,fig_height=3.)
    else:
        bovy_plot.bovy_print(fig_width=7.5,fig_height=4.5)
    apop= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psd1d[1][1:-3]
                                            -_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)),
                        'ko',lw=2.,
                        zorder=12,
                        xlabel=r'$k\,(\mathrm{kpc}^{-1})$',
                        ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$',
                        semilogx=_ADDGCS,
                        xrange=xrange,yrange=yrange)
    if _DUMP2FILE:
        with open('bovy-apogee-psd.dat','w') as csvfile:
            writer= csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
            csvfile.write('#APOGEE\n')
            for ii in range(len(ks)):
                writer.writerow([ks[ii],
                                 (scale*numpy.sqrt(psd1d[1][1:-3]-_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)))[ii],
                                 (scale*0.5*(psd1d[2][1:-3]**2.+_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)**2.)**0.5/numpy.sqrt(psd1d[1][1:-3]))[ii]])
    if _PROPOSAL:
        pyplot.gcf().subplots_adjust(bottom=0.15)
    pyplot.errorbar(ks,scale*numpy.sqrt(psd1d[1][1:-3]-_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)),
                    yerr=scale*0.5*(psd1d[2][1:-3]**2.
                                    +_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)**2.)**0.5/numpy.sqrt(psd1d[1][1:-3]),
                    marker='None',ls='none',color='k')
    if _PLOTBAND:
#        bovy_plot.bovy_plot(ks,
#                            scale*numpy.median(numpy.sqrt(noisepsd),axis=0),
#                            '--',lw=2.,zorder=10,
#                            color='0.85',overplot=True)
#        bovy_plot.bovy_plot(ks,
#                            scale*numpy.sqrt(numpy.sort(noisepsd
#                                                        -_SUBTRACTERRORS*numpy.median(noisepsd,axis=0),axis=0)[int(numpy.floor(0.99*_NNOISE)),:]),
#                            zorder=1,ls='--',overplot=True,
#                            color='0.65')
        pyplot.fill_between(ks,
                            scale*numpy.sqrt(numpy.sort(noisepsd
                                                        -_SUBTRACTERRORS*numpy.median(noisepsd,axis=0),axis=0)[int(numpy.floor(_SIGNIF*_NNOISE)),:]),
                            zorder=0,
                            color='0.65')
    #Add a simple model of a spiral potential
    if _ADDSIMPLESPIRAL:
        if False:
            alpha= -12.5
            spvlos= simulate_vlos_spiral(alpha=alpha,
                                         gamma=1.2,
                                         xmin=_RCXMIN,xmax=_RCXMAX,
                                         ymin=_RCYMIN,ymax=_RCYMAX,
                                         dx=0.01)
            potscale= 1.35*1.2
            print numpy.arctan(2./alpha)/numpy.pi*180., numpy.sqrt(0.035/numpy.fabs(alpha)/2.)*potscale*220., numpy.sqrt(0.035/numpy.fabs(alpha))*potscale*220.
            simpsd1d= bovy_psd.psd1d(spvlos*220.*potscale,0.01,binsize=binsize)
            tks= simpsd1d[0][1:-3]
            bovy_plot.bovy_plot(tks,
                                scale*numpy.sqrt(simpsd1d[1][1:-3]),
                                'k--',lw=2.,overplot=True)
        #A better simulation
#        spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14.sav')
        spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_hivres.sav')
        potscale= 1.
        simpsd1d= bovy_psd.psd1d(spvlos*220.*potscale,0.33333333,binsize=binsize)
        tks= simpsd1d[0][1:-3]
#        alpha=-14.
#        print numpy.arctan(2./-14.)/numpy.pi*180., numpy.sqrt(0.075/numpy.fabs(alpha)/2.)*potscale*220., numpy.sqrt(0.075/numpy.fabs(alpha))*potscale*220.
        line1= bovy_plot.bovy_plot(tks,
                                   scale*numpy.sqrt(simpsd1d[1][1:-3]),
                                   'k--',lw=2.,overplot=True)
        if _DUMP2FILE:
            with open('bovy-bar-psd.dat','w') as csvfile:
                writer= csv.writer(csvfile, delimiter=',',
                                   quotechar='|', quoting=csv.QUOTE_MINIMAL)
                for ii in range(len(ks)):
                    writer.writerow([tks[ii],(scale*numpy.sqrt(simpsd1d[1][1:-3]))[ii]])
        #bovy_plot.bovy_plot(tks[tks > 0.7],
        #                    scale*numpy.sqrt(simpsd1d[1][1:-3][tks > 0.7]+4./scale**2.*(1.-numpy.tanh(-(tks[tks > 0.7]-0.9)/0.1))/2.),
        #                    'k-.',lw=2.,overplot=True)
        #line2= bovy_plot.bovy_plot(tks,
        #                           scale*numpy.sqrt(simpsd1d[1][1:-3]+4./scale**2.),
        #                           'k-.',lw=2.,overplot=True,dashes=(10,5,3,5))
        l1= pyplot.legend((line1[0],),
#                      (r'$\mathrm{Spiral}:\ \delta \phi_{\mathrm{rms}} = (10\,\mathrm{km\,s}^{-1})^2,$'+'\n'+r'$\mathrm{pitch\ angle} = 8^\circ$'+'\n'+r'$\mathrm{Sun\ near\ 2\!:\!1\ Lindblad\ resonance}$',),
                      (r'$\mathrm{Bar}:\ F_{R,\mathrm{bar}} / F_{R,\mathrm{axi}} = 1.5\%,$'+'\n'+r'$\mathrm{angle} = 25^\circ,$'+'\n'+r'$\mathrm{Sun\ near\ 2\!:\!1\ Lindblad\ resonance}$',),
                      loc='upper right',#bbox_to_anchor=(.91,.375),
                      numpoints=8,
                      prop={'size':14},
                      frameon=False)
    #Add the lopsided and ellipticity constraints from Rix/Zaritsky
    if _ADDRIX:
        pyplot.errorbar([1./16.],[5.6],
                        yerr=[5.6/2.],
                        marker='d',color='0.6',
                        mew=1.5,mfc='none',mec='0.6')
        pyplot.errorbar([1./8./numpy.sqrt(2.)],[6.4],
                        yerr=numpy.reshape(numpy.array([6.4/0.045*0.02,6.4/0.045*0.03]),(2,1)),
                        marker='d',color='0.6',mec='0.6',
                        mew=1.5,mfc='none')
    if _ADDGCS:
        ks_gcs, psd_gcs, e_psd_gcs, gcsp= plot_psd_gcs()
    if _ADDRAVE:
        ks_rave, psd_rave, e_psd_rave, ravep= plot_psd_rave()
    if _ADDRED:
        plot_psd_red()
    l2= pyplot.legend((apop[0],ravep[0],gcsp[0]),
                      (r'$\mathrm{APOGEE}$',
                       r'$\mathrm{RAVE}$',
                       r'$\mathrm{GCS}$'),
                      loc='upper right',bbox_to_anchor=(.95,.750),
                      numpoints=1,
                      prop={'size':14},
                      frameon=False)
    pyplot.gca().add_artist(l1)
    pyplot.gca().add_artist(l2)
    #Plot an estimate of the noise, based on looking at the bands
    nks= numpy.linspace(2.,120.,2)
    if not 'mba23' in socket.gethostname():
        pyplot.fill_between(nks,[2.,2.],hatch='/',color='k',facecolor=(0,0,0,0),
                            lw=0.)
    #                        edgecolor=(0,0,0,0))
    pyplot.plot(nks,[2.,2.],color='k',lw=1.5)
    nks= numpy.linspace(0.17,2.,2)
    def linsp(x):
        return .8/(numpy.log(0.17)-numpy.log(2.))*(numpy.log(x)-numpy.log(0.17))+2.8
    if not 'mba23' in socket.gethostname():
        pyplot.fill_between(nks,linsp(nks),hatch='/',color='k',facecolor=(0,0,0,0),
                            lw=0.)
    #                        edgecolor=(0,0,0,0))   
    #Plot lines
    pyplot.plot([0.17,0.17],[0.,2.8],color='k',lw=1.5)
    pyplot.plot(nks,linsp(nks)+0.01,color='k',lw=1.5)
    bovy_plot.bovy_text(0.19,.5,r'$95\,\%\,\mathrm{noise\ range}$',
                        bbox=dict(facecolor='w',edgecolor='w'),fontsize=14.)
    if _INTERP:
        interpks= list(ks[:-5])
        interppsd= list((scale*numpy.sqrt(psd1d[1][1:-3]-_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)))[:-5])
        interppsd_w= (scale*0.5*psd1d[2][1:-3]/numpy.sqrt(psd1d[1][1:-3]))[:-5]
        interppsd_w[:8]*= 0.025 #fiddling to get a decent fit
        interppsd_w[3:5]*= 0.001
        interppsd_w= list(interppsd_w)
        interpks.append(0.025)
        interppsd.append(10.**-5.)
        interppsd_w.append(0.00001)
        interpks.append(110.)
        interppsd.append(1.)
        interppsd_w.append(0.00001)
        if _ADDGCS:
            interpks.extend(ks_gcs)
            interppsd.extend(psd_gcs)
            interppsd_w.extend(e_psd_gcs)
        if _ADDRAVE:
            interpks.extend(ks_rave[5:])
            interppsd.extend(psd_rave[5:])
            interppsd_w.extend(e_psd_rave[5:])
        interpks= numpy.array(interpks)
        sortindx= numpy.argsort(interpks)
        interpks= interpks[sortindx]
        interppsd= numpy.array(interppsd)[sortindx]
        interppsd_w= interppsd/numpy.array(interppsd_w)[sortindx]
        interpindx= True-numpy.isnan(interppsd)
    #interpspec= interpolate.InterpolatedUnivariateSpline(interpks[interpindx],
        interpspec= interpolate.UnivariateSpline(numpy.log(interpks[interpindx]),
                                                 numpy.log(interppsd[interpindx]/3.),
                                                 w=interppsd_w,
                                                 k=3,s=len(interppsd_w)*0.8)
        pks= numpy.linspace(interpks[0],interpks[-1],201)
        #bovy_plot.bovy_plot(pks,
        #                    3.*numpy.exp(interpspec(numpy.log(pks))),
#                    'k-',overplot=True)
    def my_formatter(x, pos):
        return r'$%g$' % x
    def my_formatter2(x, pos):
        return r'$%g$' % (1./x)
    major_formatter = FuncFormatter(my_formatter)
    major_formatter2 = FuncFormatter(my_formatter2)
    ax= pyplot.gca()
    ax.xaxis.set_major_formatter(major_formatter)
    if not _PROPOSAL:
        ax2= pyplot.twiny()
        xmin, xmax= ax.xaxis.get_view_interval()
        ax2.set_xscale('log')
        ax2.xaxis.set_view_interval(1./xmin,1./xmax,ignore=True)
        ax2.set_xlabel('$\mathrm{Approximate\ scale}\,(\mathrm{kpc})$',
                       fontsize=12.,ha='center',x=0.5)
        ax2.xaxis.set_major_formatter(major_formatter)
    bovy_plot.bovy_end_print(plotfilename,dpi=300)
    return None
Exemple #54
0
         lw=3.5,
         ms=10,
         label="Simulations, $N_{fils}=1$")
plt.plot(I0,
         nf5,
         marker="o",
         color="#8067B7",
         linestyle=":",
         lw=3.5,
         ms=10,
         label="Simulations, $N_{fils}=5$")

plt.xscale("log")
plt.yscale("log")

plt.xlabel(r"$I_0$ [$W/cm^2$]")
plt.ylabel(r"$N_+/tir$")

plt.xlim(5e18, 5e21)
plt.ylim(1e-5, 10)

plt.legend(loc=4, ncol=1)

ay = plt.twiny()
ay.set_xscale("log")
ay.set_xlim((5e18 / 8.8e22) * 25 * 30 / 0.94, (5e21 / 8.8e22) * 25 * 30 / 0.94)
ay.set_xlabel(r"$E_L$ [$J$]")
plt.grid(False)

plt.savefig("resultats_paires.png")
Exemple #55
0
def plot(ocd,
         calib,
         file_name = "test.jpg",
         interpolation = False):
    fig = plt.figure(figsize=(12,6))
    ax1 = plt.subplot(111)
    plt.xlabel("{} - Calibrated date (BC)".format(ocd.name), fontsize=18)
    plt.ylabel("Radiocarbon determination (BP)", fontsize=18)


    plt.text(0., 0.99,"pyC14 v0.1; Xtof; Bellevue 2008-2012",
         horizontalalignment='left',
         verticalalignment='bottom',
         transform = ax1.transAxes,
         size=9,
         bbox=dict(facecolor='white', alpha=1, lw=0))


    # Calendar Age
    ax2 = plt.twinx()

    calib_0 = (ocd.likelihood.array)
    calib_1 = (ocd.posterior.array)
    if(interpolation):
        calib_0 = interpolate(calib_0)
        calib_1 = interpolate(calib_1)

    max_prob_ref = max(calib_0[:,1])
    min_prob_ref = min(calib_0[:,1])
    max_prob_calib = max(calib_1[:,1])
    min_prob_calib = min(calib_1[:,1])

    beta = ocd.adjust_comparaison()

    ax2.fill(
        calib_0[:,0],
        calib_0[:,1] + max(max_prob_ref, max_prob_calib)*0.3,
        'k',
        alpha=0.2,
        )
    ax2.plot(
        calib_0[:,0],
        calib_0[:,1] + max(max_prob_ref, max_prob_calib)*0.3,
        'k:',
        alpha=0.5
        )

    # Calendar Age bis
    ax2b = plt.twinx()


    ax2b.fill(
        calib_1[:,0],
        calib_1[:,1]/beta + max(max_prob_ref, max_prob_calib)*0.3,
        'k',
        alpha=0.5,
        )
    ax2b.plot(
        calib_1[:,0],
        calib_1[:,1]/beta + max(max_prob_ref, max_prob_calib)*0.3,
        'k',
        alpha=0.5
        )

    #print(min_prob_ref, min_prob_calib)
    #print(max_prob_ref, max_prob_calib)

    ax2.set_ybound(
        min(min_prob_ref, min_prob_calib), 
        max(max_prob_ref, max_prob_calib)*3)
    ax2b.set_ybound(
        min(min_prob_ref, min_prob_calib), 
        max(max_prob_ref, max_prob_calib)*3)
    ax2.set_axis_off()
    ax2b.set_axis_off()

    # Radiocarbon Age
    sample_interval = np.arange(ocd.date-4*ocd.error, ocd.date+4*ocd.error,1.)
    sample_curve = normpdf(sample_interval, ocd.date, ocd.error)
    max_sample_curve = max(sample_curve)

    line_x = np.array([0, max_sample_curve*3])
    line_y = np.array([ocd.date, ocd.date])

    ax3 = plt.twiny(ax1)
    for i in range(-1,2,1):
        ax3.plot(
            line_x,
            line_y+i*ocd.error,
            'k--',
            alpha=0.5-0.2*abs(i),
            lw=2-abs(i)
            )
    ax3.fill(
        sample_curve,
        sample_interval,
        'r',
        alpha=0.4
        )
    ax3.plot(
        sample_curve,
        sample_interval,
        'r',
        alpha=0.5
        )
    ax3.set_xbound(0,max_sample_curve*4)
    ax3.set_axis_off()


    # Calibration Curve
    xs, ys = mlab.poly_between(calib.array[:,0],
                               calib.array[:,1] - calib.array[:,2],
                               calib.array[:,1] + calib.array[:,2])
    ax1.fill(xs, ys, 'b', alpha=0.3)
    ax1.plot(
        calib.array[:,0],
        calib.array[:,1],
        'b',
        alpha=0.5,
        lw=1
        )

    # Confidence intervals

    ymin=[0.075, 0.05, 0.025]
    if(ocd.posterior.used):
        calibrated = ocd.posterior
    else:
        calibrated = ocd.likelihood

    for j in range(2,-1,-1):
        for i in calibrated.range[j]:
            ax1.axvspan(
                i[0], i[1],
                ymin=ymin[j],
                ymax=ymin[j]+0.07,
                facecolor='none',
                alpha=0.8)
            ax1.axvspan(
                i[0], i[1],
                ymin=ymin[j]+0.02,
                ymax=ymin[j]+0.07,
                facecolor='w',
                edgecolor='w',
                lw=2)

    comments = ocd.ref + "\n"
    comments += calib.ref + "\n"

    plt.text(0.55, 0.90,'{}'.format(comments),
         horizontalalignment='left',
         verticalalignment='center',
         transform = ax1.transAxes,
         bbox=dict(facecolor='white', alpha=0.9, lw=0))

    plt.text(0.745, 0.68,'{}'.format(calibrated.get_meta("",False)),
         horizontalalignment='left',
         verticalalignment='center',
         transform = ax1.transAxes,
         bbox=dict(facecolor='white', alpha=0.9, lw=0))

    # FIXME the following values 10 and 5 are arbitrary and could be probably
    # drawn from the f_m value itself, while preserving their ratio
    tl = len(ocd.likelihood.array[:,0])
    ax1.set_ybound(ocd.date - ocd.error * 8, ocd.date + ocd.error * 8)
    ax1.set_xbound(ocd.likelihood.array[0,0],ocd.likelihood.array[-1,0])

    #plt.savefig('image_%d±%d.pdf' %(f_m, sigma_m))
    plt.savefig(file_name)
    fig = plt.gcf()
    fig.clear()
Exemple #56
0
def add_at_risk_counts(*fitters, **kwargs):
    '''
    Add counts showing how many individuals were at risk at each time point in
    survival/hazard plots.

    Arguments:
      One or several fitters, for example KaplanMeierFitter,
      NelsonAalenFitter, etc...

    Keyword arguments (all optional):
      ax: The axes to add the labels to. Default is the current axes.
      fig: The figure of the axes. Default is the current figure.
      labels: The labels to use for the fitters. Default is whatever was
              specified in the fitters' fit-function. Giving 'None' will
              hide fitter labels.

    Returns:
      ax: The axes which was used.

    Examples:
        # First train some fitters and plot them
        fig = plt.figure()
        ax = plt.subplot(111)

        f1 = KaplanMeierFitter()
        f1.fit(data)
        f1.plot(ax=ax)

        f2 = KaplanMeierFitter()
        f2.fit(data)
        f2.plot(ax=ax)

        # There are equivalent
        add_at_risk_counts(f1, f2)
        add_at_risk_counts(f1, f2, ax=ax, fig=fig)
        # This overrides the labels
        add_at_risk_counts(f1, f2, labels=['fitter one', 'fitter two'])
        # This hides the labels
        add_at_risk_counts(f1, f2, labels=None)
    '''
    from matplotlib import pyplot as plt

    # Axes and Figure can't be None
    ax = kwargs.get('ax', None)
    if ax is None:
        ax = plt.gca()

    fig = kwargs.get('fig', None)
    if fig is None:
        fig = plt.gcf()

    if 'labels' not in kwargs:
        labels = [f._label for f in fitters]
    else:
        # Allow None, in which case no labels should be used
        labels = kwargs['labels']
        if labels is None:
            labels = [None] * len(fitters)
    # Create another axes where we can put size ticks
    ax2 = plt.twiny(ax=ax)
    # Move the ticks below existing axes
    # Appropriate length scaled for 6 inches. Adjust for figure size.
    ax2_ypos = -0.15 * 6.0 / fig.get_figheight()
    move_spines(ax2, ['bottom'], [ax2_ypos])
    # Hide all fluff
    remove_spines(ax2, ['top', 'right', 'bottom', 'left'])
    # Set ticks and labels on bottom
    ax2.xaxis.tick_bottom()
    # Match tick numbers and locations
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(ax.get_xticks())
    # Remove ticks, need to do this AFTER moving the ticks
    remove_ticks(ax2, x=True, y=True)
    # Add population size at times
    ticklabels = []
    for tick in ax2.get_xticks():
        lbl = ""
        for f, l in zip(fitters, labels):
            # First tick is prepended with the label
            if tick == ax2.get_xticks()[0] and l is not None:
                if is_latex_enabled():
                    s = "\n{}\\quad".format(l) + "{}"
                else:
                    s = "\n{}   ".format(l) + "{}"
            else:
                s = "\n{}"
            lbl += s.format(f.durations[f.durations >= tick].shape[0])
        ticklabels.append(lbl.strip())
    # Align labels to the right so numbers can be compared easily
    ax2.set_xticklabels(ticklabels, ha='right')

    # Add a descriptive headline.
    ax2.xaxis.set_label_coords(0, ax2_ypos)
    ax2.set_xlabel('At risk')

    plt.tight_layout()
    return ax
plt.figure()
ax = plt.gca()
ax.semilogx(Coalbins.in_units('yr'),array(NltP_pt4)/NltP_pt4[-1],ls='-',color='k',label=r'$\mathrm{MW:\,}y_\mathrm{p} = -0.4$')
ax.semilogx(Coalbins.in_units('yr'),array(NltP_pt3)/NltP_pt3[-1],ls='-',color='c',label=r'$\mathrm{OGLE-II,\,LMC:\,}y_\mathrm{p} = -0.3$')
ax.semilogx(Coalbins.in_units('yr'),array(NltP_pt1)/NltP_pt1[-1],ls='--',color='c',label=r'$\mathrm{OGLE-III,\,LMC:\,}y_\mathrm{p} = -0.1$')
ax.semilogx(Coalbins.in_units('yr'),array(NltP_pt9)/NltP_pt9[-1],ls='-',color='m',label=r'$\mathrm{OGLE-II,\,SMC:\,}y_\mathrm{p} = -0.9$')
ax.axvline(x=13.6e9,ls=':',color='grey')
ax.set_xlabel('$t_\mathrm{coalesce}\,(\mathrm{years})$')
ax.set_ylabel('$f(\mathrm{coalescence\,time} < t_\mathrm{coalesce})$')

plt.axvline(x=minCoal.in_units('yr').item(),ls='--',color='k')

leg = plt.legend(loc=2,fontsize=24)
# leg.get_frame().set_alpha(0)

ax2 = plt.twiny()
ax2.set_xscale('log')
ax2.set_xlim(ax.get_xlim())
ax2.set_xlabel(r'$\mathrm{Redshift\,at\,}t(z = 0.1) - t_\mathrm{coalesce}$')
t_zpt1 = z_to_time(0.1)
locs = YTArray([1e9,2.5e9,6e9,1.2e10],'yr')
formtime = t_zpt1 - locs        #time at which the system became a binary black hole
# msk = formtime > 0
redshifts = time_to_z(formtime)    #top labels
# bottomlocs = Coalbins[msk]
# toptickloc = bottomlocs[::20]
topticklab = ['{0:.2}'.format(z.item()) for z in redshifts]
ax2.set_xticks(locs)
ax2.set_xticklabels(topticklab)

plt.savefig('Coal_cumulative.png')
Exemple #58
0
def add_at_risk_counts(*fitters, **kwargs):
    """
    Add counts showing how many individuals were at risk at each time point in
    survival/hazard plots.

    Parameters
    ----------
    fitters:
      One or several fitters, for example KaplanMeierFitter,
      NelsonAalenFitter, etc...


    Returns
    --------
      ax: The axes which was used.

    Examples
    --------
    >>> # First train some fitters and plot them
    >>> fig = plt.figure()
    >>> ax = plt.subplot(111)
    >>>
    >>> f1 = KaplanMeierFitter()
    >>> f1.fit(data)
    >>> f1.plot(ax=ax)
    >>>
    >>> f2 = KaplanMeierFitter()
    >>> f2.fit(data)
    >>> f2.plot(ax=ax)
    >>>
    >>> # There are equivalent
    >>> add_at_risk_counts(f1, f2)
    >>> add_at_risk_counts(f1, f2, ax=ax, fig=fig)
    >>>
    >>> # This overrides the labels
    >>> add_at_risk_counts(f1, f2, labels=['fitter one', 'fitter two'])
    >>>
    >>> # This hides the labels
    >>> add_at_risk_counts(f1, f2, labels=None)
    """
    from matplotlib import pyplot as plt

    # Axes and Figure can't be None
    ax = kwargs.get("ax", None)
    if ax is None:
        ax = plt.gca()

    fig = kwargs.get("fig", None)
    if fig is None:
        fig = plt.gcf()

    if "labels" not in kwargs:
        labels = [f._label for f in fitters]
    else:
        # Allow None, in which case no labels should be used
        labels = kwargs["labels"]
        if labels is None:
            labels = [None] * len(fitters)
    # Create another axes where we can put size ticks
    ax2 = plt.twiny(ax=ax)
    # Move the ticks below existing axes
    # Appropriate length scaled for 6 inches. Adjust for figure size.
    ax2_ypos = -0.15 * 6.0 / fig.get_figheight()
    move_spines(ax2, ["bottom"], [ax2_ypos])
    # Hide all fluff
    remove_spines(ax2, ["top", "right", "bottom", "left"])
    # Set ticks and labels on bottom
    ax2.xaxis.tick_bottom()
    # Match tick numbers and locations
    ax2.set_xlim(ax.get_xlim())
    ax2.set_xticks(ax.get_xticks())
    # Remove ticks, need to do this AFTER moving the ticks
    remove_ticks(ax2, x=True, y=True)
    # Add population size at times
    ticklabels = []
    for tick in ax2.get_xticks():
        lbl = ""
        for f, l in zip(fitters, labels):
            # First tick is prepended with the label
            if tick == ax2.get_xticks()[0] and l is not None:
                if is_latex_enabled():
                    s = "\n{}\\quad".format(l) + "{}"
                else:
                    s = "\n{}   ".format(l) + "{}"
            else:
                s = "\n{}"
            lbl += s.format(f.durations[f.durations >= tick].shape[0])
        ticklabels.append(lbl.strip())
    # Align labels to the right so numbers can be compared easily
    ax2.set_xticklabels(ticklabels, ha="right")

    # Add a descriptive headline.
    ax2.xaxis.set_label_coords(0, ax2_ypos)
    ax2.set_xlabel("At risk")

    plt.tight_layout()
    return ax
Exemple #59
0
# We now request data from the server using this query. The `NCSS` class handles parsing
# this NetCDF data (using the `netCDF4` module). If we print out the variable names,
# we see our requested variables, as well as a few others (more metadata information)
data = ncss.get_data(query)
list(data.variables)

###########################################
# We'll pull out the variables we want to use, as well as the pressure values. To get the
# name of the correct variable for pressure (which matches the levels for temperature and
# relative humidity, we look at the `coordinates` attribute. The last of the variables
# listed in `coordinates` is the pressure dimension.
temp = data.variables['Temperature_isobaric']
relh = data.variables['Relative_humidity_isobaric']
press_name = relh.coordinates.split()[-1]
press = data.variables[press_name]
press_vals = press[:].squeeze()

###########################################
# Now we can plot these up using matplotlib.
fig, ax = plt.subplots(1, 1, figsize=(9, 8))
ax.plot(temp[:].squeeze(), press_vals, 'r', linewidth=2)
ax.set_xlabel('{} ({})'.format(temp.standard_name, temp.units))
ax.set_ylabel('{} ({})'.format(press.standard_name, press.units))

# Create second plot with shared y-axis
ax2 = plt.twiny(ax)
ax2.plot(relh[:].squeeze(), press_vals, 'g', linewidth=2)
ax2.set_xlabel('{} ({})'.format(relh.standard_name, relh.units))
ax.set_ylim(press_vals.max(), press_vals.min())
ax.grid(True)