def write(self):
        self.writePreHook()

        for cut in self.contourData.filteredCombinedData:
            # Add cut to the output filename
            (outputFilename, ext) = os.path.splitext(self.outputFilename)
            outputFilename = "{0}_{1}_{2:.0f}{3}".format(outputFilename, cut.key, cut.value, ext)

            plt.ioff()
            plt.figure(figsize=(8,6))
            #plt.yscale('log')
            plt.ylim([0,1.0])
            plt.figtext(0.05, 0.96, 'Cut: {0} = {1:.0f}'.format(cut.key, cut.value), color='grey', size='small')
            plt.figtext(0.05, 0.93, 'Plot written at {:%d/%m/%Y %H:%M}'.format(datetime.datetime.now()), color='grey', size='small')

            for f in self.contourData.contributingRegionsFiltered[cut]:
                data = self.contourData.filteredData[f][cut]
                label = filterLabel(f, self.gridConfig)

                if not cut.isSimple():
                    plt.xticks( np.arange(len(data)), ["%d_%d" % (x[self.gridConfig.x], x[self.gridConfig.y]) for x in data.values()])
                    xLabel = "Grid point"
                else:
                    var = self.gridConfig.x
                    if cut.key == var: 
                        var = self.gridConfig.y
                    xLabel = var
                    plt.xticks( np.arange(len(data)), ["%d" % (x[var]) for x in data.values()])
                print [x[self.contourData.combineOn] for x in data.values()]
                plt.plot( [x[self.contourData.combineOn] for x in data.values()], label=label )

                plt.plot( [0.05 for x in data.values()], color='r', linestyle='--', linewidth=2)
    def makeVenn3(self,truthDict,snr,addon=''):
        type1 = '.svg'
        type2 = '.png'
        f = \
            os.path.join(self.destDir,self.fname+'.c'+str(self.ch)+'.snr_'+str(snr)+addon)


        reqdVennOrder = [('map','not','not'),
                         ('not','map','not'),
                         ('map','map','not'),
                         ('not','not','map'),
                         ('map','not','map'),
                         ('not','map','map'),
                         ('map','map','map')]
        valSet = list()
        for vSet in reqdVennOrder:
            val = truthDict[vSet]
            valSet.append(val)
        
        unmapped = truthDict[('not','not','not')]
        # Making venn diagram
        plt.figure(figsize=( 5,5))
        v = \
            venn3(subsets=valSet,set_labels=('Cycle1:Mock','Cycle2:Mock','Cycle3:Edman'))
        c = venn3_circles(subsets=valSet,ls='solid')
        txt = 'unmapped='+str(unmapped)+'\n SNR='+str(snr)
        plt.title('Peak Mapping :'+self.fname + '.'+self.frame+'\n channel:'+str(self.ch))
        plt.figtext( 0.7,0.1,txt)
        plt.savefig(f+type1,dpi=300)        
        plt.savefig(f+type2,dpi=300)
        plt.close()
Example #3
0
 def saveas_pdf(self, pdfname, figsize=(5,2), pos=(0.1,0.1,0.85,0.75),
                unit='lam', vr=None, brief=False):
     #
     import numpy as np
     if self.__fig__ == None:
         self.__fig__ = plt.figure(figsize = figsize)
     else:
         self.__fig__.set_size_inches(figsize[0], figsize[1])
     #
     ax = self.__fig__.add_axes(pos)
     #
     if unit == 'lam':
         ax.plot(self.lam, self.spec)
         ax.set_xlabel(r'$\lambda$ ($\mu$m)')
         ax.set_ylabel(r'Flux (jy)')
     else:
         ax.plot(self.v/1e3, self.spec, drawstyle='steps-mid')
         ax.set_xlabel(r'$V$ (km s$^{-1}$)')
         ax.set_ylabel(r'Flux (jy)')
     if vr != None:
         ax.set_xlim(vr)
     mx,mn = np.nanmax(self.spec), np.nanmin(self.spec)
     if (mx-mn) <= mn:
         ylim = (mn*0.9, mx*1.1)
     else:
         ylim = (0, mx*1.1)
     ax.set_ylim(ylim)
     #
     plt.figtext(0.1, 0.87, self.format_info(brief=brief),
                 fontdict={'horizontalalignment': 'left', 'verticalalignment': 'bottom'})
     plt.figtext(0.1, 0.60, r'$\int F_\nu d\nu$ = {0:.1e} W m$^{{-2}}$'.format(self.intfluxl),
                 fontdict={'horizontalalignment': 'left', 'verticalalignment': 'bottom'})
     plt.savefig(pdfname, bbox_inches='tight')
     self.__fig__.clf()
     return
Example #4
0
    def dovis(self):
        """
        Do runtime visualization.
        """

        plt.clf()

        phi = self.cc_data.get_var("phi")

        myg = self.cc_data.grid

        plt.imshow(np.transpose(phi[myg.ilo:myg.ihi+1,
                                         myg.jlo:myg.jhi+1]),
                     interpolation="nearest", origin="lower",
                     extent=[myg.xmin, myg.xmax, myg.ymin, myg.ymax])

        plt.xlabel("x")
        plt.ylabel("y")
        plt.title("phi")

        plt.colorbar()

        plt.figtext(0.05,0.0125, "t = %10.5f" % self.cc_data.t)

        plt.draw()
Example #5
0
def plot_onetimeseries_right(fig,n,ThisOne,xarray,yarray,p):
    if not p.has_key('ts_ax'):
        ts_ax = fig.add_axes([p['ts_XAxOrg'],p['YAxOrg'],p['ts_XAxLen'],p['ts_YAxLen']])
        ts_ax.hold(False)
        ts_ax.yaxis.tick_right()
        TextStr = ThisOne+'('+p['Units']+')'
        txtXLoc = p['ts_XAxOrg']+0.01
        txtYLoc = p['YAxOrg']+p['ts_YAxLen']-0.025
        plt.figtext(txtXLoc,txtYLoc,TextStr,color='b',horizontalalignment='left')
    else:
        ts_ax = p['ts_ax'].twinx()
    colour = 'r'
    if p.has_key('ts_ax'): del p['ts_ax']
    ts_ax.plot(xarray,yarray,'r-')
    ts_ax.xaxis.set_major_locator(p['loc'])
    ts_ax.xaxis.set_major_formatter(p['fmt'])
    ts_ax.set_xlim(p['XAxMin'],p['XAxMax'])
    ts_ax.set_ylim(p['RYAxMin'],p['RYAxMax'])
    if n==0:
        ts_ax.set_xlabel('Date',visible=True)
    else:
        ts_ax.set_xlabel('',visible=False)
    TextStr = str(p['nNotM'])+' '+str(p['nMskd'])
    txtXLoc = p['ts_XAxOrg']+p['ts_XAxLen']-0.01
    txtYLoc = p['YAxOrg']+p['ts_YAxLen']-0.025
    plt.figtext(txtXLoc,txtYLoc,TextStr,color='r',horizontalalignment='right')
    if n > 0: plt.setp(ts_ax.get_xticklabels(),visible=False)
def plot_1d(xdata, ydata, color, x_axis, y_axis, system, analysis, average = False, t0 = 0, **kwargs):
	""" Creates a 1D scatter/line plot:

	Usage: plot_1d(xdata, ydata, color, x_axis, y_axis, system, analysis, average = [False|True], t0 = 0)
	
	Arguments:
	xdata, ydata: self-explanatory
	color: color to be used to plot data
	x_axis, y_axis: strings to be used for the axis label
	system: descriptor for the system that produced the data
	analysis: descriptor for the analysis that produced the data
	average: [False|True]; Default is False; if set to True, the function will calc the average, standard dev, and standard dev of mean of the y-data	# THERE IS A BUG IF average=True; must read in yunits for this function to work at the moment.
	t0: index to begin averaging from; Default is 0
	
	kwargs:
		xunits, yunits: string with correct math text describing the units for the x/y data
		x_lim, y_lim: list w/ two elements, setting the limits of the x/y ranges of plot
		plt_title: string to be added as the plot title
		draw_line: int value that determines the line style to be drawn; giving myself space to add more line styles if I decide I need them

	"""
	# INITIATING THE PLOT...
	plt.plot(xdata, ydata, '%s' %(color))

	# READING IN KWARG DICTIONARY INTO SPECIFIC VARIABLES
	for name, value in kwargs.items():
		if name == 'xunits':
			x_units = value
			x_axis = '%s (%s)' %(x_axis, value)
		elif name == 'yunits':
			y_units = value
			y_axis = '%s (%s)' %(y_axis, value)
		elif name == 'x_lim':
			plt.xlim(value)
		elif name == 'y_lim':
			plt.ylim(value)
		elif name == 'plt_title':
			plt.title(r'%s' %(value), size='14')
		elif name == 'draw_line':
			draw_line = value
			if draw_line == 1:
				plt.plot([0,max(ydata)],[0,max(ydata)],'r-',linewidth=2)
			else:
				print 'draw_line = %s has not been defined in plotting_functions script' %(line_value)
	
	plt.grid(b=True, which='major', axis='both', color='#808080', linestyle='--')
	plt.xlabel(r'%s' %(x_axis), size=12)
	plt.ylabel(r'%s' %(y_axis), size=12)

	# CALCULATING THE AVERAGE/SD/SDOM OF THE Y-DATA
	if average != False:
		avg = np.sum(ydata[t0:])/len(ydata[t0:])
		SD = stdev(ydata[t0:])
		SDOM = SD/sqrt(len(ydata[t0:]))

		plt.axhline(avg, xmin=0.0, xmax=1.0, c='r')
		plt.figtext(0.680, 0.780, '%s\n%6.4f $\\pm$ %6.4f %s \nSD = %4.3f %s' %(analysis, avg, SDOM, y_units, SD, y_units), bbox=dict(boxstyle='square', ec='r', fc='w'), fontsize=12)

	plt.savefig('%s.%s.plot1d.png' %(system,analysis),dpi=300)
	plt.close()
def plotta(name,fname,texts,x,y):
    print name
    #find optical parameters
    a,b,pa = galaxy.FULLMAJAX[0],galaxy.FULLMINAX[0], galaxy.PA[0]
    ra,dec = galaxy.GRA2000[0], galaxy.GDEC2000[0]
    #pa = pa + 90.
    beam = 18.2/3600.0
    rDust = galaxy.R250[0]*1.4
    #make plot
    f = ap.FITSFigure(fname,figure=fig,subplot=[x,y,dx,dy])
    #f.show_contour(str(name)+"-PSWmap-ellipses.fits",levels=[rDust], smooth=1, colors='black')
    f.recenter(ra,dec,beam*4.)
    f.show_colorscale(vmin=-6.02e-02, vmax=20.664e-02, cmap='gist_earth')
    #f.show_contour(fname,levels=150, filled=True, cmap='cool') 
    f.add_scalebar(0.5/60.0)
    f.scalebar.set_label('30 arcsec')
    f.scalebar.set_color('black')
    #f.show_grid()
    f.set_tick_labels_format(xformat='hh:mm:ss',yformat='dd:mm:ss')
    #f.show_markers(ra, dec,c='r',marker='x')
    f.show_ellipses(ra, dec, a*1.15/60.0, a*1.15/60.0, angle=pa, edgecolor='red', lw=1)
    f.show_ellipses(ra, dec, rDust/60.0, rDust/60.0, angle=pa, edgecolor='black', lw=1)
    f.add_beam(major=beam, minor=beam,angle=0.0)
    f.show_beam(major=beam, minor=beam,angle=0.0,fc='white')
    f.axis_labels.set_font(size=8)
    f.tick_labels.set_font(size=6)
    #f.set_theme('publication')
    
    # add text 
    plt.figtext(x+tune, y+0.23,texts, size=12, weight="semibold", color='black')
Example #8
0
def MOorderplot(popul,path,picname=None,title=None):
    x=[]; y1=[]; y2=[]; y3=[]; y4=[]; y5=[]; y6=[]; c=[]
    for i,dude in enumerate(popul):
        x.append(i)
        y1.append(dude.no)
        y2.append(dude.oldno)
        y3.append(dude.ranks[0])
        y4.append(dude.ranks[1])
        y5.append(dude.score)
        y6.append(dude.overall_rank)
        c.append(dude.score)
    f=plt.figure(figsize=(8,12)); a1=f.add_subplot(321); a2=f.add_subplot(322); a3=f.add_subplot(323); a4=f.add_subplot(324); a5=f.add_subplot(325); a6=f.add_subplot(326)
    a1.scatter(x,y1,c=c,cmap=cm.gist_stern)
    a2.scatter(x,y2,c=c,cmap=cm.gist_stern)
    a3.scatter(x,y3,c=c,cmap=cm.gist_stern)
    a4.scatter(x,y4,c=c,cmap=cm.gist_stern)
    a5.scatter(x,y5,c=c,cmap=cm.gist_stern)
    a6.scatter(x,y6,c=c,cmap=cm.gist_stern)
    a1.set_xlabel('place in population'); a1.set_ylabel('dude.no')
    a2.set_xlabel('place in population'); a2.set_ylabel('dude.oldno')
    a3.set_xlabel('place in population'); a3.set_ylabel('dude.ranks[0]')
    a4.set_xlabel('place in population'); a4.set_ylabel('dude.ranks[1]')
    a5.set_xlabel('place in population'); a5.set_ylabel('dude.score')
    a6.set_xlabel('place in population'); a6.set_ylabel('dude.overall_rank')
    if title is not None: plt.figtext(0.5, 0.98,title,va='top',ha='center', color='black', weight='bold', size='large')
    if picname is not None:
        plt.savefig(join(path,picname))
    else:
        plt.savefig(join(path,'orderplot_c'+str(popul.ncase)+'_sc'+str(popul.subcase).zfill(3)+'_g'+str(popul.gg)+'.png'))
    plt.close()
def plot_results(algo, datas, xlabel, ylabel, note, factor=None):
    plt.clf()
    fig1, ax1 = plt.subplots()
    plt.figtext(0.90, 0.94, "Note: " + note, va='top', ha='right')
    w, h = fig1.get_size_inches()
    fig1.set_size_inches(w*1.5, h)
    ax1.set_xscale('log')
    ax1.get_xaxis().set_major_formatter(ticker.ScalarFormatter())
    ax1.get_xaxis().set_minor_locator(ticker.NullLocator())
    ax1.set_xticks(datas[0][:,0])
    ax1.grid(color="lightgrey", linestyle="--", linewidth=1, alpha=0.5)
    if factor:
        ax1.set_xticklabels([str(int(x)) for x in datas[0][:,0]/factor])
    plt.xlabel(xlabel, fontsize=16)
    plt.ylabel(ylabel, fontsize=16)
    plt.xlim(datas[0][0,0]*.9, datas[0][-1,0]*1.1)
    plt.suptitle("%s Performance" % (algo), fontsize=28)

    for backend, data in zip(backends, datas):
        N = data[:, 0]
        plt.plot(N, data[:, 1], 'o-', linewidth=2, markersize=5, label=backend)
        dy = max(data[:,1]) / 20.0
        for x, y in zip(N, data[:, 1]):
            plt.annotate('%.1f' % y, (x, y+dy))
        plt.legend(loc='upper left', fontsize=18)

    plt.savefig(algo + '.png')
Example #10
0
def plot_radar(gene2plot, tissue, path):
    '''
    Plot radar plot
    :param data:
    :param path:
    :return:
    '''
    data = gene2plot
    #[0.00364299,0.0582878,0.04189435,0.13661202,0.10928962,0.14754098,0.00728597,0.0582878,0.40801457,0.3]
    spoke_labels = tissue
    #['lung', 'bone', 'blood', 'epithelial', 'progenitor', 'nervous', 'endocrine', 'epidermal', 'immune','liver']
    N = len(data)
    theta = radar_factory(N, frame='polygon')

    plt.rcParams['font.size'] = 10
    fig = plt.figure(figsize=(6, 6))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)

    ax = fig.add_subplot(1, 1, 1, projection='radar')
    #plt.rgrids([0.1, 0.2, 0.3, 0.4])
    #ax.set_title('Fraction of gene', weight='bold', fontsize=15, position=(0.5, 1.1),
    #             horizontalalignment='center', verticalalignment='center')
    ax.plot(theta, data, color='r', lw=1)
    ax.fill(theta, data, facecolor='r', alpha=0.25)
    ax.set_varlabels(spoke_labels)
    plt.figtext(0.5, 0.965, 'Gene enrichment fraction for (tissue)* types',
                ha='center', color='black', weight='bold', fontsize=15)
    plt.savefig(os.path.join(path, 'GCAM_redar.svg'))
    plt.clf()
    plt.close()
def plot_multiline_alpha(data_list, legend_list, picture_title, picture_save_path, text1, text2):
    """ Draw data series info """

    # plot file and save picture
    fig = plt.figure(figsize=(15, 8))

    left = 0.1
    bottom = 0.3
    width = 0.75
    height = 0.60
    ax = fig.add_axes([left, bottom, width, height])
    ax.set_title(picture_title)

    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    plt.gca().xaxis.set_major_locator(mdates.YearLocator())
    plt.figtext(0.01, 0.01, text1, horizontalalignment='left')
    plt.figtext(0.51, 0.01, text2, horizontalalignment='left')

    date_series = data_list[0].index

    color_list = ['r-', 'b-', 'y-', 'g-']

    for i, data_series in enumerate(data_list):
        plt.plot(date_series, data_series, color_list[i], label=legend_list[i])

    min_date = date_series[0]
    max_date = date_series[-1]
    plt.gca().set_xlim(min_date, max_date)
    plt.legend(loc=0)
    fig.autofmt_xdate()
    fig.savefig(picture_save_path)
    plt.close()
Example #12
0
    def plotEvolution(self, var, name, name_long="new plot", figlabel="Resolution", ylabel="", loc="", reference=False):
        """
        Plots evolution in time of the given variable.
        """
        plt.clf()
        var = np.array(var)
        if var.ndim == 1:  # in case a single set of data is provided
            var = [var]
        ls = ["-.", "--", "-"]
        kwargs = {}
        if "bw" in self.file_name:
            kwargs["color"] = "k"
        for i in range(len(self.t)):
            plt.plot(self.t[i], var[i], label="{0} {1}".format(figlabel, i + 1), ls=ls[i], **kwargs)
        plt.title(self.title.format(name_long))
        plt.xlabel(self.xlabel)
        plt.ylabel(ylabel)

        if self.info:
            plt.figtext(self.text_pos[0], self.text_pos[1], self.info)
        plt.xlim(np.round(np.min(self.t[0])), np.round(np.max(self.t[0])))
        if reference:
            self.plotReference()
        plt.legend(loc=loc or self.loc)
        for e in self.ext:
            plt.savefig(os.path.join(self.out_dir, self.file_name.format(name=name, ext=e)))
Example #13
0
    def save_fig(self, poly=None, directory="/tmp/plots",
                 overwrite=False, labels=None, extension=".png"):
        """Save the pass as a figure. Filename is automatically generated.
        """
        logger.debug("Save fig " + str(self))
        rise = self.risetime.strftime("%Y%m%d%H%M%S")
        fall = self.falltime.strftime("%Y%m%d%H%M%S")
        filename = os.path.join(directory,
                                (rise + self.satellite.replace(" ", "_") + fall + extension))

        self.fig = filename
        if not overwrite and os.path.exists(filename):
            return filename

        import matplotlib as mpl
        mpl.use('Agg')
        import matplotlib.pyplot as plt
        plt.clf()
        with Mapper() as mapper:
            mapper.nightshade(self.uptime, alpha=0.2)
            self.draw(mapper, "-r")
            if poly is not None:
                poly.draw(mapper, "-b")
        plt.title(str(self))
        for label in labels or []:
            plt.figtext(*label[0], **label[1])
        plt.savefig(filename)
        return filename
Example #14
0
def plot_tiegcm(time, lat, lon, den, temp, ht, pres, image_name):
    """Plot density, temperature, and geopotential height
    for all latitudes and longitudes at relevant time"""
    y_values = [-90, -45, 0, 45, 90]
    x_values = [-180, -135, -90, -45, 0, 45, 90, 135, 180]
    fig = plt.figure()
#    fig.subplots_adjust(left = 0.25, right = 0.7, bottom = 0.07, top = 0.9, wspace = 0.2, hspace = 0.08)
    sub_den = fig.add_subplot(3, 1, 1)
    plot_settings(sub_den, den*1e12, lon, lat, 
                  y_values, x_values = [], 
                  ylabel = "", xlabel = "",
                  title = 'Density',
                  ctitle = r"x 10$^{-12}$ kgm$^{-3}$ ",
                  minmax = [2., 4.])
    pres = format(pres, '.2e')
    plt.title('{} at {} Pa'.format(time, pres), fontsize = 11)
    sub_temp = fig.add_subplot(3, 1, 2)
    plot_settings(sub_temp, temp, lon, lat,
                  y_values, x_values = [],
                  ylabel = 'Latitude [$^\circ$]', xlabel = "",
                  title = 'Temperature',
                  ctitle = "Kelvin",
                  minmax = [750., 1250.])
    sub_ht = fig.add_subplot(3, 1, 3)
    plot_settings(sub_ht, ht/100000., lon, lat,
                  y_values, x_values, 
                  ylabel = " ", xlabel = 'Longitude [$^\circ$]', 
                  title = 'Geopotential Height', 
                  ctitle = "km",
                  minmax = [350., 450.])
    plt.figtext(.6, .032, r'$\copyright$ Crown Copyright. Source: Met Office', size = 8)
    plt.tight_layout()
#    insert_logo()
    save_to_web(fig, time, image_name)
Example #15
0
 def _show_3d_plot(self):
     '''
     Shows the plot using pylab.  Usually I won't do imports in methods,
     but since plotting is a fairly expensive library to load and not all 
     machines have matplotlib installed, I have done it this way.
     '''
     import matplotlib.pyplot as plt
     import mpl_toolkits.mplot3d.axes3d as p3
     from matplotlib.font_manager import FontProperties
     fig = plt.figure()
     ax = p3.Axes3D(fig)
     font = FontProperties()
     font.set_weight('bold')
     font.set_size(20)
     (lines, labels, unstable) = self.pd_plot_data
     count = 1
     newlabels = list()
     for x, y, z in lines:
         ax.plot(x, y, z, 'bo-', linewidth=3, markeredgecolor='b', markerfacecolor='r', markersize=10)
     for coords in sorted(labels.keys()):
         entry = labels[coords]
         label = entry.name
         if len(entry.composition.elements) == 1:
             # commented out options are only for matplotlib 1.0.  Removed them so that most ppl can use this class.
             ax.text(coords[0], coords[1], coords[2], label)#, horizontalalignment=halign, verticalalignment=valign, fontproperties=font)
         else:
             ax.text(coords[0], coords[1], coords[2], str(count))#, horizontalalignment=halign, verticalalignment=valign, fontproperties=font)
             newlabels.append(str(count) + " : " + label)
             count += 1
     plt.figtext(0.01, 0.01, '\n'.join(newlabels))
     ax.axis('off')
     plt.show()
Example #16
0
def beaut(fig, axes):
    for row_i, axes_row in enumerate(axes):
        for col_i, ax in enumerate(axes_row):
            ax.set_xticks([])
            ax.set_yticks([])

            if col_i == 0:
                ax.set_ylabel(str(row_i))

            if row_i == 9:
                ax.set_xlabel(str(col_i))

    plt.figtext(
        0.5,
        0,
        "public goods effect threshold",
        figure=fig,
        fontsize=17,
        horizontalalignment='center',
        verticalalignment='top',
    )


    plt.figtext(
        0,
        0.5,
        "quorum sensing threshold",
        figure=fig,
        fontsize=17,
        horizontalalignment='right',
        verticalalignment='center',
        rotation=90,
    )

    fig.tight_layout()
Example #17
0
def plot_noisy_means(graph_title, means, bands, series, xvals=None, xlabel=None, ylabel=None, subtitle=None, data=None, filename='results.pdf'):
    colors = ['blue','red','green', 'black', 'orange', 'purple', 'brown', 'yellow'] # max 8 lines
    assert(means.shape == bands.shape)
    assert(xvals is None or xvals.shape[0] == means.shape[1])
    assert(means.shape[0] <= len(colors))
    if xvals is None:
        xvals = np.arange(means.shape[0])
    ax = plt.axes([.1,.1,.8,.7])
    plt.ticklabel_format(axis='y', style='plain', useOffset=False)
    for i,mean in enumerate(means):
        plt.plot(xvals, mean, label=series[i], color=colors[i])
        plt.fill_between(xvals, mean + bands[i], mean - bands[i], facecolor=colors[i], alpha=0.2)
    if xlabel is not None:
        plt.xlabel(xlabel)
    if ylabel is not None:
        plt.ylabel(ylabel)
    if subtitle is not None:
        plt.figtext(.40,.9, graph_title, fontsize=18, ha='center')
        plt.figtext(.40,.85, subtitle, fontsize=10, ha='center')
    else:
        plt.title('{0}'.format(graph_title))
    # Shink current axis by 20%
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    # Put a legend to the right of the current axis
    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=12)
    plt.savefig(filename)
    plt.clf()
def finish_plot(ylabel=r'z [$\mu$ m]'):
    plt.xlabel(r'$\theta$ [deg]')
    plt.xlim(0, 360)
    plt.ylabel(ylabel)
    
    yoke_label = ord('A')
    
    for i in xrange(0, 37):

        x = (i * 10.0 - 15.0 - 0.1012) % 360.0

        if i % 3 == 0:
            plt.axvline(x, linestyle='-', color='k', alpha=0.2)

        else:
            plt.axvline(x, linestyle='--', color='k', alpha=0.2)
        
        if i is not 0:
            if i < 10:
                s = str(i) + ' '
            else:
                s = str(i)
                
            plt.figtext(0.052 + i * (0.868 / 36.0), 0.86, s, color='k', alpha=0.4)
            
        if (i % 3) == 1:
            plt.figtext(0.052 + i * (0.868 / 36.0), 0.82, chr(yoke_label), color='k', alpha=0.4)
            yoke_label += 1
            
    plt.show()
Example #19
0
    def _get_3d_plot(self, label_stable=True):
        """
        Shows the plot using pylab.  Usually I won"t do imports in methods,
        but since plotting is a fairly expensive library to load and not all
        machines have matplotlib installed, I have done it this way.
        """
        import matplotlib.pyplot as plt
        import mpl_toolkits.mplot3d.axes3d as p3
        from matplotlib.font_manager import FontProperties

        fig = plt.figure()
        ax = p3.Axes3D(fig)
        font = FontProperties()
        font.set_weight("bold")
        font.set_size(20)
        (lines, labels, unstable) = self.pd_plot_data
        count = 1
        newlabels = list()
        for x, y, z in lines:
            ax.plot(x, y, z, "bo-", linewidth=3, markeredgecolor="b", markerfacecolor="r", markersize=10)
        for coords in sorted(labels.keys()):
            entry = labels[coords]
            label = entry.name
            if label_stable:
                if len(entry.composition.elements) == 1:
                    ax.text(coords[0], coords[1], coords[2], label)
                else:
                    ax.text(coords[0], coords[1], coords[2], str(count))
                    newlabels.append("{} : {}".format(count, latexify(label)))
                    count += 1
        plt.figtext(0.01, 0.01, "\n".join(newlabels))
        ax.axis("off")
        return plt
	def __init__(self):
		plt.ion()
		self.fig = plt.figure(num=3, figsize=(12,7))
		self.ax = self.fig.gca(projection='3d')
		self.ax.set_xlim(-255, 255)
		self.ax.set_ylim(-255, 255)
		self.ax.set_zlim(-255, 255)
		axisline = np.linspace(-255, 255, 6)
		zeros =  np.zeros((1,6)).tolist()[0]
		self.ax.plot(axisline, zeros, zeros, 'b', linewidth=2)
		self.ax.plot(zeros, axisline, zeros, 'b', linewidth=2)
		self.ax.plot(zeros, zeros, axisline, 'b', linewidth=2)

		bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)
		self.annotation = plt.figtext(0.02, 0.9, 'rssi = ', size=15, alpha = 0.9, bbox = bbox_props)
		self.Freq = plt.figtext(0.91, 0.85, 'freq = ???', size=10, alpha = 0.9, bbox = bbox_props)
		self.Freq = plt.figtext(0.91, 0.9, 'Horizontal Plane', size=10, alpha = 0.9, bbox = bbox_props)

		# quiver lines (there is no quiver 3d so I draw the vector manually 
		# using plot of two points (0 to rho)
		self.referencedir = np.array([1, 0, 0])
		self.polarline, = self.ax.plot([0, self.referencedir[0]] , [0, self.referencedir[1]], [0, self.referencedir[2]], 'k', linewidth=2)
		# since its a T shaped, these are the two smaller lines 
		self.wing1 = np.array([0, 1, 0])
		self.wing2 = np.array([0, -1, 0])
		self.polarline, = self.ax.plot([0, self.wing1[0]] , [0, self.wing1[1]], [0, self.wing1[2]], 'k', linewidth=2)
		self.polarline, = self.ax.plot([0, self.wing2[0]] , [0, self.wing2[1]], [0, self.wing2[2]], 'k', linewidth=2)
		# initialize x,y,z buffers for mesh plotting as well
		self.xdata = []
		self.ydata = []
		self.zdata = []
		self.polarline2, = self.ax.plot(self.xdata,self.ydata, self.zdata, 'r')
def shots4time(player='Noah', team='CHI', 
               s_date='20091001', f_date='20151231', path='D:\Gal\Work\Results'):
    ''' '''
    actions_1, played_games_1 = actions_raster(players=[player], team=team,
                                               s_date=s_date, f_date=f_date, path=path, action=c.Shot)
    actions_2, played_games_2 = time_raster(player, team, s_date, f_date, path)
    actions_3, played_games_3 = actions_raster(players=[player], team=team, 
                                               s_date=s_date, f_date=f_date, path=path, action=c.FreeThrow)

    plt.hold(1)
    # plt.title(player+','+team)
    # plt.plot(actions_1, played_games_1, 'b.')
    # plt.plot(actions_3, played_games_3, 'm.')

    plt.figure(1)
    plt.plot(actions_histogram(actions_1), 'b')
    plt.plot(actions_histogram(actions_2), 'r')
    plt.plot(actions_histogram(actions_3), 'm')

    plt.figure(2)
    plt.title(player+','+team)
    plt.figtext(0, 0.5, 'blue - shots \n'+'red - presentce on court\n'+'magenta - freethrows')
    plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_1), 3)), 'b')
    plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_2), 3)), 'r')
    plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_3), 3)), 'm')
    plt.xlabel('Time (in half minutes)')
    plt.ylabel('Points')
    plt.grid(axis='x')
    plt.xticks(np.arange(1, 5)*c.Q_LEN/30)
    plt.show()
Example #22
0
def plot_graph(data_frame, data_frame_features):
    data_frame_features.remove('irisClass')
    grouped_data_frame = data_frame.groupby(data_frame['irisClass']).apply(
        lambda tdf: pd.Series(dict([[vv, tdf[vv].tolist()] for vv in tdf if
                                    vv not in ['irisClass']])))
    flower_list = set(data_frame['irisClass'])
    for feature in data_frame_features:
        data = []
        fig, box_plotter = plt.subplots(figsize=(10, 6))
        box_plotter.yaxis.grid(True, linestyle='-', which='major',
                               color='lightgrey',
                               alpha=0.5)
        # Hide these grid behind plot objects
        box_plotter.set_axisbelow(True)
        box_plotter.set_xlabel('Distribution of flowers')
        box_plotter.set_ylabel('Length of features')
        box_plotter.set_title('Comparison of %s across flowers' % (feature))
        for flower in flower_list:
            data.append(grouped_data_frame[feature][flower])
        plt.figtext(0.8, 0.9,
                    '1 --> Iris-Versicolor\n2--> Iris-Virginica\n3--> '
                                                                'Iris-Setosa',
                    backgroundcolor='white', color='black', weight='roman',
                    size='medium')
        box_plotter.boxplot(data)
        plt.show()
Example #23
0
def i2pcontrol_stats(conn, output=''):
	things=[
		{'stat':'activepeers','xlab':'time','ylab':'total',},
		{'stat':'tunnelsparticipating','xlab':'time','ylab':'total',},
		{'stat':'decryptFail','xlab':'time','ylab':'total',},
		{'stat':'failedLookupRate','xlab':'time','ylab':'total',},
		{'stat':'streamtrend','xlab':'time','ylab':'total',},
		{'stat':'windowSizeAtCongestion','xlab':'time','ylab':'total',},
		#{'stat':'','xlab':'','ylab':'',}, # Template to add more.
		]

	tokens = query_db(conn, 'select owner,token from submitters;')
	for thing in things:
		combined=[]
		dfs=[]
		for token in tokens:
			q = 'select datetime(cast(((submitted)/({0})) as int)*{0}, "unixepoch") as sh, {1} from speeds where submitter="{2}" group by sh order by sh desc;'.format(interval, thing['stat'], token[1])
			df = pd.read_sql_query(q, conn)
			# unix -> human
			df['sh'] = pd.to_datetime(df['sh'], unit='s')
			dfs.append(df)

		# Reverse so it's put in left to right
		combined = reduce(lambda left,right: pd.merge(left,right,on='sh',how='outer'), dfs)
		combined.columns=['time'] + [i[0] for i in tokens]
		combined = combined.set_index('time')

		combined.head(num_intervals).plot(marker='o')
		plt.figtext(.1,.03,'{}\n{} UTC'.format(site,generation_time))
		plt.title(thing['stat'])
		plt.xlabel(thing['xlab'])
		plt.ylabel(thing['ylab'])
		plt.savefig('{}/{}.png'.format(output, thing['stat']))
		plt.close()
Example #24
0
def pie_graph(conn, query, output, title='', lower=0, log=False):
	labels = []
	sizes = []

	res = query_db(conn, query)
	# Sort so the graph doesn't look like complete shit.
	res = sorted(res, key=lambda tup: tup[1])
	for row in res:
		if row[1] > lower:
			labels.append(row[0])
			if log:
				sizes.append(math.log(row[1]))
			else:
				sizes.append(row[1])
	# Normalize.
	norm = [float(i)/sum(sizes) for i in sizes]

	plt.pie(norm,
			labels=labels,
			shadow=True,
			startangle=90,
	)
	plt.figtext(.1,.03,'{}\n{} UTC'.format(site,generation_time))
	plt.axis('equal')
	plt.legend()
	plt.title(title)
	plt.savefig(output)
	plt.close()
    def plot_multiline(data_list, legend_list, picture_title, picture_save_path, text=None):
        """ Draw data series info """

        # plot file and save picture
        fig = plt.figure(figsize=(15, 6))

        plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        plt.gca().xaxis.set_major_locator(mdates.YearLocator())
        if text is not None:
            plt.figtext(0.01, 0.01, text, horizontalalignment='left')

        date_series = data_list[0].index

        color_list = ['r-', 'b-', 'y-', 'g-']

        for i, data_series in enumerate(data_list):
            # get data series info
            plt.plot(date_series, data_series, color_list[i], label=legend_list[i])

        min_date = date_series[0]
        max_date = date_series[-1]
        plt.gca().set_xlim(min_date, max_date)
        plt.legend(loc=0)
        fig.autofmt_xdate()
        fig.suptitle(picture_title)

        # print dir(fig)
        fig.savefig(picture_save_path)
        plt.close()
Example #26
0
def show_spider(p):
    L = Logging('log')
    data = L.get_stacked_bar_data('Template', p, 'spider')

    N = 12
    theta = radar_factory(N, frame='polygon')

    spoke_labels = data.pop('column names')

    fig = plt.figure(figsize=(7, 7))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)

    colors = ['r', 'g', 'b', 'm', 'y']
    # Plot the four cases from the example data on separate axes
    for n, title in enumerate(data.keys()):
        ax = fig.add_subplot(1, 1, n + 1, projection='radar')
        # plt.rgrids([0.5, 1.0, 1.5, 2.0, 2.5, 3.0])
        ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
                     horizontalalignment='center', verticalalignment='center')
        for d, color in zip(data[title], colors):
            ax.plot(theta, d, color=color)
            ax.fill(theta, d, facecolor=color, alpha=0.25)
        ax.set_varlabels(spoke_labels)

    # add legend relative to top-left plot
    plt.subplot(1, 1, 1)
    labels = ('Losers', 'Winners')
    legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1)
    plt.setp(legend.get_texts(), fontsize='small')

    plt.figtext(0.5, 0.965, 'Winner vs Losers',
                ha='center', color='black', weight='bold', size='large')
    plt.show()
def execute(model, data, savepath, *args, **kwargs):

    descriptors = ['Cu (At%)', 'Ni (At%)', 'Mn (At%)', 'P (At%)', 'Si (At%)', 'C (At%)', 'Temp (C)', 'log(fluence)',
                   'log(flux)']
    xlist = np.asarray(data.get_data(descriptors))

    model = model
    model.fit(data.get_x_data(), np.array(data.get_y_data()).ravel())
    error = model.predict(data.get_x_data()) - np.array(data.get_y_data()).ravel()

    for x in range(len(descriptors)):
        plt.scatter(xlist[:, x], error, color='black', s=10)
        xlim = plt.gca().get_xlim()
        plt.plot(xlim, (20, 20), ls="--", c=".3")
        plt.plot(xlim, (0, 0), ls="--", c=".3")
        plt.plot(xlim, (-20, -20), ls="--", c=".3")
        m, b = np.polyfit(np.reshape(xlist[:, x], len(xlist[:, x])), np.reshape(error, len(error)),1)  # line of best fit

        matplotlib.rcParams.update({'font.size': 15})
        plt.plot(xlist[:, x], m * xlist[:, x] + b, color='red')
        plt.figtext(.15, .83, 'y = ' + "{0:.6f}".format(m) + 'x + ' + "{0:.5f}".format(b), fontsize=14)
        plt.title('Error vs. {}'.format(descriptors[x]))
        plt.xlabel(descriptors[x])
        plt.ylabel('Predicted - Actual (Mpa)')
        plt.savefig(savepath.format(plt.gca().get_title()), dpi=200, bbox_inches='tight')
        plt.close()
def plotta(im,xx,yy,ext):
	#make plot
	f = ap.FITSFigure(im,figure=fig,subplot=[xx,yy-dy,dx,dy])


	f.show_colorscale(cmap = 'hot', vmin = -1.245E-02, vmax  = 2.405E-02 )
	f.recenter(ra, dec, re_cen)

	#if ext == 'E':
	f.show_ellipses(ra, dec, a/60.0, b/60.0, angle=pa-90, edgecolor='grey', lw=2)

	#if ext == 'P':
		#f.show_markers(ra, dec, c='grey',marker='x')

	#f.add_scalebar(1.0/60.0)
	f.scalebar.set_label('1 arcmin')
	#f.scalebar.set_color('white')

	#f.show_grid()
	#f.set_tick_labels_format(xformat='hh:mm:ss',yformat='dd:mm:ss')
	#f.show_markers(ra, dec, c='red',marker='x')
	#f.add_beam(major=beam, minor=beam,angle=0.0)
	f.show_beam(major=beam, minor=beam,angle=0.0,fc='white')
	f.axis_labels.hide()
	f.tick_labels.hide()

	# add text 
	plt.figtext(xx+0.012 , yy-dy+0.14, name, size=20, weight="bold", color='white')
def plot_results(datas, factor=None, algo='FFT'):
    xlabel = r'Array Size (2^x)'
    ylabel = 'Speed (GFLOPs)'
    backends = ['numpy', 'numpy+mkl']

    plt.clf()
    fig1, ax1 = plt.subplots()
    plt.figtext(0.90, 0.94, "Note: higher is better", va='top', ha='right')
    w, h = fig1.get_size_inches()
    fig1.set_size_inches(w*1.5, h)
    ax1.get_xaxis().set_major_formatter(ticker.ScalarFormatter())
    ax1.get_xaxis().set_minor_locator(ticker.NullLocator())
    ax1.set_xticks(datas[0][:,0])
    ax1.grid(color="lightgrey", linestyle="--", linewidth=1, alpha=0.5)
    if factor:
        ax1.set_xticklabels([str(int(x)) for x in datas[0][:,0]/factor])
    plt.xlabel(xlabel, fontsize=16)
    plt.ylabel(ylabel, fontsize=16)
    plt.xlim(datas[0][0,0]*.9, datas[0][-1,0]*1.025)
    plt.suptitle("%s Performance" % ("FFT"), fontsize=28)

    for backend, data in zip(backends, datas):
        N = data[:, 0]
        plt.plot(N, data[:, 1], 'o-', linewidth=2, markersize=5, label=backend)
        plt.legend(loc='upper left', fontsize=18)

    plt.savefig(algo + '.png')
Example #30
0
	def DBLR_f(self):

		global a

		#if (self.graph_sw.get()==True):
		b=a
		a=a+1
		#else:
		#	b=0

		aux=self.base_path.get()
#		path=''.join([aux,str(self.meas.get()),'.txt'])
#		g=pd.read_csv(path)
		f=read_panel_hdf5(aux, self.point.get(), self.meas.get())
		f=4096-f

		recons,energia = DB.BLR( signal_daq=f.flatten().astype(float),
						  coef=self.coef.get(),
						  n_sigma=self.n_sigma.get(),
						  NOISE_ADC=self.noise.get(),
						  thr1=self.thr1.get(),
						  thr2=self.thr2.get(),
						  thr3=self.thr3.get(),
						  plot=False)
		plt.figure(a)
		plt.plot(recons)
		plt.figtext(0.2,0.75, ('ENERGY = %0.2f ' % (energia)))
		plt.show()
Example #31
0
def test_type42_font_without_prep():
    # Test whether Type 42 fonts without prep table are properly embedded
    mpl.rcParams["ps.fonttype"] = 42
    mpl.rcParams["mathtext.fontset"] = "stix"

    plt.figtext(0.5, 0.5, "Mass $m$")
Example #32
0
def plot_1d(xdata,
            ydata,
            color,
            x_axis,
            y_axis,
            system,
            analysis,
            average=False,
            t0=0,
            marker_style=None,
            **kwargs):
    """ Creates a 1D scatter/line plot:

	Usage: plot_1d(xdata, ydata, color, x_axis, y_axis, system, analysis, average = [False|True], t0 = 0)
	
	Arguments:
	xdata, ydata: self-explanatory
	color: color to be used to plot data
	x_axis, y_axis: strings to be used for the axis label
	system: descriptor for the system that produced the data
	analysis: descriptor for the analysis that produced the data
	average: [False|True]; Default is False; if set to True, the function will calc the average, standard dev, and standard dev of mean of the y-data	# THERE IS A BUG IF average=True; must read in yunits for this function to work at the moment.
	t0: index to begin averaging from; Default is 0
	marker_style: default None; string that matches the desired marker style 
	
	kwargs:
		xunits, yunits: string with correct math text describing the units for the x/y data
		x_lim, y_lim: list w/ two elements, setting the limits of the x/y ranges of plot
		plt_title: string to be added as the plot title
		draw_line: int value that determines the line style to be drawn; giving myself space to add more line styles if I decide I need them

	"""
    # INITIATING THE PLOT...
    plt.plot(xdata, ydata, '%s' % (color), marker=marker_style)

    # READING IN KWARG DICTIONARY INTO SPECIFIC VARIABLES
    for name, value in kwargs.items():
        if name == 'xunits':
            x_units = value
            x_axis = '%s (%s)' % (x_axis, value)
        elif name == 'yunits':
            y_units = value
            y_axis = '%s (%s)' % (y_axis, value)
        elif name == 'x_lim':
            plt.xlim(value)
        elif name == 'y_lim':
            plt.ylim(value)
        elif name == 'plt_title':
            plt.title(r'%s' % (value), size='14')
        elif name == 'draw_line':
            draw_line = value
            if draw_line == 1:
                plt.plot([0, max(ydata)], [0, max(ydata)], 'r-', linewidth=2)
            else:
                print 'draw_line = %s has not been defined in plotting_functions script' % (
                    line_value)

    plt.grid(b=True,
             which='major',
             axis='both',
             color='#808080',
             linestyle='--')
    plt.xlabel(r'%s' % (x_axis), size=12)
    plt.ylabel(r'%s' % (y_axis), size=12)

    # CALCULATING THE AVERAGE/SD/SDOM OF THE Y-DATA
    if average != False:
        avg = np.sum(ydata[t0:]) / len(ydata[t0:])
        SD = stdev(ydata[t0:])
        SDOM = SD / sqrt(len(ydata[t0:]))

        plt.axhline(avg, xmin=0.0, xmax=1.0, c='r')
        plt.figtext(0.680,
                    0.780,
                    '%s\n%6.4f $\\pm$ %6.4f %s \nSD = %4.3f %s' %
                    (analysis, avg, SDOM, y_units, SD, y_units),
                    bbox=dict(boxstyle='square', ec='r', fc='w'),
                    fontsize=12)

    plt.savefig('%s.%s.plot1d.png' % (system, analysis), dpi=300)
    plt.close()
Example #33
0
def plot_ROC_curve(network_output, y_true, identifier, meta=''):
    from sklearn.metrics import roc_curve, auc
    import matplotlib.pyplot as plt
    import seaborn as sns

    # Compute ROC curve, integrate
    y_pred = network_output
    fpr, tpr, thresholds = roc_curve(y_true, y_pred)
    roc_auc = auc(fpr, tpr)

    print('AUC: {}'.format(roc_auc))
    plt.figure()
    plt.axes([.1, .1, .8, .75])
    plt.figtext(.5,
                .95,
                r'Receiver Operating Characteristic',
                fontsize=15,
                ha='center')
    plt.figtext(.5, .9, meta, fontsize=10, ha='center')
    plt.plot(fpr,
             tpr,
             color='darkorange',
             lw=2,
             label='ROC (area = %0.3f)' % roc_auc)
    plt.plot([0, 1], [0, 1], color='navy', lw=1.0, linestyle='--')
    plt.xlim([-0.05, 1.05])
    plt.ylim([-0.05, 1.05])
    plt.xlabel(r'False Positive Rate')
    plt.ylabel(r'True Positive Rate')
    plt.legend(loc="lower right")
    plt.savefig(os.path.join('graphs',
                             'val_{}'.format(identifier) + 'ROC.pdf'),
                format='pdf',
                dpi=1000)
    plt.show()
    plt.gcf().clear()

    print('Plotting signal efficiency versus background rejection')
    plt.figure()
    plt.axes([.1, .1, .8, .75])
    plt.figtext(.5,
                .95,
                r'Signal Efficiency v. Background Rejection',
                fontsize=15,
                ha='center')
    plt.figtext(.5, .9, meta, fontsize=10, ha='center')
    plt.plot(tpr,
             1 - fpr,
             color='springgreen',
             lw=2,
             label='ROC (area = %0.3f)' % roc_auc)
    plt.xlim([-0.05, 1.05])
    plt.ylim([-0.05, 1.05])
    plt.xlabel(r'$\epsilon_S$')
    plt.ylabel(r'$1-\epsilon_B$')
    plt.legend(loc="upper right")
    plt.savefig(os.path.join('graphs',
                             'val_{}'.format(identifier) + 'SEvBR.pdf'),
                format='pdf',
                dpi=1000)
    plt.show()
    plt.gcf().clear()
Example #34
0
def sci_plots(etable, gtitable, args):
    #GRID SET UP
    figure2 = plt.figure(figsize = (11, 8.5), facecolor = 'white')
    sci_grid = gridspec.GridSpec(5,7)

    # Build PHA Fast/Slow ratio plot before filtering by ratio
    # Only do this if powerspectrum not requested

    if not args.powspec:
        log.info('Building fast/slow subplot')
        plt.subplot(sci_grid[1:3,2:5])
        plot_slowfast(etable,args)

    # Now, filter out the points above the ratio cut, if requested
    if args.filtratio:
        log.info('Applying ratio filter using trumpet')
        etable = filt_ratio_trumpet(etable)

    #Light Curve
    log.info('Building light curve')
    plt.subplot(sci_grid[3:5,:7])
    meanrate, a = plot_light_curve(etable, args.lclog, gtitable, binsize=args.lcbinsize)
    plot.title('Light Curve')
    plot.xlabel('Time Elapsed (s)')

    #Energy Spectrum
    log.info('Building energy spectrum')
    plt.subplot(sci_grid[1:3,:2])
    plot_energy_spec(etable)

    #Power Spectrum
    if args.powspec:
        log.info('Looking at power spectrum')
        plt.subplot(sci_grid[1:3,2:5])
        # plot_fft_of_power(etable, args.nyquist, args.pslog, args.writeps)

    # PULSE PROFILE
    log.info('Building pulse profile')
    axprofile = plt.subplot(sci_grid[1:3,5:7])
    if (args.orb is not None) and (args.par is not None):
        log.info('Calling pulse profile using PINT')
        pulse_profile(axprofile, etable, args)
    elif args.foldfreq > 0.0:
        log.info('Calling pulse profile with fixed frequency')
        pulse_profile_fixed(etable, args.foldfreq)
    else:
        pass

    #Making the plot all nice and stuff
    plt.subplots_adjust(left = .07, right = .99, bottom = .05, top = .9, wspace = .8, hspace = .8)

    figure2.suptitle('ObsID {0}: {1} on {2}'.format(etable.meta['OBS_ID'],
            etable.meta['OBJECT'],etable.meta['DATE-OBS'].replace('T',' at ')),
            fontsize=14)

    #tstart, tstop, exposure
    exposure = float(etable.meta['EXPOSURE'])
    #tstart = etable.meta['DATE-OBS'].replace('T',' at ')
    #tend = etable.meta['DATE-END'].replace('T', ' at ')
    tstart = TimeDelta(etable.meta['TSTART'], format='sec',scale='tt')+Time(etable.meta['MJDREFI']+etable.meta['MJDREFF'], format='mjd',scale='tt')
    tend = TimeDelta(etable.meta['TSTOP'], format='sec',scale='tt')+Time(etable.meta['MJDREFI']+etable.meta['MJDREFF'], format='mjd',scale='tt')
    fraction = exposure/(float(etable.meta['TSTOP'])-float(etable.meta['TSTART']))

    # Add text info here:
    plt.figtext(.07, .93, 'Start time is {0}, End time is {1}'.format(tstart.iso,tend.iso), fontsize = 10)
    plt.figtext(.07, .90, 'Exposure is {0:.1f} s, Good time fraction is {1:.3f}'.format(exposure, fraction),
        fontsize = 10)
    plt.figtext(.07, .87, 'Mean count rate {0:.3f} c/s'.format(meanrate), fontsize = 10)
   # plt.figtext(.07, .84, etable.meta['FILT_STR'], fontsize=10)
    if args.mask:
        plt.figtext(.07, .81, 'IDS {0} are masked'.format(args.mask), fontsize=10)
    plt.figtext(.5, .77, str(gtitable['START'][:]), fontsize =9)
    plt.figtext(.58, .77, str(gtitable['STOP'][:]), fontsize =9)
    plt.figtext(.66, .77, str(gtitable['DURATION'][:]), fontsize =9)

    return figure2
                 weight="bold",
                 position=(0.5, 1.1),
                 horizontalalignment="center",
                 verticalalignment="center",
                 fontsize=13.)
    for d, color in zip(case_data, colors):
        ax.plot(theta, d, color=color)
        ax.fill(theta, d, facecolor=color, alpha=0.5)
    ax.set_varlabels(spoke_labels)
plt.subplot(2, 2, 1)
labels = kings
legend = plt.legend(labels, loc=(.95, .95), labelspacing=0.1)
plt.setp(legend.get_texts(), fontsize="large")
plt.figtext(0.5,
            0.965,
            "Types of Battles Fought By Kings as Attacker/Defender",
            ha="center",
            color="k",
            size=16.)
plt.show()
death_preds = character_predictions.copy(deep=True)
from xgboost import plot_importance
from xgboost import XGBClassifier as XGBC
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, roc_curve, log_loss, confusion_matrix, precision_score, recall_score, classification_report, accuracy_score
death_preds.loc[:, "culture"] = [
    get_cult(x) for x in death_preds.culture.fillna("")
]
death_preds.loc[:, "title"] = pd.factorize(death_preds.title)[0]
death_preds.loc[:, "culture"] = pd.factorize(death_preds.culture)[0]
death_preds.loc[:, "mother"] = pd.factorize(death_preds.mother)[0]
death_preds.loc[:, "father"] = pd.factorize(death_preds.father)[0]
def view_sample(sample_id,
                all_samples,
                before=0.15,
                after=0.05,
                show_plot=True,
                save_plot=None):

    # Select the sample (i.e., the row from the data frame of samples)
    try:
        sample = all_samples.loc[sample_id]
    except KeyError:
        raise KeyError('Given sample_id is too big! Maximum value = {}'.format(
            len(all_samples) - 1))

    # Check if the sample we have received contains an injection or not
    if 'h1_signal' in sample.keys():
        has_injection = isinstance(sample['h1_signal'], np.ndarray)
    else:
        has_injection = False

    # Read out and construct some necessary values for plotting

    seconds_before_event = float(sample['seconds_before_event'])
    seconds_after_event = float(sample['seconds_after_event'])
    #  seconds_after_event = 2.0 - seconds_before_event
    target_sampling_rate = float(sample['target_sampling_rate'])
    sample_length = float(sample['sample_length'])
    #  sample_length = 2.0

    # Create a grid on which the sample can be plotted so that the
    # `event_time` is at position 0
    grid = np.linspace(0 - seconds_before_event, 0 + seconds_after_event,
                       int(target_sampling_rate * sample_length))

    # Create subplots for H1 and L1
    fig, axes1 = plt.subplots(nrows=2)

    # If the sample has an injection, we need a second y-axis to plot the
    # (unwhitened) detector signals
    if has_injection:
        axes2 = [ax.twinx() for ax in axes1]
    else:
        axes2 = None

    # Plot the strains for H1, L1 and V1
    max_strain = max(np.max(sample['h1_strain']), np.max(sample['l1_strain']))
    for i, (det_name, det_string) in enumerate([('H1', 'h1_strain'),
                                                ('L1', 'l1_strain')]):

        axes1[i].plot(grid, sample[det_string] / max_strain, color='C0')
        axes1[i].set_xlim(-before, after)
        axes1[i].set_ylim(-150, 150)
        axes1[i].tick_params('y', colors='C0', labelsize=8)
        axes1[i].set_ylabel(
            'Amplitude of Whitened Strain ({})'.format(det_name),
            color='C0',
            fontsize=8)

    # If applicable, also plot the detector signals for H1 and L1
    if has_injection:

        # Get the maximum value of the detector signal (for norming them)
        maximum = max(np.max(sample['h1_signal']), np.max(sample['l1_signal']))
        print('Maximum=', maximum)

        for i, (det_name, det_string) in enumerate([('H1', 'h1_signal'),
                                                    ('L1', 'l1_signal')]):
            axes1[i].plot(grid, sample[det_string] / maximum, color='C1')

            #            axes2[i].plot(grid, sample[det_string], color='C1')
            #            axes1[i].set_xlim(-before, after)
            axes1[i].set_xlim(-seconds_before_event, seconds_after_event)
            axes1[i].set_ylim(-1.2, 1.2)
            axes1[i].tick_params('y', colors='C1', labelsize=8)
            axes1[i].set_ylabel('Amplitude of Simulated\n'
                                'Detector Signal ({})'.format(det_name),
                                color='C1',
                                fontsize=8)
#            axes2[i].set_ylabel('Amplitude of Simulated\n'
#                                'Detector Signal ({})'.format(det_name),
#                                color='C1', fontsize=8)

# Also add the injection parameters
    if has_injection:
        keys = ('mass1', 'mass2', 'spin1z', 'spin2z', 'ra', 'dec', 'coa_phase',
                'inclination', 'polarization', 'injection_snr')
        string = ', '.join(
            ['{} = {:.2f}'.format(_, float(sample[_])) for _ in keys])
    else:
        string = '(sample does not contain an injection)'
    plt.figtext(0.5,
                0.9,
                'Injection Parameters:\n' + string,
                fontsize=8,
                ha='center')

    # Add a vertical line at the position of the event (x=0)
    axes1[0].axvline(x=0, color='black', ls='--', lw=1)
    axes1[1].axvline(x=0, color='black', ls='--', lw=1)

    # Set x-labels
    #    axes1[2].set_xticklabels([])
    axes1[1].set_xlabel('Time from `event_time` (in seconds)')

    # Adjust the size and spacing of the subplots
    plt.gcf().set_size_inches(12, 6, forward=True)
    plt.tight_layout(rect=[0, 0, 1, 0.9])
    plt.subplots_adjust(wspace=0, hspace=0.3)

    # Add a title
    plt.suptitle('Sample #{}'.format(sample_id), y=0.975)

    # If desired, save the resulting plot
    if save_plot is not None:
        plt.savefig(save_plot)

    # If desired, show the resulting plot
    if show_plot:
        plt.show()
"""
  Name     : c15_10_volatility_smile_put.py
  Book     : Python for Finance (2nd ed.)
  Publisher: Packt Publishing Ltd. 
  Author   : Yuxing Yan
  Date     : 6/6/2017
  email    : [email protected]
             [email protected]
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
infile = "c:/temp/puts17march.txt"
data = pd.read_table(infile, skiprows=1)
x = data['Strike']
y0 = list(data['Implied Volatility'])
n = len(y0)
y = []
for i in np.arange(n):
    a = float(y0[i].replace("%", "")) / 100.
    y.append(a)
    print(a)
#
plt.title("Volatility smile")
plt.figtext(0.55, 0.80, "IBM puts")
plt.figtext(0.55, 0.75, "maturity: 3/17/2017")
plt.ylabel("Volatility")
plt.xlabel("Strike Price")
plt.plot(x, y, 'o')
plt.show()
Example #38
0
plt.axis('tight')
if int(dates[1][4:6]) > 10 or int(dates[2][4:6]) < 4:
    plt.xlim(2.5,4.0)
else:
    plt.xlim(2.2,3.4)
plt.ylim(levbot,levtop)
plt.grid(True)

plt.subplot(1,2,2)
temp_fits1mean = np.sqrt(temp_fits1).mean(axis=0)
temp_fits2mean = np.sqrt(temp_fits2).mean(axis=0) 
temp_fits_pval = ttest(temp_fits1,temp_fits2,inflate=True)
sig = temp_fits_pval >= sigthresh
plt.plot(temp_fits1mean,levels,color=color1,linewidth=linewidth1,marker='o',label=expt1)
plt.plot(temp_fits2mean,levels,color=color2,linewidth=linewidth2,marker='o',label=expt2)
for n in range(len(levels)):
    if sig[n]:
        plt.axhspan(levels_up[n], levels_down[n], facecolor='lightgoldenrodyellow')
plt.xlabel('RMS (K)')
plt.title('%s: %s' % (obtypes+' T',region))
plt.axis('tight')
plt.xlim(0.5,1.4)
plt.ylim(levbot,levtop)
plt.grid(True)
plt.legend(loc=0)

plt.figtext(0.5,0.93,'%s RMS O-F (%s)' % (title,dates_txt),horizontalalignment='center',fontsize=18)
plt.savefig('obfits_%s_%s_%s.png' % (expt1,expt2,region))

plt.show()
Example #39
0
def hist1d(data,
           x_axis,
           system,
           analysis,
           num_b=100,
           norm=False,
           average=False,
           t0=0,
           **kwargs):
    """ Creates a 1D histogram:

	Usage: hist1d(data, x_axis, num_b, system, analysis, norm)
	
	Arguments:
	data: self-explanatory
	x_axis: string to be used for the axis label
	system: descriptor for the system analyzed
	analysis: descriptor for the analysis performed and plotted
	num_b: number of bins to be used when binning the data; Default is 100
	norm = [False][True]; Default is False; if False, plotting a frequency of data; if True, plotting a probability density
	average: [False|True]; Default is False; if set to True, the function will calc the average, standard dev, and standard dev of mean of the y-data
	t0: index to begin averaging from; Default is 0

	kwargs:
		xunits: string with correct math text describing the units for the x data
		x_lim, y_lim: list w/ two elements, setting the limits of the x/y ranges of plot
		plt_title: string to be added as the plot title

	"""

    # INITIATING THE PLOT...
    events, edges, patches = plt.hist(data,
                                      bins=num_b,
                                      histtype='bar',
                                      normed=norm)

    # READING IN KWARG DICTIONARY INTO SPECIFIC VARIABLES
    for name, value in kwargs.items():
        if name == 'xunits':
            x_units = value
            x_axis = '%s (%s)' % (x_axis, value)
        elif name == 'x_lim':
            plt.xlim(value)
        elif name == 'y_lim':
            plt.ylim(value)
        elif name == 'plt_title':
            plt.title(r'%s' % (value), size='14')

    plt.grid(b=True,
             which='major',
             axis='both',
             color='#808080',
             linestyle='--')
    plt.xlabel(r'%s' % (x_axis), size=12)

    # CALCULATING THE AVERAGE/SD/SDOM OF THE Y-DATA
    if average != False:
        avg = np.sum(data[t0:]) / len(data[t0:])
        SD = stdev(data[t0:])
        SDOM = SD / sqrt(len(data[t0:]))

        plt.axvline(avg, ymin=0.0, ymax=1.0, c='r')
        plt.figtext(0.680,
                    0.780,
                    '%s\n%6.4f $\\pm$ %6.4f %s \nSD = %4.3f %s' %
                    (analysis, avg, SDOM, x_units, SD, x_units),
                    bbox=dict(boxstyle='square', ec='r', fc='w'),
                    fontsize=12)

    if norm == True:
        plt.ylabel('Probability Density')
        plt.savefig('%s.%s.prob1d.png' % (system, analysis), dpi=300)
        nf = open('%s.%s.prob1d.dat' % (system, analysis), 'w')
    else:
        plt.ylabel('Frequency', size=12)
        plt.savefig('%s.%s.hist1d.png' % (system, analysis), dpi=300)
        nf = open('%s.%s.hist1d.dat' % (system, analysis), 'w')

    for i in range(len(events)):
        nf.write('%10.1f      %10.4f\n' % (events[i], edges[i]))

    plt.close()
    nf.close()
    events = []
    edges = []
    patches = []
Example #40
0
def scat_hist(xdata,
              ydata,
              color,
              x_axis,
              y_axis,
              system,
              analysis,
              num_b=100,
              average=False,
              t0=0,
              **kwargs):
    """ Creates 1D scatter plot w/ a 1D histogram

	Usage: scat_hist(xdata, ydata, color, x_axis, y_axis, system, analysis, num_b)
	
	Arguments:
	xdata, ydata: self-explanatory
	color: color to be used to plot data
	x_axis, y_axis: strings to be printed on the axi labels
	system: descriptor for the system analyzed
	analysis: descriptor for the analysis performed and plotted
	num_b: number of bins to be used when binning the data; Default is 100
	average: [False|True]; Default is False; if set to True, the function will calc the average, standard dev, and standard dev of mean of the y-data	# THERE IS A BUG; if average = True, need to read in xunits for this function to work...
	t0: index to begin averaging from; Default is 0
	
	kwargs:
		xunits, yunits: string with correct math text describing the units for the x/y data
		x_lim, y_lim: list w/ two elements, setting the limits of the x/y ranges of plot
		plt_title: string to be added as the plot title

	"""
    # INITIATING THE PLOT SIZES
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.8
    bottom_h = left_h = left + width + 0.01
    rect_scatter = [left, bottom, width, height]
    rect_histy = [left_h, bottom, 0.2, height]

    # INITIATING THE PLOT...
    plt.figure(1, figsize=(10, 8))
    axScatter = plt.axes(rect_scatter)
    axScatter.plot(xdata, ydata, '%s.' % (color))

    # READING IN KWARG DICTIONARY INTO SPECIFIC VARIABLES
    for name, value in kwargs.items():
        if name == 'xunits':
            x_units = value
            x_axis = '%s (%s)' % (x_axis, value)
        elif name == 'yunits':
            y_units = value
            y_axis = '%s (%s)' % (y_axis, value)
        elif name == 'x_lim':
            plt.xlim(value)
        elif name == 'y_lim':
            plt.ylim(value)
        elif name == 'plt_title':
            plt.title(r'%s' % (value), size='14')

    plt.grid(b=True,
             which='major',
             axis='both',
             color='#808080',
             linestyle='--')
    plt.ylabel(r'%s' % (y_axis), size=20)
    plt.xlabel(r'%s' % (x_axis), size=20)
    axScatter.tick_params(axis='both', which='major', labelsize=14)

    if average != False:
        avg = np.sum(ydata[t0:]) / len(ydata[t0:])
        SD = stdev(ydata[t0:])
        SDOM = SD / sqrt(len(ydata[t0:]))
        plt.axhline(avg, xmin=0.0, xmax=1.0, c='r')

    axHisty = plt.axes(rect_histy)
    axHisty.yaxis.set_major_formatter(nullfmt)
    axHisty.xaxis.set_major_formatter(nullfmt)
    plt.grid(b=True,
             which='major',
             axis='both',
             color='#808080',
             linestyle='--')
    axHisty.hist(ydata,
                 bins=num_b,
                 orientation='horizontal',
                 facecolor='grey',
                 edgecolor='black')
    axHisty.set_ylim(axScatter.get_ylim())

    # CALCULATING THE AVERAGE/SD/SDOM OF THE Y-DATA
    if average != False:
        plt.axhline(avg, xmin=0.0, xmax=1.0, c='r')
        plt.figtext(0.775,
                    0.810,
                    '%s\n%6.4f $\\pm$ %6.4f %s \nSD = %4.3f %s' %
                    (analysis, avg, SDOM, y_units, SD, y_units),
                    bbox=dict(boxstyle='square', ec='r', fc='w'),
                    fontsize=12)

    plt.savefig('%s.%s.scat_hist.png' % (system, analysis), dpi=300)
    plt.close()
Example #41
0
    theta = radar_factory(N, frame='polygon')

    data = example_data()
    spoke_labels = data.pop('column names')

    fig = plt.figure(figsize=(9, 9))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)

    colors = ['b', 'r', 'g', 'm', 'y']
    # Plot the four cases from the example data on separate axes
    for n, title in enumerate(data.keys()):
        ax = fig.add_subplot(2, 2, n + 1, projection='radar')
        plt.rgrids([0.2, 0.4, 0.6, 0.8])
        ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
                     horizontalalignment='center', verticalalignment='center')
        for d, color in zip(data[title], colors):
            print(d)
            ax.plot(theta, d, color=color)
            ax.fill(theta, d, facecolor=color, alpha=0.25)
        ax.set_varlabels(spoke_labels)

    # add legend relative to top-left plot
    plt.subplot(2, 2, 1)
    labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')
    legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1)
    plt.setp(legend.get_texts(), fontsize='small')

    plt.figtext(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',
                ha='center', color='black', weight='bold', size='large')
    plt.show()
        pyplot.plot(TestData.index, TestData['GWL'], 'b', label ="observed")
        pyplot.title("CNN - Forecast 3 Months seq2seq: "+Well_ID, size=15)
        pyplot.ylabel('GWL [m asl]', size=12)
        pyplot.xlabel('Date',size=12)
        pyplot.legend(fontsize=12,bbox_to_anchor=(1.2, 1),loc='upper right')
        pyplot.tight_layout()

        s = """NSE = {:.2f}\nR²  = {:.2f}\nRMSE = {:.2f}\nrRMSE = {:.2f}
Bias = {:.2f}\nrBias = {:.2f}\nPI = {:.2f}\n\nfilters = {:d}\ndense-size = {:d}\nin_seqlength = {:d}
out_seqlength = {:d}\nbatchsize = {:d}\nrH = {:d}\nT = {:d}\nTsin = {:d}""".format(scores.NSE[0],scores.R2[0],
        scores.RMSE[0],scores.rRMSE[0],scores.Bias[0],scores.rBias[0],scores.PI[0],
        filters_int, densesize_int,seqlength_int,12,batchsize_int,rH,T,Tsin)

        # pyplot.figtext(0.865, 0.18, s, bbox=dict(facecolor='white'))
        pyplot.figtext(0.856, 0.4, s, bbox=dict(facecolor='white'))
        pyplot.savefig(Well_ID+'_testset_CNN_seq2seq.png', dpi=300)
        pyplot.show()
        
        # print log summary file
        f = open('./log_summary_CNN_seq2seq_'+Well_ID+'.txt', "w")
        print("\nBEST:\n\n"+s+"\n", file = f)
        print("best iteration = {}".format(step+1), file = f)
        print("max iteration = {}\n".format(len(optimizer.res)), file = f)
        for i, res in enumerate(optimizer.res):
            print("Iteration {}: \t{}".format(i+1, res), file = f) 
        f.close()
        
        #print sim data
        for i in range(inimax):
            printdf = pd.DataFrame(data=testresults_members[:,:,i],index=TestData.index)
Example #43
0
def main(session: str,
         dims: int = 32,
         pooling: str = 'stride',
         batch_size: int = 16,
         epochs: int = 75,
         normalization: str = 'batch',
         v_normalization: str = 'global',
         weights=None,
         workers: int = 1,
         l2: float = 0.01,
         kernel_initializer: str = 'glorot_uniform',
         random_seed: int = None,
         cmd='train',
         paper_mode: int = 0):
    assert os.access('.', os.W_OK | os.R_OK)

    if cmd != 'salience':
        tf.compat.v1.disable_eager_execution()

    if random_seed is not None:
        np.random.seed(random_seed)
        tf.random.set_seed(random_seed)
        random.seed(random_seed)

    gpus = tf.config.experimental.list_physical_devices('GPU')
    if gpus:
        try:
            # Currently, memory growth needs to be the same across GPUs
            for gpu in gpus:
                tf.config.experimental.set_memory_growth(gpu, True)
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus),
                  "Logical GPUs")
        except RuntimeError as e:
            # Memory growth must be set before GPUs have been initialized
            print(e)

    if l2 is not None:
        kernel_regularizer = l2r(l2)
    else:
        kernel_regularizer = None

    model, loss_fns, metrics = residual_model(
        dims=dims,
        pooling=pooling,
        kernel_regularizer=kernel_regularizer,
        kernel_initializer=kernel_initializer)

    if weights is not None:
        model.load_weights(weights, by_name=True)

    optimizer = SGD(lr=1e-4, momentum=0.9)

    model.compile(optimizer=optimizer, loss=loss_fns, metrics=metrics)

    try:
        os.mkdir('weights')
    except FileExistsError:
        assert os.access('weights', os.W_OK | os.R_OK)

    filepath = "weights/%s_epoch-{epoch:02d}_val_auc-{val_auc:.4f}.h5" % session
    checkpoint = ModelCheckpoint(filepath,
                                 monitor='val_auc',
                                 verbose=1,
                                 save_best_only=True,
                                 mode='max')

    def sched(epoch):
        return 1e-4 * 0.5**(np.floor(epoch / 15))

    reduce_lr = LearningRateScheduler(schedule=sched)

    try:
        os.mkdir('logs')
    except FileExistsError:
        assert os.access('logs', os.W_OK | os.R_OK)

    if os.path.exists('logs/%s' % session):
        assert os.access('logs/%s' % session, os.W_OK | os.R_OK)

    tensorboard = TensorBoard(log_dir='logs/%s' % session, profile_batch=0)

    if cmd == 'train':
        Xy = np.load('data/train.npy', mmap_mode='r')

        X_train = Xy[:, :, 1:11]
        y_train = Xy[:, :, 0]
        d_train = np.load('data/train_props.npy')
        d_train = np.piecewise(d_train, [
            d_train == 0,
            np.logical_and(0 < d_train, d_train <= 1 / 10), 1 / 10 < d_train
        ], [0.95, lambda x: 10 * x, 1])

        train_seq = SMBISequence(X=X_train,
                                 y=y_train,
                                 d=d_train,
                                 stage='train',
                                 batch_size=batch_size,
                                 normalization=normalization)

    X_test = np.swapaxes(np.load('data/test_inps.p', mmap_mode='r'), 1, 2)
    y_test = np.load('data/test_labels.p', mmap_mode='r')
    p_test = np.load('data/test_pids.p', mmap_mode='r')

    val_seq = SMBISequence(X=X_test,
                           y=y_test,
                           stage='test',
                           batch_size=batch_size,
                           normalization=v_normalization)

    validation_metrics = ValidationMetrics(seq=val_seq,
                                           batch_size=batch_size,
                                           seqlen=2000,
                                           n_feat=10)

    callbacks = [validation_metrics, checkpoint, reduce_lr, tensorboard]

    if cmd == 'train':
        model.fit_generator(
            train_seq,
            validation_data=val_seq,
            epochs=epochs,
            callbacks=callbacks,
            use_multiprocessing=True if workers != 1 else False,
            workers=workers,
            shuffle=True)

    if cmd == 'eval':
        if weights is not None:
            model.load_weights(weights)

        validation_metrics.model = model
        validation_metrics.on_epoch_end(0)

    if cmd == 'salience':
        import matplotlib.pyplot as plt
        import matplotlib.cm as cm

        val_seq_nonorm = SMBISequence(X=X_test,
                                      y=y_test,
                                      p=p_test,
                                      stage='test',
                                      batch_size=batch_size,
                                      normalization='none')

        gidx = 0

        onset = False
        onset_idx = 0

        for bidx in range(0, len(val_seq)):
            model_seq, model_cls, _ = val_seq.__getitem__(bidx)
            vis_input, _, _ = val_seq_nonorm.__getitem__(bidx)

            vis_seq = vis_input[0]
            vis_p = vis_input[1]

            for sidx in range(0, batch_size):
                input_seq = model_seq[sidx]
                input_seq_v = vis_seq[sidx]
                output_cls = model_cls[sidx][0]

                wrt = np.array([input_seq.astype(np.float32)])
                wrt_t = tf.constant(wrt)

                with tf.GradientTape() as g:

                    g.watch([wrt_t])
                    evaluated_cls = model([wrt_t])

                evaluated_gradients = np.abs(
                    g.gradient(evaluated_cls, [wrt_t])[0][0].numpy())
                evaluated_gradients_all = np.sum(evaluated_gradients, axis=-1)

                if bool(output_cls):
                    if not onset:
                        onset = True
                        onset_idx = 1999
                else:
                    if onset:
                        onset = False

                if paper_mode:
                    fig = plt.figure(figsize=(10, 5))
                    plt.title('Patient %d' % vis_p[sidx])
                else:
                    fig = plt.figure(figsize=(10, 5), facecolor='#808080')
                    plt.figtext(
                        0.01, 0.01,
                        'Model: Residual CNN\nCarroll Vance <*****@*****.**>'
                    )
                    plt.title(
                        'GTC seizure onset of slow activity prediction w/ saliency: Patient %d'
                        % vis_p[sidx])
                ax = fig.gca()

                t = np.array([i for i in range(0, 2000)])

                xlim = (0, 2000)
                ylim = (0, np.max(evaluated_gradients_all))

                vmin = ylim[0]
                vmax = ylim[1]

                for i in range(0, 10):
                    plt.plot(t, input_seq_v[:, i])
                ax.pcolorfast(xlim,
                              ax.get_ylim(),
                              evaluated_gradients_all[np.newaxis],
                              vmin=vmin,
                              vmax=vmax,
                              cmap='viridis')
                plt.grid()

                locs = [i * 200 for i in range(0, 11)]
                labels = ["%d" % (int(loc / 200)) for loc in locs]

                plt.legend([
                    'fp1-f7', 'f7-t7', 't7-p7', 'p7-o1', 'fp2-f8', 'f8-t8',
                    't8-p8', 'p8-o2', 'fz-cz', 'cz-pz'
                ],
                           fontsize='small',
                           loc='upper left')
                plt.xticks(locs, labels)
                plt.ylabel("Amplitude")
                plt.xlabel("Seconds")

                cb_pred = plt.colorbar(cm.ScalarMappable(cmap='viridis'),
                                       ticks=[0.0, 0.25, 0.5, 0.75, 1.0])

                if bool(np.round(evaluated_cls)) == bool(np.round(output_cls)):
                    textcolor = '#00EE00'
                    if bool(np.round(output_cls)):
                        outcome = 'TP'
                    else:
                        outcome = 'TN'
                else:
                    textcolor = 'red'
                    if bool(np.round(evaluated_cls)):
                        outcome = 'FP'
                    else:
                        outcome = 'FN'

                if onset:
                    cb_pred.ax.plot(0.5,
                                    evaluated_cls,
                                    '_',
                                    markersize=96,
                                    color='magenta',
                                    markeredgewidth=3)
                    cb_pred.ax.annotate("Positive", (0.5, 1.0),
                                        xytext=(-0.75, 1.02),
                                        color='red')
                else:
                    cb_pred.ax.plot(0.5,
                                    evaluated_cls,
                                    '_',
                                    markersize=96,
                                    color='magenta',
                                    markeredgewidth=3)
                    cb_pred.ax.annotate("Negative", (0.5, 0.0),
                                        xytext=(-0.75, -0.05),
                                        color='#00EE00')

                cb_pred.ax.set_ylabel('Prediction: %s' % outcome,
                                      color=textcolor)
                if onset:
                    plt.annotate("Onset", (onset_idx, 0),
                                 color='red',
                                 xytext=(onset_idx, np.max(input_seq_v)),
                                 arrowprops=dict(color='red',
                                                 width=1.,
                                                 headwidth=6.))
                    onset_idx -= 20

                if paper_mode:
                    plt.savefig('figs/%d.png' % gidx)
                else:
                    plt.savefig('figs/%d.png' % gidx, facecolor='#808080')

                plt.close('all')

                print(gidx)
                gidx += 1
for i in range(10):
    ax1[i].tick_params(
        axis='y',  # changes apply to the y-axis
        labelleft=False)

for i in range(10):
    ax2[i].tick_params(
        axis='y',  # changes apply to the y-axis
        labelleft=False)

for i in range(10):
    ax3[i].tick_params(
        axis='y',  # changes apply to the y-axis
        labelleft=False)

plt.figtext(0.02, 0.82, 'V (mV)', rotation=90, fontsize='large')
plt.figtext(0.005, 0.94, 'A', fontsize='xx-large')
plt.figtext(0.005, 0.5, 'B', fontsize='xx-large')
#plt.figtext(0.005,0.42,'C',fontsize = 'xx-large')
plt.figtext(0.005, 0.18, 'C', fontsize='xx-large')

#ax2[4].text(522,1025,r'$\mathsf{t_{1} }$',fontsize = 'x-large')
#ax2[4].text(535,1025,r'$\mathsf{t_{2} }$',fontsize = 'x-large')

plt.figtext(0.965, 0.97, r'$\mathsf{J_{gap} }$', fontsize='large')

ax11 = [ax1[4], ax2[4], ax3[4], ax3[9]]

S = [0.0, 0.05, 0.1, 1.0]

for ax0, s0 in zip(ax11, S):
Example #45
0
def plot_avg_both(real_data,
                  fake_data,
                  n_events,
                  epoch,
                  imageSize,
                  withMarginals=True,
                  save_dir=None):
    fig = plt.figure(figsize=(10, 5))
    xran = (-50, 50)
    yran = (-50, 50)
    extent = xran + yran

    #real_data = real_image
    img = real_data
    test_unnormed = fake_data
    test_noNans = np.copy(test_unnormed)
    img2 = np.squeeze(test_noNans)
    t = np.arange(-50, 50, 100 / float(imageSize))
    #t = np.arange(img.shape[0])
    f = np.arange(-50, 50, 100 / float(imageSize))
    #f = np.arange(img.shape[1])
    flim = (f.min(), f.max())
    tlim = (t.min(), t.max())

    gs = gridspec.GridSpec(2,
                           4,
                           width_ratios=[5, 1, 1, 5],
                           height_ratios=[1, 5])
    gs.update(hspace=0, wspace=0)
    ax1 = fig.add_subplot(gs[1, 0])
    axl = fig.add_subplot(gs[1, 1], sharey=ax1)
    axb = fig.add_subplot(gs[0, 0], sharex=ax1)
    ax2 = fig.add_subplot(gs[1, 3])
    axl2 = fig.add_subplot(gs[1, 2], sharey=ax2)
    axb2 = fig.add_subplot(gs[0, 3], sharex=ax2)
    plt.setp(axl.get_yticklabels(), visible=False)
    plt.setp(axb.get_xticklabels(), visible=False)
    plt.setp(axl.get_xticklabels(), visible=False)
    plt.setp(axb.get_yticklabels(), visible=False)
    plt.setp(axl2.get_yticklabels(), visible=False)
    plt.setp(axb2.get_xticklabels(), visible=False)
    plt.setp(axl2.get_xticklabels(), visible=False)
    plt.setp(axb2.get_yticklabels(), visible=False)
    axl.yaxis.set_ticks_position('none')
    axb.xaxis.set_ticks_position('none')
    axl.xaxis.set_ticks_position('none')
    axb.yaxis.set_ticks_position('none')
    axl2.yaxis.set_ticks_position('none')
    axb2.xaxis.set_ticks_position('none')
    axl2.xaxis.set_ticks_position('none')
    axb2.yaxis.set_ticks_position('none')
    cmap = sns.cubehelix_palette(dark=0.4,
                                 light=0.915,
                                 gamma=2.5,
                                 hue=1,
                                 start=0,
                                 as_cmap=True)
    im = ax1.imshow(real_data,
                    vmin=0,
                    extent=extent,
                    origin='lower',
                    cmap=cmap)
    ax1.spines["top"].set_visible(False)
    ax1.spines['right'].set_visible(False)
    #ax.spines['left'].set_visible(False)
    color_list = sns.cubehelix_palette(dark=0.4, light=0.915, gamma=2.5,
                                       hue=1).as_hex()
    axl.fill_between(img.mean(1), f, alpha=0.7, color=color_list[1])
    axl.spines["top"].set_visible(False)
    axl.spines['right'].set_visible(False)
    axl.spines['left'].set_visible(False)
    axl.spines['bottom'].set_visible(False)
    axb.fill_between(t, img.mean(0), alpha=0.7, color=color_list[1])
    axb.spines["top"].set_visible(False)
    axb.spines["right"].set_visible(False)
    axb.spines["left"].set_visible(False)
    axb.spines["bottom"].set_visible(False)
    ax1.set_xlim(tlim)

    ax1.set_ylim(tlim)

    #RECONSIDER TAKING OUT THE LESS THAN 0 VALUES
    #real_data[real_data < 0.0] = np.nan

    #test_unnormed[test_unnormed < 0.0] = np.nan
    print type(img2), type(img)

    test_unnormed = np.squeeze(test_unnormed)
    im = ax2.imshow(test_unnormed,
                    vmin=0,
                    extent=extent,
                    origin='lower',
                    cmap=cmap)
    ax2.spines["top"].set_visible(False)
    ax2.spines['left'].set_visible(False)
    axl2.fill_between(img2.mean(1), f, alpha=0.7, color=color_list[1])
    axl2.invert_xaxis()
    axl2.spines["top"].set_visible(False)
    axl2.spines['right'].set_visible(False)
    axl2.spines['left'].set_visible(False)
    axl2.spines['bottom'].set_visible(False)
    axb2.fill_between(t, img2.mean(0), alpha=0.7, color=color_list[1])
    axb2.spines["top"].set_visible(False)
    axb2.spines["right"].set_visible(False)
    axb2.spines["left"].set_visible(False)
    axb2.spines["bottom"].set_visible(False)
    ax2.set_xlim(tlim)
    ax2.set_ylim(tlim)

    ax1.set_xlabel("Real", fontsize=11)
    ax2.set_xlabel("VAE", fontsize=11)
    ax1.set_ylabel(r"$\mathit{y}$", fontsize=12, rotation=0)
    ax1.yaxis.set_label_coords(-0.07, 0.98)
    fig.tight_layout(rect=[0, 0, .9, 1])
    cbar_ax = fig.add_axes([0.9, 0.25, 0.025, 0.45])
    cb = fig.colorbar(im, cax=cbar_ax)
    cb.set_label(r'$E_{dep}$ (MeV)', y=0.85)
    plt.figtext(0.05, 0.060, r"$\mathit{x}$", fontsize=12)
    fig.subplots_adjust(wspace=0.1, hspace=0)
    fig.suptitle(r" CVAE Avg $E_{dep}$ Over " + str(n_events) + " Events, " +
                 str(imageSize) + "x" + str(imageSize) + " \n Image Size, " +
                 str(epoch) + " Epochs",
                 x=0.46,
                 y=0.02)
    if save_dir != None:
        #learning_rate = '%.0E' % Decimal(lr)
        #directory = "/home/chris/Documents/MPhilProjects/ForViewing/plots/Geant4/SingleLayerEGun/VAE/"
        filename = "CVAE_RealandFakeAvgEdep" + str(
            withMarginals) + "Over" + str(n_events) + "Events_Epoch" + str(
                epoch) + ".png"
        plt.savefig(save_dir + filename, bbox_inches='tight')
    plt.show()
    return
Example #46
0
import pandas as p
import matplotlib.pyplot as plt

#reading training data set
data=p.read_csv('train.csv')
X_train= data.iloc[:, :-1].values 
Y_train= data.iloc[:, 1].values 

#fitting training dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X_train,Y_train)

#reading test dataset
data1=p.read_csv("test.csv")
X_test= data1.iloc[:, :-1].values 
Y_test= data1.iloc[:, 1].values 

#predicting 
Y_predict=lin_reg.predict(X_test)

#plot
plt.scatter(X_test,Y_test,color='purple')
plt.plot(X_train,lin_reg.predict(X_train),color='orange')
plt.figtext(.2, .7, "Test set result = purple")
plt.figtext(.2, .6, "Predicted result = orange")
plt.title('Linear Regression Model')
plt.ylabel('Amount (in lakhs)')
plt.xlabel('Time invested')
plt.show()
Example #47
0
#set axis limits
plt.ylim(1e9, 1e12)

#adjust tick label font size
label_size = 22
matplotlib.rcParams['xtick.labelsize'] = label_size
matplotlib.rcParams['ytick.labelsize'] = label_size
# do it this way!!:
#plt.rcParams.update[{'font.size':20}]

# add a legend with some customizations.
legend = ax.legend(loc='lower right', fontsize='x-large')

#add figure text
plt.figtext(0.15, 0.83, 'Milky Way Mass Profile', fontsize=22)

# Save to a file
ax.set_rasterized(True)
plt.savefig('MassProfile_MW.eps', rasterized=True, dpi=350)

# Plot the Mass Profile for M31.
####################################

fig = plt.figure(figsize=(10, 10))
ax = plt.subplot(111)

# Plot mass enclosed for Halo
plt.semilogy(R,
             M31.MassEnclosed(1, R),
             color='blue',
Example #48
0
    simulations[run] = stock_monte_carlo(start_price,days,mu,sigma)[days-1];


# In[64]:


# Now we'lll define q as the 1% empirical qunatile, this basically means that 99% of the values should fall between here
q = np.percentile(simulations, 1)
    
# Now let's plot the distribution of the end prices
plt.hist(simulations,bins=200)

# Using plt.figtext to fill in some additional information onto the plot

# Starting Price
plt.figtext(0.6, 0.8, s="Start price: $%.2f" %start_price)
# Mean ending price
plt.figtext(0.6, 0.7, "Mean final price: $%.2f" % simulations.mean())

# Variance of the price (within 99% confidence interval)
plt.figtext(0.6, 0.6, "VaR(0.99): $%.2f" % (start_price - q,))

# Display 1% quantile
plt.figtext(0.15, 0.6, "q(0.99): $%.2f" % q)

# Plot a line at the 1% quantile result
plt.axvline(x=q, linewidth=4, color='r')

# Title
plt.title(u"Final price distribution for Google Stock after %s days" % days, weight='bold');
Example #49
0
    ax = plt.subplot(111)
    ax.plot(xp, yp, linewidth=1)

    # Display trapezoid rule errors by sampling just a few points
    a, b = 2, 9  # integral area
    npts = 4

    # make the shaded region
    ix = np.linspace(a, b, npts)
    iy = func(ix)
    verts = [(a, 0)] + zip(ix, iy) + [(b, 0)]
    poly = plt.Polygon(verts, facecolor='0.8', edgecolor='k')
    ax.add_patch(poly)
    ax.scatter(ix, iy, zorder=2)

    # Fancify plot with labels and clean axes
    plt.text(0.5 * (a + b),
             30,
             r"$\int_a^b f(x)\mathrm{d}x$",
             horizontalalignment='center',
             fontsize=20)
    plt.axis([0, 10, 0, 180])
    plt.figtext(0.9, 0.05, 'x')
    plt.figtext(0.1, 0.9, 'y')
    plt.title('Trapezoid rule integration')
    ax.set_xticks((a, b))
    ax.set_xticklabels(('a', 'b'))
    ax.set_yticks([])
    plt.show()
Example #50
0
def _plot_topo(info,
               times,
               show_func,
               click_func=None,
               layout=None,
               vmin=None,
               vmax=None,
               ylim=None,
               colorbar=None,
               border='none',
               axis_facecolor='k',
               fig_facecolor='k',
               cmap='RdBu_r',
               layout_scale=None,
               title=None,
               x_label=None,
               y_label=None,
               font_color='w',
               unified=False,
               img=False,
               axes=None):
    """Plot on sensor layout."""
    import matplotlib.pyplot as plt

    if layout.kind == 'custom':
        layout = deepcopy(layout)
        layout.pos[:, :2] -= layout.pos[:, :2].min(0)
        layout.pos[:, :2] /= layout.pos[:, :2].max(0)

    # prepare callbacks
    tmin, tmax = times[[0, -1]]
    click_func = show_func if click_func is None else click_func
    on_pick = partial(click_func,
                      tmin=tmin,
                      tmax=tmax,
                      vmin=vmin,
                      vmax=vmax,
                      ylim=ylim,
                      x_label=x_label,
                      y_label=y_label,
                      colorbar=colorbar)

    if axes is None:
        fig = plt.figure()
        axes = plt.axes([0.015, 0.025, 0.97, 0.95])
        _set_ax_facecolor(axes, fig_facecolor)
    else:
        fig = axes.figure
    if colorbar:
        sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin, vmax))
        sm.set_array(np.linspace(vmin, vmax))
        cb = fig.colorbar(sm,
                          ax=axes,
                          pad=0.025,
                          fraction=0.075,
                          shrink=0.5,
                          anchor=(-1, 0.5))
        cb_yticks = plt.getp(cb.ax.axes, 'yticklabels')
        plt.setp(cb_yticks, color=font_color)
    axes.axis('off')

    my_topo_plot = _iter_topography(info,
                                    layout=layout,
                                    on_pick=on_pick,
                                    fig=fig,
                                    layout_scale=layout_scale,
                                    axis_spinecolor=border,
                                    axis_facecolor=axis_facecolor,
                                    fig_facecolor=fig_facecolor,
                                    unified=unified,
                                    img=img,
                                    axes=axes)

    for ax, ch_idx in my_topo_plot:
        if layout.kind == 'Vectorview-all' and ylim is not None:
            this_type = {'mag': 0, 'grad': 1}[channel_type(info, ch_idx)]
            ylim_ = [v[this_type] if _check_vlim(v) else v for v in ylim]
        else:
            ylim_ = ylim

        show_func(ax,
                  ch_idx,
                  tmin=tmin,
                  tmax=tmax,
                  vmin=vmin,
                  vmax=vmax,
                  ylim=ylim_)

    if title is not None:
        plt.figtext(0.03, 0.95, title, color=font_color, fontsize=15, va='top')

    return fig
    if len(subax) < 3:
        bottomax2.spines['right'].set_visible(False)
        bottomax2.yaxis.set_major_locator(plt.NullLocator())

    if len(subax) == 3:
        bottomax2.set_ylabel('$\Delta$T from Previous Year ($^\circ$C)')

    dataframe_ttest(y, bottomax)

    subax.append([bottomax, bottomax2])

fig.suptitle(
    'Does Crop Yield$^1$ change as Surface Temperatures$^2$ Rise for\n' +
    'the World and Economic Country Groups$^3$ from 1961-2018')

# Proxy artist for line plot legend entry
blueline = mlines.Line2D([], [], color='C0')
fig.legend((blueline, wbar), ('Crop Yield', '$\Delta$T'))

plt.figtext(
    0.005,
    0.9,
    '$^1$ Crop data source - http:/www.fao.org/faostat/en/#data/QC\n' +
    '$^2$ Temperature data source - http:/www.fao.org/faostat/en/#data/ET\n' +
    '$^3$ Economic Country Groups according to UN M49 (2009)\n' +
    '- This is a general analysis. Underlying or additional factors\nare not considered.',
    horizontalalignment='left')

plt.show()
Example #52
0
def test_partial_usetex(caplog):
    caplog.set_level("WARNING")
    plt.figtext(.5, .5, "foo", usetex=True)
    plt.savefig(io.BytesIO(), format="ps")
    assert caplog.records and all("as if usetex=False" in record.getMessage()
                                  for record in caplog.records)
Example #53
0
def plot_2f_variability(dic, x_train, y_train, x_test, y_test):
    """
    Plots decision boundaries for a discrimination problem with 
    2 features in function of the training set draws.
    Superimposed with scatter plots of both training and test sets.
    """

    #### PLOT ####
    nullfmt = NullFormatter()

    # definitions for the axes
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.65
    bottom_h = left_h = left + width + 0.02

    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom_h, width, 0.2]
    rect_histy = [left_h, bottom, 0.2, height]

    # start with a rectangular Figure
    fig = plt.figure(1, figsize=(8, 8))
    fig.set_facecolor('white')

    axScatter = plt.axes(rect_scatter)
    axHistx = plt.axes(rect_histx)
    axHisty = plt.axes(rect_histy)

    # No labels
    axHistx.xaxis.set_major_formatter(nullfmt)
    axHisty.yaxis.set_major_formatter(nullfmt)

    # Scatter plot:
    from LR_functions import normalize
    x_train, x_test = normalize(x_train, x_test)
    feat_1 = x_test.columns[0]
    feat_2 = x_test.columns[1]
    axScatter.scatter(x_test[feat_1],
                      x_test[feat_2],
                      c=list(y_test.NumType.values),
                      cmap=plt.cm.gray,
                      alpha=.2)
    axScatter.scatter(x_train[feat_1],
                      x_train[feat_2],
                      c=list(y_train.NumType.values),
                      cmap=plt.cm.winter,
                      alpha=.5)

    # Plot decision boundaries
    x_vec = np.arange(-1, 1, .01)
    rates = []
    for draw in sorted(dic):
        theta = dic[draw]['out']['thetas']
        t = dic[draw]['out']['threshold']
        rates.append(dic[draw]['out']['rate_test']['global'])
        db = -1. / theta[1][2] * (theta[1][0] + np.log(
            (1 - t[1]) / t[1]) + theta[1][1] * x_vec)
        axScatter.plot(x_vec, db, lw=1., c=(0, 0.1 * draw, 1))

    imax = np.argmax(rates)
    theta = dic[imax]['out']['thetas']
    t = dic[imax]['out']['threshold']
    method = dic[imax]['out']['method'].upper()
    types = dic[imax]['out']['types']
    lab = r'%s %.1f$\pm$%.1f%%' % (method, np.mean(rates), np.std(rates))
    db_max = -1. / theta[1][2] * (theta[1][0] + np.log(
        (1 - t[1]) / t[1]) + theta[1][1] * x_vec)
    axScatter.plot(x_vec, db_max, lw=3., c='midnightblue', label=lab)
    axScatter.legend(loc=4)

    x_vec, y_vec, proba, map = class_2c_2f(theta, t)
    axScatter.contourf(x_vec, y_vec, map, cmap=plt.cm.gray, alpha=0.2)

    # Determine nice limits by hand
    bins_1, bins_2 = plot_limits(x_test, x_train)
    axScatter.set_xlim((bins_1[0], bins_1[-1]))
    axScatter.set_ylim((bins_2[0], bins_2[-1]))
    axScatter.set_xlabel(feat_1)
    axScatter.set_ylabel(feat_2)

    # Plot histograms and PDFs
    plot_histos_and_pdfs_kde(axHistx,
                             axHisty,
                             bins_1,
                             bins_2,
                             x_test,
                             y_test,
                             x_train=x_train,
                             y_train=y_train)
    axHistx.set_xlim(axScatter.get_xlim())
    axHisty.set_ylim(axScatter.get_ylim())

    # Display success rates
    pos_x = .76
    pos_y_ini = .95
    pas = .025
    plt.figtext(pos_x, pos_y_ini, 'Training set %s' % method)
    rate_tr, rate_tr_1, rate_tr_2 = [], [], []
    for draw in sorted(dic):
        p = dic[draw]['out']['rate_train']
        rate_tr.append(p['global'])
        for key in sorted(p):
            if key != 'global':
                cl, icl = key[0], key[1]
                if icl == 1:
                    rate_tr_1.append(p[(cl, icl)])
                else:
                    rate_tr_2.append(p[(cl, icl)])

    plt.figtext(
        pos_x, pos_y_ini - 1 * pas,
        'Global : %.1f$\pm$%.1f%%' % (np.mean(rate_tr), np.std(rate_tr)))
    plt.figtext(
        pos_x, pos_y_ini - 2 * pas, '%s (%d) : %.1f$\pm$%.1f%%' %
        (types[0], 0, np.mean(rate_tr_1), np.std(rate_tr_1)))
    plt.figtext(
        pos_x, pos_y_ini - 3 * pas, '%s (%d) : %.1f$\pm$%.1f%%' %
        (types[1], 1, np.mean(rate_tr_2), np.std(rate_tr_2)))

    pos_y_ini = pos_y_ini - 4.5 * pas
    pas = .025
    plt.figtext(pos_x, pos_y_ini, 'Test set %s' % method)
    rate_test, rate_test_1, rate_test_2 = [], [], []
    for draw in sorted(dic):
        p = dic[draw]['out']['rate_test']
        rate_test.append(p['global'])
        for key in sorted(p):
            if key != 'global':
                cl, icl = key[0], key[1]
                if icl == 1:
                    rate_test_1.append(p[(cl, icl)])
                else:
                    rate_test_2.append(p[(cl, icl)])

    plt.figtext(
        pos_x, pos_y_ini - 1 * pas,
        'Global : %.1f$\pm$%.1f%%' % (np.mean(rate_test), np.std(rate_test)))
    plt.figtext(
        pos_x, pos_y_ini - 2 * pas, '%s (%d) : %.1f$\pm$%.1f%%' %
        (types[0], 0, np.mean(rate_test_1), np.std(rate_test_1)))
    plt.figtext(
        pos_x, pos_y_ini - 3 * pas, '%s (%d) : %.1f$\pm$%.1f%%' %
        (types[1], 1, np.mean(rate_test_2), np.std(rate_test_2)))
Example #54
0
def test_type3_font():
    plt.figtext(.5, .5, "I/J")
Example #55
0
        print('dissimilarity : ', dissimilarity)
        print('similarity_loss : ', similarity_loss)

        dist = cdist(model_lf, model_rg, 'cosine')
        print('Pairwise distance : ', dist)
        euc = np.linalg.norm(model_lf - model_rg)
        print('euc : ', euc)

        fig = plt.figure()
        plt.title(('Similarity: %f, Dissimilarity: %f\nEuclidean Dist: %f, Logits: %f' % (similarity, dissimilarity, euc, my_logits)), loc='center')
        if my_logits > 0.0:
            textstr = 'Similar'
            props = dict(boxstyle='round', facecolor='green', alpha=0.5)
            fig_txt = tw.fill(tw.dedent(textstr), width=80)
            plt.figtext(0.51, 0.05, fig_txt, horizontalalignment='center',
                        fontsize=12, multialignment='center',
                        bbox=dict(boxstyle="round", facecolor='green',
                                  ec="0.5", pad=0.5, alpha=1), fontweight='bold')
        else:
            textstr = 'Dissimilar'
            props = dict(boxstyle='round', facecolor='red', alpha=0.5)
            fig_txt = tw.fill(tw.dedent(textstr), width=80)
            plt.figtext(0.51, 0.05, fig_txt, horizontalalignment='center',
                        fontsize=12, multialignment='center',
                        bbox=dict(boxstyle="round", facecolor='red',
                                  ec="0.5", pad=0.5, alpha=1), fontweight='bold')



        plt.axis('off')
        ax1 = fig.add_subplot(1, 2, 1)
        l_im = np.array(img)[0]
Example #56
0
    midpoint_errors_before, data_colors[date_list_before[0]],
    data_error_colors[date_list_before[0]], 'Before baking')
print(residual_std_after)
print(residual_std_before)
residual_percentages(ax_sub, temps_shifted_after, fit_parameters_after[0],
                     midpoints_after, data_colors[date_list_after[0]],
                     data_error_colors[date_list_after[0]], 'After baking')
residual_percentages(ax_sub, temps_shifted_before, fit_parameters_before[0],
                     midpoints_before, data_colors[date_list_before[0]],
                     data_error_colors[date_list_before[0]], 'Before baking')

# Setting the positions of the text on the figure
if not plot_ratios:
    plt.figtext(0.75,
                0.55,
                txt_str_after,
                color=data_colors[date_list_after[0]],
                fontsize=10)
    plt.figtext(0.75,
                0.35,
                txt_str_before,
                color=data_colors[date_list_before[0]],
                fontsize=10)

if plot_ratios:

    ax_ratio = ax_data.twinx()
    ax_ratio.set_position((0.08, 0.4, 0.6, 0.5))
    ax_ratio.tick_params(axis='y', colors='green')
    axes = [ax_data, ax_sub, ax_ratio]
random_seed = 6
sample_fraction = 0.1

sample_df = no2_df.sample(frac=sample_fraction,
                          axis="columns",
                          random_state=random_seed)
sample_df.reset_index(inplace=True)
sample_df.MeasurementDateGMT = pd.to_datetime(sample_df.MeasurementDateGMT)

fig, ax = plt.subplots(figsize=(20, 8))
fig.suptitle(r"LAQN sample - NO$_2$")
for column in sample_df.iloc[:, 1:].columns:
    print(f"Plotting {column}...")
    ax.plot(sample_df.MeasurementDateGMT,
            sample_df[column],
            label=column,
            alpha=0.3)

plt.figtext(
    0.2, 0.8,
    f"Sampling {int(sample_fraction*100)}% of all sites with random seed ({random_seed})"
)
ax.set(xlabel="Time", ylabel=r"NO$_2$ ($\mu$g m$^{-3}$)")
ax.legend(loc="upper right")
# plt.show()

plot_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             f"LAQN_NO2_sample_seed{random_seed}.png")
fig.savefig(plot_filename)
print(f"\nSaved plot to:\n{plot_filename}")
Example #58
0
def display_rates(plt, out, out_comp=None, map_nl=None):
    """
    Display success rates in the top right corner.
    """
    method = out['method']
    rate = out['rate_test']
    NB_class = len(rate) - 1
    if not (out_comp and map_nl):
        pos_y_ini = .95
        pas = .025
        plt.figtext(.78, pos_y_ini, 'Test set %s' % method.upper())
        for key in sorted(rate):
            if key != 'global':
                cl, icl = key[0], key[1]
                plt.figtext(.78, pos_y_ini - (icl + 1) * pas,
                            '%s (%d) : %.1f%%' % (cl, icl, rate[(cl, icl)]))
        if out_comp or map_nl:
            if out_comp:
                sup = out_comp
            elif map_nl:
                sup = map_nl
            pos_y = pos_y_ini - .04
            plt.figtext(.78, pos_y - NB_class * pas,
                        'Test set %s' % sup['method'].upper())
            p = sup['rate_test']
            for key in sorted(p):
                if key != 'global':
                    cl, icl = key[0], key[1]
                    plt.figtext(.78, pos_y - NB_class * pas - (icl + 1) * pas,
                                '%s (%d) : %.1f%%' % (cl, icl, p[(cl, icl)]))

    if out_comp and map_nl:
        if NB_class == 2:
            pos_y_ini = .95
            pas = .02
        else:
            pos_y_ini = .96
            pas = .015
        s = 10
        plt.figtext(.78, pos_y_ini, 'Test set %s' % method.upper(), size=s + 1)
        for key in sorted(rate):
            if key != 'global':
                cl, icl = key[0], key[1]
                plt.figtext(.78,
                            pos_y_ini - (icl + 1) * pas,
                            '%s (%d) : %.1f%%' % (cl, icl, rate[(cl, icl)]),
                            size=s)

        pos_y = pos_y_ini - .03
        pos_y_ini = pos_y - NB_class * pas
        plt.figtext(.78,
                    pos_y_ini,
                    'Test set %s' % out_comp['method'].upper(),
                    size=s + 1)
        p = out_comp['rate_test']
        for key in sorted(p):
            if key != 'global':
                cl, icl = key[0], key[1]
                plt.figtext(.78,
                            pos_y_ini - (icl + 1) * pas,
                            '%s (%d) : %.1f%%' % (cl, icl, p[(cl, icl)]),
                            size=s)

        pos_y = pos_y_ini - .03
        pos_y_ini = pos_y - NB_class * pas
        plt.figtext(.78,
                    pos_y_ini,
                    'Test set %s' % map_nl['method'].upper(),
                    size=s + 1)
        p = map_nl['rate_test']
        for key in sorted(p):
            if key != 'global':
                cl, icl = key[0], key[1]
                plt.figtext(.78,
                            pos_y_ini - (icl + 1) * pas,
                            '%s (%d) : %.1f%%' % (cl, icl, p[(cl, icl)]),
                            size=s)
Example #59
0
def plot_RAO_1d(s, omegas, wave_direction, waterdepth=0):
    """Calculates and plots the RAOs. Call plt.show afterwards to show the plots"""

    RAOs = RAO_1d(s=s,
                  omegas=omegas,
                  wave_direction=wave_direction,
                  waterdepth=waterdepth)

    # now plot
    # Use one figure per node
    nodes = s.dynamics_nodes()
    modes = s.dynamics_modes()

    figures = dict()

    # loop over nodes and modes and attach a figure to each of the nodes

    for i in range(len(nodes)):

        node = nodes[i]
        node_name = node.name

        if node_name in figures.keys():
            figure = figures[node_name]
        else:
            figure = list()

        figure.append(i)
        figures[node_name] = figure

    mode_names = ['X', 'Y', 'Z', 'RX', 'RY', 'RZ']

    import matplotlib.pyplot as plt
    from matplotlib.figure import figaspect

    for figure in figures.values():

        n_plots = len(figure)
        n_h = 1
        n_v = 1
        w, h = figaspect(1)
        if n_plots > 1:
            n_h = 2  # horizontal
            n_v = 1
            w, h = figaspect(0.5)
        if n_plots > 2:
            n_h = 2  # horizontal
            n_v = 2
            w, h = figaspect(1)
        if n_plots > 4:
            n_h = 2  # horizontal
            n_v = 3
            w, h = figaspect(1.5)

        f = plt.figure(figsize=(w, h))

        for i_plot, i_entry in enumerate(figure):
            ax1 = plt.subplot(n_v, n_h, i_plot + 1)

            node = nodes[i_entry]
            mode = modes[i_entry]

            a = RAOs[i_entry, :]

            amplitude = np.abs(a)

            if mode > 2:
                amplitude = np.rad2deg(amplitude)

            ax1.plot(omegas,
                     amplitude,
                     label="amplitude",
                     color='black',
                     linewidth=1)
            plt.title(mode_names[mode])
            ax1.set_xlabel('omega [rad/s]')
            plt.grid()

            yy = plt.ylim()
            if yy[1] < 1e-4:
                plt.ylim((0, 1))
                continue
            elif yy[1] < 1.0:
                plt.ylim((0, 1))
            else:
                plt.ylim((0, yy[1]))

            xx = plt.xlim()  # force min x to 0
            plt.ylim((0, xx[1]))

            ax2 = ax1.twinx()
            ax2.plot(omegas,
                     np.angle(a),
                     label="phase",
                     color='black',
                     linestyle=':',
                     linewidth=1)

            plt.suptitle('{}\nIncoming wave direction = {}'.format(
                node.name, wave_direction))

        plt.figtext(
            0.995,
            0.01,
            'Amplitude (solid) in [m] or [deg] on left axis\nPhase (dashed) in [rad] on right axis',
            ha='right',
            va='bottom',
            fontsize=6)
        plt.tight_layout()
Example #60
0
#ax.plot( range(valid_freq, len(train_history)+valid_freq, valid_freq), valid_history['loss'].tolist(), label='valid loss', color='Red')
         #marker='o', markersize=5, 
#plt.axis([0, len(train_history), 0, 1.5])
ax.set_xlim([0, len(train_history)])
ax.set_ylim([-0.05,0.2])
ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.005))
#ax.xaxis.set_major_locator(ticker.MultipleLocator(5))

plt.title('Loss graph', fontsize=15)
plt.xlabel('epoch', fontsize=13)
plt.ylabel('loss', fontsize=13)

box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width*0.7, box.height])
plt.legend(fontsize=12, bbox_to_anchor=(1.05,1),loc=2)
plt.figtext(0.7, 0.7, 'accuracy: '+str(test_accuracy[-1]))
plt.figtext(0.7, 0.6, 'frozen at '+str(frozen_epoch))

plt.savefig(os.path.join(save_path,  model_name, str(len(train_history))+'epochs_tvloss.png'))
print("Figure saved: "+os.path.join(save_path,  model_name, str(len(train_history))+'epochs_tvloss.png'))
#plt.close()



plt.figure(figsize=(8,6))
ax = plt.subplot(111)
ax.plot(train_history['err'].tolist(), label='train err')
#ax.plot( range(valid_freq, len(train_history)+valid_freq, valid_freq), valid_history['err'].tolist(), label='valid err', color='Red')
         #marker='o', markersize=5
#plt.axis([0, len(train_history), 0, 1.5])
ax.set_xlim([0, len(train_history)])