def plot_points(means_common, means_extra_ms, mean_extra_e, labels):
	ind = np.arange(len(labels))  # the x locations for the groups
	width = 0.2       # the width of the bars

	fig, ax = plt.subplots()
	rects1 = ax.bar(ind + 0.2, means_extra_ms, width, color='r')
	rects2 = ax.bar(ind + 0.4, means_common, width, color='g')
	rects3 = ax.bar(ind + 0.6, means_extra_e, width, color='b')

	# add some text for labels, title and axes ticks
	ax.set_ylabel('Number of points')
	ax.set_title('Point comparison')
	ax.set_xticks(ind+3*width)
	ax.set_xticklabels( tuple(labels) )
	
	plt.ylim(ymin = 0, ymax = 100)

	plt.figlegend( (rects1, rects2, rects3), ('Unique in MATSim route', 'Common points', 'Unique in estimated route'), 'upper right' )

	def autolabel(rects):
	    # attach some text labels
	    for rect in rects:
	        height = rect.get_height()
	        ax.text(rect.get_x()+0.6*rect.get_width(), 1.05*height, str(int(height)),
	                ha='center', va='bottom')

	autolabel(rects1)
	autolabel(rects2)
	autolabel(rects3)
def plot_all_dbs_hist():
    figure(figsize=(6.5,5))
    dbs = ['Heinemann-chemo','Peebo-gluc','Valgepea','HuiAlim','HuiClim','HuiRlim']
    dbext = {'Heinemann-chemo':'','Peebo-gluc':'','Valgepea':'','HuiAlim':', A-lim','HuiClim':', C-lim','HuiRlim':', R-lim'}
    p=subplot(111)
    for i,db in enumerate(dbs):
        ps = subplot(231+i)
        conds,gr,conc_data = datas[""][db]
        plot_corr_hist(ps,db,conc_data,categories)
        if db == 'Valgepea':
            year = 2013
        else:
            year = 2015
        ps.annotate("data from %s et. al. %d%s" % (db_name[db],year,dbext[db]),xy=(0.5,0.5),xytext=(-0.87,303),fontsize=6,zorder=10)
        ps.set_ylim(0,350)
        ps.set_xlim(-1,1)
        ps.annotate(chr(65+i),xy=(0.5,0.5),xytext=(-0.87,320),fontsize=10,zorder=10)

    #assume both subplots have the same categories.
    handles,labels=ps.get_legend_handles_labels()

    tight_layout()
    figlegend(handles,labels,fontsize=6,mode='expand',loc='upper left',bbox_to_anchor=(0.15,0.8,0.7,0.2),ncol=2)

    subplots_adjust(top=0.9)
    #fig = gcf()
    #py.plot_mpl(fig,filename="Growth rate Correlation histograms")
    savefig('AllDbsGrowthRateCorrelation.pdf')
    close()
Example #3
0
def rcp(results, graphNames):
  rsltSize = results[0].size / 3 
  prec = range(0,rsltSize)
  precN = range(0,rsltSize)
  recall = range(0, rsltSize)

  for r in results:
    for x in range(0,rsltSize):
      numPos = float(r[0,x][0])
      if numPos == 0:
        prec[x] = 1
      else:
        prec[x] = r[0,x][2] / numPos

    for x in range(0,rsltSize):
      recall[x] = r[0,x][2] / float(r[0,x][1])

    for x in range(0,rsltSize):
      precN[x] = 1- prec[x]

    graph = plt.plot(precN,recall)
    graphs.append(graph)

  # plot settings
  plt.ylabel('Recall')
  plt.xlabel('1 - Precision')
  plt.axis([0, 1.0, 0, 1.0])
  plt.grid(True)

  # legend for our graphs
  plt.figlegend( (graphs), graphNames,'upper left')
Example #4
0
 def rank_plot(self, rank_thresh = 100, show = True, filename = None):
     """Returns plot of the frequencies of the attributes, sorted by rank."""
     plt.figure()
     afdf = self.attr_freq_df(rank_thresh)
     cmap = plt.cm.gist_ncar
     colors = {i : cmap(int((i + 1) * cmap.N / (self.num_attr_types + 1.0))) for i in range(self.num_attr_types)}
     fig, (ax1, ax2) = plt.subplots(2, 1, sharex = False, sharey = False, facecolor = 'white')
     plots_for_legend = []
     for (i, t) in enumerate(self.attr_types):
         afdf_for_type = afdf[afdf['type'] == t]
         plots_for_legend.append(ax1.plot(afdf_for_type['rank'], np.log10(afdf_for_type['freq']), color = colors[i], linewidth = 2)[0])
         ax2.plot(afdf_for_type['rank'], afdf_for_type['cumulative %'], color = colors[i], linewidth = 2)
     ax1.set_title('Attribute frequencies by type', fontweight = 'bold')
     ax2.set_xlabel('rank')
     ax1.set_ylabel('log10(freq)')
     ax2.set_ylabel('cumulative %')
     ax2.set_ylim((0, 100))
     ax1.grid(True, 'major', color = 'w', linestyle = '-')
     ax2.grid(True, 'major', color = 'w', linestyle = '-')
     ax1.set_axisbelow(True)
     ax2.set_axisbelow(True)
     ax1.patch.set_facecolor('0.89')
     ax2.patch.set_facecolor('0.89')
     plt.figlegend(plots_for_legend, self.attr_types, 'right', fontsize = 10)
     if filename:
         plt.savefig(filename)
     if show:
         plt.show(block = False)
def plotDif(leap, est, tMag, setName):
    styleL = ["solid", "dashed", "dotted", "dashdot"]
    if len(est[0]) == 3:
        leap = leap[:, :-1]

    plt.figure()

    statesP = plt.subplot(211)

    #    for i in range(0,len(est[0]),1):
    for i in range(0, 1, 4):
        statesP.plot(tMag, leap[:, i], c="r", ls=styleL[i])
        statesP.plot(tMag, est[:, i], c="g", ls=styleL[i])

    #    statesP.legend()
    statesP.set_ylabel("Angle [rad]")
    statesP.set_title("Difference " + setName)

    difP = plt.subplot(212)
    dif = leap - est[:, :4]
    normedDif = np.linalg.norm(dif, axis=1)

    difP.plot(tMag, normedDif, c="g", ls="-")

    difP.set_ylabel("Normed Difference [rad]")
    difP.set_xlabel("Time [sec]")

    linePerf = mlines.Line2D([], [], color="r", markersize=15, label="Leap")
    lineEst = mlines.Line2D([], [], color="g", markersize=15, label="Estimated")
    plt.figlegend((linePerf, lineEst), ("Leap", "Estimated"), loc="upper right")
Example #6
0
def scatter_plot_matrix(data,class_labels,filename):
    plt.figure(figsize=(2000/96, 2000/96), dpi=96)
    for i in range(0,5):
        plt.subplot(5,5,5*i+i+1)
        plt.title(str(data.columns[i]), fontsize=10)
        min_value = float(np.min(data.ix[:,i]))
        max_value = float(np.max(data.ix[:,i]))
        xs = np.linspace(min_value,max_value,500) 
        k=0
        for cl in class_list:
            ind = np.where(class_labels == cl)[0]
            plot_density(data.ix[ind,i],xs,col[k])
            k+=1
        k=0
        for j in range(0,5):
            if i!=j:
                plt.subplot(5,5,5*i+j+1)
                plt.title(str(data.columns[i]) + " vs " + str(data.columns[j]), fontsize=10)
                plt.xlabel(data.columns[i], fontsize=10)
                plt.ylabel(data.columns[j], fontsize=10)
                for k in range(0,4):
                    ind = np.where(class_labels == class_list[k])[0]
                    plt.scatter(data.ix[ind,i],data.ix[ind,j],s=10,color = col[k],marker = marker_style[k], facecolors = 'none')
    line=[]
    for i in range(0,4):
        line.append(mlines.Line2D([], [], color=col[i], marker=marker_style[i],markersize=10))
    plt.tight_layout()
    plt.figlegend(handles = line, labels = class_list, loc = "upper right")
    plt.savefig(filename)
    plt.show() #refer to the saved image for proper visualization
Example #7
0
def plot(labels, real_values, *values_list):
    values = list(values_list)
    one_step_ahead = []
    one_step_ahead.append(real_values)
    k_step_ahead = []
    k_step_ahead.append(real_values)
    for i in range(0, len(values)/2):
        one_step_ahead.append(values[i])
        k_step_ahead.append(values[len(values)/2 + i])
    observations = []
    for i in np.arange(1, len(real_values) + 1):
        observations.append(i)
    plt.subplot(211)
    plt.grid(True)
    plt.xlabel('observations')
    plt.ylabel('temperature (C)')
    plt.title('One-step-ahead Data Prediction')
    plt.ylim(0, 31)
    lines = []
    for lab, val in zip(labels, one_step_ahead):
        lines.extend(plt.plot(observations, val, label=lab))
    plt.subplot(212)
    plt.grid(True)
    plt.xlabel('observations')
    plt.ylabel('temperature (C)')
    plt.title('K-step-ahead Data Prediction')
    plt.ylim(0, 31)
    for lab, val in zip(labels, k_step_ahead):
        plt.plot(observations, val, label=lab)
    plt.figlegend(lines, labels, loc = 'lower center', ncol=len(labels), labelspacing=0.)
    plt.show()
Example #8
0
def compare_hr_run(filename1, filename2, descriptor1='1st HR',
                   descriptor2='2nd HR', verbose=False):
  """
  Method to generate a plot comparison between two gpx runs
  """
  import matplotlib.pyplot as plt
  run1 = GPXCardio(filename1, verbose)
  run2 = GPXCardio(filename2, verbose)
  cardio1 = run1.getCardio()
  cardio2 = run2.getCardio()

  # Assume 1st file goes first in time
  def pts_fun(it, hr):
    t = map(lambda x: (x[0] - it).seconds, hr)
    hr = map(lambda x: x[1], hr)
    return t, hr

  initial_time = cardio1[0][0]
  f1_time, f1_hr = pts_fun(initial_time, cardio1)
  f2_time, f2_hr = pts_fun(initial_time, cardio2)
  lines = plt.plot(f1_time, f1_hr, 'r', f2_time, f2_hr, 'b')
  plt.ylabel("Heart Rate [bpm]")
  plt.xlabel("Seconds from begining")
  plt.title("Heart Rate Monitor Comparison")
  plt.grid(True)
  plt.figlegend((lines), (descriptor1, descriptor2), 'lower right')

  plt.show()
def model_effects_plot():
    grs = linspace(0.01,1,15)
    simple = grs
    neg = linspace(-0.4,0.01,6)
    simple = simple/simple.mean()
    degraded = grs+0.4
    degmean = degraded.mean()
    degraded = degraded/degmean
    neg_deg = neg+0.4
    neg_deg = neg_deg/degmean
    rate = 1/(1+0.2/grs)
    rate_effect = grs/rate
    rate_effect = rate_effect/rate_effect.mean()
    figure(figsize=(5,3))
    ax = subplot(111)
    ax.plot(grs,simple,'o',label="Unregulated protein - basic model")
    ax.plot(grs,degraded,'o',label="Unregulated protein - with degradation")
    ax.plot(neg,neg_deg,'--g')
    ax.plot(grs,rate_effect,'o',label="Unregulated protein - under decreasing biosynthesis rate")
    ax.plot(grs,rate,'--r',label="Biosynthesis rate")
    ax.annotate("degradation\nrate", xy=(-0.4,0),xytext=(-0.4,.6),arrowprops=dict(facecolor='black',shrink=0.05,width=1,headwidth=4),horizontalalignment='center',verticalalignment='center',fontsize=8)
    ax.set_xlim(xmin=-0.5)
    ax.set_ylim(ymin=0.)
    ax.set_xlabel('Growth rate [$h^{-1}$]',fontsize=8)
    set_ticks(ax,6)
    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.set_ylabel('Normalized protein concentration',fontsize=8)
    tight_layout()
    subplots_adjust(top=0.83)
    handles,labels=ax.get_legend_handles_labels()
    figlegend(handles,labels,fontsize=6,mode='expand',loc='upper left',bbox_to_anchor=(0.0,0.8,1,0.2),ncol=2,numpoints=1)
    savefig('TheoreticalModelEffects.pdf')
    close()
Example #10
0
def PlotGraphs(posDistList, negDiNucDist, graphFileName):
	global threeUtrValues, threeUtrErrors;

	import matplotlib
	matplotlib.use('Agg')
	
	from matplotlib import pyplot as plt	
	matplotlib.rcParams.update({'font.size': 8})

	posMeanValues = [x[0] for x in posDistList.values()]
	posErrorValues = [x[1] for x in posDistList.values()]	

	negMeanValues = [x[0] for x in negDiNucDist.values()]
	negErrorValues = [x[1] for x in negDiNucDist.values()]	

	#Two subplots, the axes array is 1-d
	fig, (ax1, ax2) = plt.subplots(nrows=2)
	fig.suptitle("Di-nucleotide distribution: 3'UTR vs Generated Files", fontsize=8)
	labels = posDistList.keys();
	eb1, eb2 = distribution_plot(ax1, "Positive Set", posMeanValues, posErrorValues, labels);
	eb1, eb2 = distribution_plot(ax2, "Negative Set", negMeanValues, negErrorValues, labels);

	plt.figlegend((eb1, eb2), ("Generated", "3'UTR"), loc = 'lower right');
	plt.savefig(graphFileName);
	plt.close(fig)
def plotMulti(leap, mag, time):
    """ plot only flex-ext of MCP """

    colorL = ["red", "green", "blue", "yellow"]
    a = plt.subplot(211)
    state = 0
    for i in range(0, len(leap), 1):
        a.plot(time, leap[i][:, state], c=colorL[i], ls="-")
        a.plot(time, mag[:, i * 4 + state], c=colorL[i], ls="--")

    dif = plt.subplot(212)
    state = 1
    for i in range(0, len(leap), 1):
        dif.plot(time, leap[i][:, state], c=colorL[i], ls="-")
        dif.plot(time, mag[:, i * 4 + state], c=colorL[i], ls="--")

    lineInd = mlines.Line2D([], [], color="r", markersize=15, label="Index")
    lineMid = mlines.Line2D([], [], color="g", markersize=15, label="Middle")

    lineLeap = mlines.Line2D([], [], color="k", linestyle="-", markersize=15, label="Leap")
    lineEst = mlines.Line2D([], [], color="k", linestyle="--", markersize=15, label="Estimated")

    plt.figlegend(
        (lineInd, lineMid, lineLeap, lineEst), ("Index", "Middle", "Leap", "Estimated"), loc="upper center", ncol=2
    )
def overlay_raw_data(raw_dict, individual_raw_dict, mole_graph, individual_graph, sun_results, uuid, out_path):
    # used because the SUN model uses single letter labels
    para_map = {"Notch2NL-A": "A", "Notch2NL-B": "B", "Notch2NL-C": "C", "Notch2NL-D": "D", "Notch2": "N"}
    fig, plots = plt.subplots(len(mole_graph.paralogs), sharey=True, figsize=(12.0, 5.0))
    individual_patch = matplotlib.patches.Patch(color=color_palette[0], fill="true")
    mole_patch = matplotlib.patches.Patch(color=color_palette[1], fill="true")
    plt.figlegend((individual_patch, mole_patch), ("Individual", "Mole"), loc='upper right', ncol=2)
    max_gap = max(stop - start for start, stop in mole_graph.paralogs.itervalues())
    for i, (p, para) in enumerate(izip(plots, mole_graph.paralogs.iterkeys())):
        start, stop = mole_graph.paralogs[para]
        rounded_max_gap = int(math.ceil(1.0 * max_gap / 10000) * 10000)
        p.axis([start, start + rounded_max_gap, 0, 4])
        x_ticks = [start] + range(start + 20000, start + rounded_max_gap + 20000, 20000)
        p.axes.set_yticks(range(5))
        p.axes.set_yticklabels(map(str, range(5)), fontsize=9)
        p.axes.set_xticks(x_ticks)
        p.axes.set_xticklabels(["{:.3e}".format(start)] + [str(20000 * x) for x in xrange(1, len(x_ticks))])
        starts, stops, vals = zip(*raw_dict[para])
        p.hlines(vals, starts, stops, color=color_palette[1], alpha=0.8, linewidth=2.0)
        if len(sun_results[para_map[para]]) > 0:
            sun_pos, sun_vals = zip(*sun_results[para_map[para]])
            p.vlines(np.asarray(sun_pos), np.zeros(len(sun_pos)), sun_vals, color="#E83535", linewidth=0.5, alpha=0.5)
        for x in range(1, 4):
            p.axhline(y=x, ls="--", lw=0.5)
        p.set_title("{}".format(para))
    for i, (p, para) in enumerate(izip(plots, individual_graph.paralogs.iterkeys())):
        starts, stops, vals = zip(*individual_raw_dict[para])
        p.hlines(vals, starts, stops, color=color_palette[0], alpha=0.8, linewidth=2.0)
        p.set_title("{}".format(para))    
    fig.subplots_adjust(hspace=0.8)
    plt.savefig(out_path, format="png", dpi=500)
    plt.close()
def VisualizeReferenceSpectrum(rf_files, freq_sampling):
    plt.figure(1, figsize=(5, 4))
    handles = []
    labels = []
    for rf_file in rf_files:
        ComponentType = itk.ctype('float')
        Dimension = 2
        ImageType = itk.VectorImage[ComponentType, Dimension]
        reader = itk.ImageFileReader[ImageType].New(FileName=rf_file)
        reader.Update()
        image = reader.GetOutput()
        arr = itk.GetArrayFromImage(image)
        arr /= arr[:,:,arr.shape[2]/3-arr.shape[2]/5:arr.shape[2]/2+arr.shape[2]/5].max()
        freq = np.linspace(freq_sampling / 2 / arr.shape[2], freq_sampling / 2, arr.shape[2])
        ax = plt.plot(freq, arr[0, 0, :].ravel(), label=rf_file)
        handles.append(ax[0])
        labels.append(rf_file)
        plt.xlabel('Frequency [Hz]')
        plt.ylabel('Power spectrum [V]')
    plt.figlegend(handles, labels, 'upper right')
    plt.ylim(0.0, 1.0)

    dirname = os.path.dirname(rf_files[0])
    plt.savefig(os.path.join(dirname, 'ReferenceSpectrum.png'), dpi=300)
    plt.show()
Example #14
0
def regional_sa(model, expr, policy={}, nsamples=1000):
    samples = sample_lhs(model, nsamples)
    output = evaluate(model, overwrite(samples, policy))
    classification = output.apply(expr)
    classes = sorted(set(classification))
    fig, axarr = plt.subplots(1, len(model.uncertainties))
    lines = []
    
    for i, u in enumerate(model.uncertainties):
        for k in classes:
            indices = [classification[j] == k for j in range(len(classification))]
            values = [output[j][u.name] for j in range(len(indices)) if indices[j]]
            sorted_values = sorted(enumerate(values), key=operator.itemgetter(1))
            h = axarr[i].plot([v[1] for v in sorted_values], np.arange(len(values))/float(len(values)-1))
            lines.append(h[0])
            
        values = [output[j][u.name] for j in range(len(indices))]
        sorted_values = sorted(enumerate(values), key=operator.itemgetter(1))
        h = axarr[i].plot([v[1] for v in sorted_values], np.arange(len(values))/float(len(values)-1))
        lines.append(h[0])
        
        axarr[i].set_title(u.name)
        
    plt.figlegend(lines[:len(classes)] + [lines[-1]],
                  map(str, classes) + ["Unconditioned"],
                  loc='lower center',
                  ncol=3,
                  labelspacing=0. )
    
    return fig
Example #15
0
def med_spread_plot(data, obj_names, fig_name="temp.png", **settings):
  fig = plt.figure(1)
  fig.subplots_adjust(hspace=0.5)
  directory = fig_name.rsplit("/", 1)[0]
  mkdir(directory)
  for i, data_map in enumerate(data):
    meds = data_map["meds"]
    iqrs = data_map.get("iqrs", None)
    if iqrs:
      x = range(len(meds))
      index = int(str(len(data))+"1"+str(i+1))
      plt.subplot(index)
      plt.title(obj_names[i])
      plt.plot(x, meds, 'b-', x, iqrs, 'r-')
      plt.ylim((min(iqrs)-1, max(meds)+1))
    else:
      x = range(len(meds))
      index = int(str(len(data))+"1"+str(i+1))
      plt.subplot(index)
      plt.title(obj_names[i])
      plt.plot(x, meds, 'b-')
      plt.ylim((min(meds)-1, max(meds)+1))
  blue_line = mlines.Line2D([],[], color='blue', label='Median')
  red_line = mlines.Line2D([],[], color='red', label='IQR')
  plt.figlegend((blue_line, red_line), ('Median', 'IQR'), loc=9, bbox_to_anchor=(0.5, 0.075), ncol=2)
  plt.savefig(fig_name)
  plt.clf()
def percplot(data, perclist, file_name='weight_update_percentile', file_extension='.png', save_im=True, disp_im=False,
             sety=True):
    """Plot percentiles of weight update information during 'training1' of RBM object (RBM_m.py)

    :param data: list of lists, each sublist containing the same percentiles of the weight update matrices
    :param perclist: list of used percentiles
    :param file_name: name of optional output file (default: 'weight_update_percentile')
    :param file_extension: extension of optional output file (default: '.png')
    :param save_im: whether to save image (default: True)
    :param disp_im: whether to show image (default: False)
    :param sety: whether to set the y-range to predefined limits (default: True)
    :return: nothing, displays plot or saves plot to output file
    """

    fig = plt.figure()
    lines = plt.plot(data)
    plt.ylabel('update / weight')
    plt.xlabel('batch number')

    if sety:
        plt.ylim([-0.1, 0.1])

    plt.figlegend(lines, perclist, 'upper right')

    if disp_im:
        plt.show()

    if save_im:
        # Save to (.png) file, remove white border
        plt.savefig("{}{}".format(file_name, file_extension), bbox_inches='tight')

    plt.close(fig)                  # Clear current figure
Example #17
0
    def __init__(self, window, subplot_num, x_axis, dim=2):
        ax = window.add_subplot(subplot_num)
        l = len(x_axis)
        self.y = ax.plot(range(l), l*[-1,], '-',       # Obtain handle to y axis.
                         range(l), l*[-1,], '--',
                         marker='^'
                         )
        # Hack: because initially the graph has too few y points, compared to x points,
        # nothing should be shown on the graph.
        # The hack is that initial y axis is seto be be below in hell.
        self.y_data = []
        for i in range(dim):
            self.y_data.append( col.deque(len(x_axis)*[-9999,],          # Circular buffer.
                                          maxlen=len(x_axis)
                                          )
                              )

        # Make plot prettier
        plt.grid(True)
        plt.tight_layout()
        ax.set_ylim(MIN_TEMP, MAX_TEMP)
        plt.figlegend(self.y, ('tempr', 'ctrl'), 'upper right');
        ax.set_ylabel('temperature [C]')
        # Terrible hack!
        if subplot_num == 121:
            ax.set_xlabel('time [s]')
        else:
            ax.set_xlabel('time [min]')
Example #18
0
def loglogplot(l, title = None, names = None):
    a = np.array(l).transpose((1,2,0))
    mp.figure()
    lines = mp.loglog(1.0 / a[0], a[1])
    if title: mp.suptitle(title)
    if len(lines) > 1:
        if names is None: names = range(len(lines)) 
        mp.figlegend(lines, names, 'right')
Example #19
0
def plot_timfile(timfile):
    """Make a plot summarizing a timfile.

        Input:
            timfile: A row of info of the timfile to summarize.

        Output:
            None
    """
    import matplotlib.pyplot as plt
    import matplotlib
    
    COLOURS = ['k', 'g', 'r', 'b', 'm', 'c', 'y']
    ncolours = len(COLOURS)
    BANDS = ['UHF', 'L-band', 'S-band']
    numbands = len(BANDS)
    toas = get_timfiles_toas(timfile['timfile_id'])
    obssys_ids = set()
    for toa in toas:
        obssys_ids.add(toa['obssystem_id'])
    obssys_ids = list(obssys_ids)
    fig = plt.figure()
    ax = plt.axes((0.1, 0.15, 0.85, 0.75))
    lomjd = 70000
    himjd = 10000
    artists = []
    for toa in toas:
        ind = BANDS.index(toa['band_descriptor'])
        ymin = float(ind)/numbands
        ymax = float(ind+1)/numbands
        cc = COLOURS[obssys_ids.index(toa['obssystem_id']) % ncolours]
        artists.append(plt.axvline(toa['mjd'], ymin, ymax, c=cc))
        himjd = max(himjd, toa['mjd'])
        lomjd = min(lomjd, toa['mjd'])
    plt.xlabel("MJD")
    plt.yticks(np.arange(0.5/numbands, 1, 1.0/numbands), BANDS,
               rotation=30, va='top')
    plt.xlim(lomjd, himjd)
    patches = []
    obssystems = []
    for ii, obssys_id in enumerate(obssys_ids):
        cc = COLOURS[ii % ncolours]
        patches.append(matplotlib.patches.Patch(fc=cc))
        obssystems.append(cache.get_obssysinfo(obssys_id)['name'])
    plt.figlegend(patches, obssystems, 'lower center', ncol=4,
                  prop=dict(size='small'))

    def change_thickness(event):
        if event.key == '=':
            for art in artists:
                lw = art.get_linewidth()
                art.set_linewidth(lw+0.5)
        elif event.key == '-':
            for art in artists:
                lw = art.get_linewidth()
                art.set_linewidth(max(1, lw-0.5))
        plt.draw()
    fig.canvas.mpl_connect('key_press_event', change_thickness)
def makeGraph(choices, flightID, folder):
    fig, ax =  plt.subplots()
    axes = [ax]
    axes[0].set_xlabel('Time (minutes)')

    title = 'Time vs %s for Flight: %s'
    msg = parameters[choices[0]]['label']
    for i in range(1, len(choices)):  # Loop to add y-axes & append onto msg
        axes.append(axes[0].twinx())
        msg += ' & ' + parameters[choices[i]]['label']
        if i > 1:
            # Move the last y-axis spine over to the right by 10% of the width of the axes
            axes[-1].spines['right'].set_position(('axes', 1 + (.1 * (i-1))))

            # To make the border of the right-most axis visible, we need to turn the frame
            # on. This hides the other plots, however, so we need to turn its fill off.
            axes[-1].set_frame_on(True)
            axes[-1].patch.set_visible(False)

    if len(choices) > 2:
        # Make some space on the right side for the extra y-axis.
        fig.subplots_adjust(right=(0.75))

    COLORS = ('blue', 'red', 'green', 'indigo', 'magenta', 'lightskyblue', 'black', 'salmon', 'chartreuse', 'maroon', 'crimson')

    for ax, c, color in zip(axes, choices, COLORS):
        ax.plot(parameters[0]['data'], parameters[c]['data'], color)
        ax.set_ylabel( '%s (%s)' % (parameters[c]['label'], parameters[c]['units']), color=color )
        ax.tick_params(axis='y', colors=color)

    patches = []
    types = ('Stop and Go', 'Touch and Go', 'Go Around', 'Unstable Approach')
    COLORS = ('lime', 'cyan', 'orange', 'red')

    for landingType, color in zip(types, COLORS):
        patches.append(mpatches.Patch(color=color, label = landingType))
    for key, a in approaches.items():
        for x in a['unstable']:
            axes[0].axvspan( parameters[0]['data'][x[0]], parameters[0]['data'][x[1]], alpha = 0.8, color='red')
        if (a['landing-type'] == 'stop-and-go'):
            landingColor = 'lime'
        elif (a['landing-type'] == 'touch-and-go'):
            landingColor = 'cyan'
        else:
            landingColor = 'orange'
        axes[0].axvspan( parameters[0]['data'][a['landing-start']], parameters[0]['data'][a['landing-end']], alpha = 0.8, color = landingColor)


    plt.title(title % (msg, flightID))

    plt.figlegend(handles=patches, labels=types, loc='center right')

    figure = plt.gcf()
    figure.set_size_inches(25.6, 16)
    plt.savefig('%s/%s.png' % (folder, flightID), dpi = 100)
    plt.clf()
Example #21
0
def compare_control(traj, traj_comp, shadow_last=0,plot_columns = 4, order=None):

    xlabel = 't'
    if 't' in traj:
        t = traj['t']
    else:
        print('Time is needed for control comparison')
        return None

    if 't' in traj_comp:
        t_comp = traj_comp['t']
    else:
        print('Time is needed for control comparison')
        return None

    columns = [c for c in traj.columns if c != 't']
    if not order == None:
        columns = [columns[i] for i in order]

    plot_rows = int(len(columns)/plot_columns)

    if len(columns) % plot_columns > 0:
        plot_rows += 1

    sns.set(font_scale=1.8)
    sns.set_style("whitegrid")
    sns.set_style("ticks", {"xtick.major.size": 4, "ytick.major.size": 4})

    plt.rcParams['figure.figsize'] = (12, 5 *plot_rows)

    fig, axes = plt.subplots(nrows=plot_rows, ncols=plot_columns)
    sns.set_context(font_scale=2)


    for i, c in enumerate(columns):
        bg_color = None
        if i > (len(columns)-shadow_last-1):
            bg_color = 'lightgray'
        plt.subplot(plot_rows, plot_columns, i+1, axisbg=bg_color)
        plt.xlabel(xlabel)
        plt.ylabel(c)
        l1, = plt.plot(t, traj[c])
        l2, = plt.plot(t_comp, traj_comp[c], c=sns.color_palette()[2])
        plt.locator_params(nbins=4)
        r = (max(traj[c])) - (min(traj[c]))
        plt.ylim((min(traj[c])-0.1*r, max(traj[c])+0.1*r))
        plt.xlim((t.iloc[0], t.iloc[-1]))

    plt.figlegend([l1,l2],['Optimal control', 'DNN control'],loc = 'upper center', ncol=2,prop={'size':20}, bbox_to_anchor=(0.5, 1.01 ))

    for i in range(len(columns),plot_rows*plot_columns):
        plt.subplot(plot_rows,plot_columns,i+1)
        plt.axis('off')

    plt.tight_layout()
    return fig
Example #22
0
def visualize2(path):
    print("Processing path {0}...".format(path))
    data = built_converged_data(path)

    inums_oldpop = dict()
    inums_random = dict()
    for wf_name, tasks in data.items():
        for task_id, (old_pop_results, random_results) in _sort_dict(tasks):



            for inum, record in _sort_dict(old_pop_results):
                if int(inum) in points:
                    dt = inums_oldpop.get(inum, [])
                    dt.append(record["best_avr"])
                    inums_oldpop[inum] = dt

            for inum, record in _sort_dict(random_results):
                if int(inum) in points:
                    dt = inums_random.get(inum, [])
                    dt.append(record["best_avr"])
                    inums_random[inum] = dt
            pass



    result_oldpop = {i: sum(values)/len(values) for i, values in inums_oldpop.items()}
    result_random = {i: sum(values)/len(values) for i, values in inums_random.items()}

    result = {i_1: (1 - v_1/v_2)*100 for((i_1, v_1), (i_2, v_2)) in zip_longest(_sort_dict(result_oldpop), _sort_dict(result_random))}

    plt.figure(figsize=(10, 10))
    plt.grid(True)
    ax = plt.gca()
    ax.set_xlim(0, len(points))
    ax.set_xscale('linear')
    plt.xticks(range(0, len(points)))
    ax.set_xticklabels(points)
    ax.set_title("Overall")
    plt.yticks([i/5 for i in range(0, 100)])

    data = [v for (i, v) in _sort_dict(result)]
    plt.plot(data, '-bx')

    h1 = Rectangle((0, 0), 1, 1, fc="r")
    h2 = Rectangle((0, 0), 1, 1, fc="g")
    h3 = Rectangle((0, 0), 1, 1, fc="b")



    plt.suptitle('Average of Best vs Average of Avr', fontsize=20)
    plt.figlegend([h1, h2, h3], ['with old pop', 'random', 'perf profit'], loc='lower center', ncol=10, labelspacing=0. )
    plt.subplots_adjust(hspace=0.5)
    plt.savefig(path + "overall.png", dpi=128.0, format="png")
    plt.clf()
    pass
Example #23
0
    def customeLegend(self,color_map):
	    legend_map=[[],[]]
	    for sample in color_map:
	        legend_map[0].append(Rectangle((0,0),0,0,visible=False))
	        legend_map[1].append(sample)
	        for label  in color_map[sample]:
	            box=Rectangle((0,0),1,1,color=color_map[sample][label],fill=True)
	            legend_map[0].append(box)
	            legend_map[1].append(label)
	    plt.figlegend(legend_map[0],legend_map[1],loc=9,ncol=len(color_map),prop={'size':8})  
Example #24
0
    def make_diag_figure(self, xnames, ynames):
        nobj = len(xnames)

        # initialize subplot size
        gs, fig = ftools.gen_gridspec_fig(
            nobj, add_row=False, border=(0.6, 0.6, 0.2, 0.4),
            space=(0.6, 0.35))

        # set up subplot interactions
        gs_geo = gs.get_geometry()

        fgrid_r, fgrid_c = tuple(list(range(n)) for n in gs_geo)
        gs_iter = iproduct(fgrid_r, fgrid_c)

        # set up kwargs for matplotlib errorbar
        # prefer to change color, then marker
        colors_ = ['C{}'.format(cn) for cn in range(10)]
        markers_ = ['o', 'v', 's', 'P', 'X', 'D', 'H']

        # iterate through rows & columns (rows change fastest)
        # which correspond to different quantities
        for (i, (ri, ci)) in enumerate(gs_iter):

            if i >= len(xnames):
                continue

            # choose axis
            ax = fig.add_subplot(gs[ri, ci])
            kwarg_cycler = cycler(marker=markers_) * \
                           cycler(c=colors_)

            xqty = xnames[i]
            yqty = ynames[i]

            # now iterate through results hdulists
            for (j, (result, kwargs)) in enumerate(
                zip(self.results, kwarg_cycler)):

                kwargs['label'] = result[0].header['PLATEIFU']

                ax = self._add_log_offset_plot(
                    j, xqty=xqty, yqty=yqty, ax=ax, **kwargs)

                ax.tick_params(labelsize=5)

            if i == 0:
                handles_, labels_ = ax.get_legend_handles_labels()
                plt.figlegend(
                    handles=handles_, labels=labels_,
                    loc='upper right', prop={'size': 4.})

        fig.suptitle('PCA fitting diagnostics', size=8.)

        return fig
Example #25
0
def handle_plot(req):
    t = time.time()
    plt.clf()
    ax = plt.subplot(111)
    plt.subplots_adjust(top=0.6)
    for plot_data in req.plots:
        plot(plot_data)
    labels = [line.get_label() for line in ax.lines]
    plt.figlegend(ax.lines, labels, 'upper right')
    plt.savefig(location + str(t) + '.png')
    
    return PlotResponse()
def plotdata(ionofile_in,ionofile_fit,madfile,time1):


    fig1,axmat =plt.subplots(2,2,facecolor='w',figsize=(10,10))
    axvec = axmat.flatten()
    paramlist = ['ne','te','ti','vo']
    paramlisti = ['Ne','Te','Ti','Vi']
    paramlistiname = ['$N_e$','$T_e$','$T_i$','$V_i$']
    paramunit = ['$m^{-3}$','$^\circ$ K','$^\circ$ K','m/s']
    boundlist = [[0.,7e11],[500.,3200.],[500.,2500.],[-500.,500.]]
    IonoF = IonoContainer.readh5(ionofile_fit)
    IonoI = IonoContainer.readh5(ionofile_in)
    gfit = GeoData(readIono,[IonoF,'spherical'])
    ginp = GeoData(readIono,[IonoI,'spherical'])
    data1 = GeoData(readMad_hdf5,[madfile,['nel','te','ti','vo','dnel','dte','dti','dvo']])
    data1.data['ne']=sp.power(10.,data1.data['nel'])
    data1.data['dne']=sp.power(10.,data1.data['dnel'])
    
    t1,t2 = data1.timelisting()[340]
    handlist = []
    for inum,iax in enumerate(axvec):
        ploth = rangevsparam(data1,data1.dataloc[0,1:],time1,gkey=paramlist[inum],fig=fig1,ax=iax,it=False)
        handlist.append(ploth[0])
        ploth = rangevsparam(ginp,ginp.dataloc[0,1:],0,gkey=paramlisti[inum],fig=fig1,ax=iax,it=False)
        handlist.append(ploth[0])
        ploth = rangevsparam(gfit,gfit.dataloc[0,1:],0,gkey=paramlisti[inum],fig=fig1,ax=iax,it=False)
        handlist.append(ploth[0])
        iax.set_xlim(boundlist[inum])
        iax.set_ylabel('Altitude in km')
        iax.set_xlabel(paramlistiname[inum]+' in '+paramunit[inum])
    # with error bars
    plt.tight_layout()
    fig1.suptitle('Comparison Without Error Bars\nPFISR Data Times: {0} to {1}'.format(t1,t2))
    plt.subplots_adjust(top=0.9)
    plt.figlegend( handlist[:3], ['PFISR', 'SimISR Input','SimISR Fit'], loc = 'lower center', ncol=5, labelspacing=0. )
    fig2,axmat2 =plt.subplots(2,2,facecolor='w',figsize=(10,10))
    axvec2 = axmat2.flatten()
    handlist2 = []
    for inum,iax in enumerate(axvec2):
        ploth = rangevsparam(data1,data1.dataloc[0,1:],time1,gkey=paramlist[inum],gkeyerr='d'+paramlist[inum],fig=fig2,ax=iax,it=False)
        handlist2.append(ploth[0])
        ploth = rangevsparam(ginp,ginp.dataloc[0,1:],0,gkey=paramlisti[inum],fig=fig2,ax=iax,it=False)
        handlist2.append(ploth[0])
        ploth = rangevsparam(gfit,gfit.dataloc[0,1:],0,gkey=paramlisti[inum],gkeyerr='n'+paramlisti[inum],fig=fig2,ax=iax,it=False)
        handlist2.append(ploth[0])
        iax.set_xlim(boundlist[inum])
        iax.set_ylabel('Altitude in km')
        iax.set_xlabel(paramlistiname[inum]+' in '+paramunit[inum])
    plt.tight_layout()
    fig2.suptitle('Comparison With Error Bars\nPFISR Data Times: {0} to {1}'.format(t1,t2))
    plt.subplots_adjust(top=0.9)
    plt.figlegend( handlist2[:3], ['PFISR', 'SimISR Input','SimISR Fit'], loc = 'lower center', ncol=5, labelspacing=0. )
    return (fig1,axvec,handlist,fig2,axvec2,handlist2)
Example #27
0
    def currdenfig(self, title=None, times=[0], z_index=0, leg_kwargs={},
                   **kwargs):
        """Plot current densities of the cell segments at times.

        **Arguments:**

        - *title*: Title for the figure

        - *times*: List of times at which the data should be sampled

             If multiple times are given, then subfigures will be generated.

        - *z_index*: z-index at which the current densities are taken

        - *leg_kwargs*: Dictionary of keyword arguments for
          :meth:`matplotlib.pyplot.legend`

             If *leg_kwargs* is *None*, then no legend will be shown.

        - *\*\*kwargs*: Additional arguments for  :meth:`barfig`
        """
        # Process the arguments.
        xlabel = kwargs.pop('xlabel', 'y-axis index (inlet to outlet)')
        name_template = self.cell + ('iprimeprime_seg[%i, ' + '%i]'
            % (z_index+1))
        #description = self.get_description(name_template % 1)
        #unit = self.get_unit(name_template % 1)
        unit = self.get_unit(name_template % 1)
        #ylabel = kwargs.pop('ylabel', label_number(description, unit))
        ylabel = kwargs.pop('ylabel', label_number("Current density", unit))

        # Create the plot.
        ax = self.barfig(names=[name_template % (i_y+1) for i_y in range(1)],
                         times=times, xlabel=xlabel, ylabel=ylabel,
                         leg_kwargs=None, **kwargs)
        for a, time in zip(ax, times):
            a.axhline(self.get_values('cell.iprimeprime', time),
                      linestyle='--', color='k', label='Entire cell')

        # Decorate.
        if title is None:
            if self.n_z == 1:
                plt.title("Current Distribution of Cell Segments")
            else:
                plt.title("Current Distribution of Cell Segments\n"
                          "z-axis index %i (of %i)" % (z_index+1, self.n_z))
        if leg_kwargs is not None:
            loc = leg_kwargs.pop('loc', 'best')
            if len(ax) == 1:
                ax[0].legend(loc=loc, **leg_kwargs)
            else:
                plt.figlegend(ax[0].lines, **leg_kwargs)
Example #28
0
	def plotPeriodic(self, measureTypes, yLabel=None, xAxis=None, yAxis=None):
		self.__checkMeasureTypes(self.__multipleMeasures, measureTypes)			
		self.__checkUnits(self.__multipleMeasures, measureTypes)

		plt.xlabel('time [s]')
		
		lines = []
		labels = []
			
		plt.grid(True)
		for measureType in measureTypes:			
			if not measureType in self.__multipleMeasures:
				print 'ERROR: Unknown measure %s' % measureType
				sys.exit()
			else:			
				name, units, results = self.__multipleMeasures[measureType]
				for result in results: 
					means, stds, times = result.getValues()
					relStdValues = result.getRelStdValues() 
					
					#print "X: ", x
					#print "Y: ", y
			
					measureName, measure, units = self.__getMeasureInfo(measureType)
			
					label = '%s (%s %s)' % (measureName, result.getTag(), name)
					
					self.__printPeriodicInfo(means, times, stds, relStdValues, label, '')
			
					line = plt.plot(times, means)
					
					if isinstance(measure, GenericAvgMeasure):
						#draw average line
						avgValues = [result.getMeanTotal()] * len(times)
						avgLine = plt.plot(times, avgValues)
						avgLabel = 'Avg. of %s: %s %s' % (measureName, result.getMeanTotal(), units)
						lines.append(avgLine)
						labels.append(avgLabel)
					else:
						label += '\nTotal: %s %s' % (result.getMeanTotal(), units)
						
					lines.append(line)
					labels.append(label)
		
		if not yLabel is None:
			plt.ylabel(yLabel)
		else:
			plt.ylabel(units) 
			
		self.__setAxis(plt, xAxis, yAxis, (min(times), max(times)))
		
		plt.figlegend(lines, labels, 'upper right')  
Example #29
0
def plotPCA(proj3D, X_r, PCs, ligs, colors, csvPath, save_flag):
    """
    Plot the PCA data on 2D plot
    """

    # Main figure
    fig = plt.figure(figsize=(13, 12), dpi=100)

    if proj3D:
        ax = fig.add_subplot(111, projection="3d")
        for label, col, x, y, z in zip(ligs, colors,
                                       X_r[:, 0], X_r[:, 1], X_r[:, 2]):
            newCol = makeColor(col)
            Axes3D.scatter(ax, x, y, z, label=label, color=newCol,
                           marker="o", lw=1, s=800)
        ax.set_xlabel("PC1 (" + '{0:g}'.format(PCs[0]) + " %)", fontsize=30)
        ax.set_ylabel("PC2 (" + '{0:g}'.format(PCs[1]) + " %)", fontsize=30)
        ax.set_zlabel("PC3 (" + '{0:g}'.format(PCs[2]) + " %)", fontsize=30)
        ax.tick_params(axis="both", which="major", labelsize=20)
        pngPath = csvPath.replace(".csv", "_3D.png")
    else:
        ax = fig.add_subplot(111)
        for label, col, x, y in zip(ligs, colors, X_r[:, 0], X_r[:, 1]):
            newCol = makeColor(col)
            ax.scatter(x, y, label=label, color=newCol, marker="o", lw=1, s=800)
            # ax.annotate(label, xy=(x, y - 0.05), fontsize=10,
            #             ha='center', va='top')
        ax.set_xlabel("PC1 (" + '{0:g}'.format(PCs[0]) + " %)", fontsize=30)
        ax.set_ylabel("PC2 (" + '{0:g}'.format(PCs[1]) + " %)", fontsize=30)
        ax.tick_params(axis="both", which="major", labelsize=30)
        pngPath = csvPath.replace(".csv", "_2D.png")

    # figTitle = "PCA on " + csvPath + " (PC1=" + pcVals[0] + ", PC2=" +
    # pcVals[1] + ")"
    # ax.text(0.5, 1.04, figTitle, horizontalalignment="center", fontsize=30,
    #         transform=ax.transAxes)

    # Legend figure
    fig_legend = plt.figure(figsize=(13, 12), dpi=100)
    plt.figlegend(*ax.get_legend_handles_labels(), scatterpoints=1,
                  loc="center", fancybox=True,
                  shadow=True, prop={"size": 30})

    # Save figures if save flag was used
    if save_flag:
        print("\nSAVING figures\n")
        fig.savefig(pngPath, bbox_inches="tight")
        fig_legend.savefig(pngPath.replace(".png", "_legend.png"))
    # Otherwise show the plots
    else:
        print("\nSHOWING figures\n")
        plt.show()
Example #30
0
def pltcscan(series):
    cmodes = sorted(series)
    f = plt.figure(1)
    plt.clf()
    lines = {}
    i = 0
    for i, s in enumerate(cmodes):
        ser = series[s]
        lines["%s 1->2" % s] = plt.plot(ser[0], COLORS[i] + LSTYLES[0])
        lines["%s 2->1" % s] = plt.plot(ser[1], COLORS[i] + LSTYLES[1])
    n = sorted(lines)
    plt.figlegend([lines[k] for k in n], n, 'upper right')
    f.canvas.draw()
         0.5,
         r"Maximum Sensor Value (Noise)",
         ha='left',
         va='center',
         rotation='vertical',
         fontproperties=customfont)

# Legend
dummy = plt.Rectangle(
    (0, 0), 1, 1, facecolor=[0.3, 0.3, 0.3],
    alpha=0.1)  # fill_between is not matplotlib artist compatible
plt.figlegend([bar, reg_line, dummy], [
    r"Sample mean ($1\sigma$)", r"Regression line",
    r"Prediction band: {0}-RMSE (99.7 \%)".format(std_errors)
],
              loc='upper center',
              ncol=5,
              labelspacing=10.0,
              fancybox=True,
              shadow=False)

#fig.suptitle("Title centered above all subplots", fontsize=14)

#plt.show()

#plotname = "noise_threshold_matrix_%d" %matrixID
plotname = "noise_threshold_linear_regression"

fig.savefig(plotname + ".pdf", pad_inches=0, dpi=fig.dpi)  # pdf
fig.savefig(plotname + ".pgf", pad_inches=0, dpi=fig.dpi)  # pgf
plt.close(fig)
Example #32
0
plt.title(stage3, fontsize=12, x=0.1, fontweight='demi')

# Turn off axis lines and ticks of the big subplot
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.tick_params(labelcolor='w',
               top='off',
               bottom='off',
               left='off',
               right='off')

plt.suptitle(fig_title, fontsize=15, color='b')
plt.figlegend((wakesal_fig, wakeivm_fig), (condition1, condition2),
              loc='upper right',
              fontsize=10,
              frameon=False)
ax.set_xlabel('time (hours)', fontsize=14)
ax.set_ylabel('% time spent in stage', fontsize=14)
plt.figtext(
    0.1, 0.02,
    str(condition1) + ' at ' + str(stamp1[0]) + ', ' + str(condition2) +
    ' at ' + str(stamp2[0]))
plt.tight_layout()

#plt.errorbar(t, mean_y1, yerr = st.plt.xlabel('Time of day (hours)')sem(sorted_values, axis = 0), fmt = 'b-')
#plt.errorbar(t, mean_y2, yerr = st.sem(sorted_values1, axis =0), fmt = 'r')

plt.hold
Example #33
0
	for line in file1:
	    variance.append(float(line))
	file1.close()


	[coeffs, xv, yv] = findpowerlaw(bins,count)
	power.append(coeffs[1])

	plt.figure(1)
	handl, = plt.plot(bins[0:plotmax],count[0:plotmax])
	handles.append(handl)
	plt.figure(2)
	handles2, =plt.plot(variance)
	handlesinit.append(handles2)

plt.figure(1)
plt.xlabel('Money')
plt.ylabel('Count')
plt.figlegend(handles,('$norm = 0.03$','$norm = 0.3$','$norm = 3$','$norm = 30$'),'upper right')
plt.savefig("norm.png")
plt.close()

plt.figure(2)
plt.xlabel('Runs')
plt.ylabel('Variance of the wealth distribution')
plt.figlegend(handlesinit,('$norm = 0.03$','$norm = 0.3$','$norm = 3$','$norm = 30$'),'upper right')
plt.savefig('norminit.png')
plt.close()


Example #34
0
			pop[0].currentImage.save(name, "PNG")
		
		#estrutura auxiliar para fazer o grafico
		fit = []
		for i in pop:
			fit.append(i.fitness)
		lista[0].append(pop[0].fitness)
		lista[1].append(np.mean(fit))

	return pop, lista

if __name__ == '__main__':
	h1 = Image.open(IMG_NAME).convert("RGB")
	h1 = h1.resize((200, 200))

	pop = []
	pop = initPop(h1)

	x, lista = evolve(pop, h1)
	x[0].currentImage.save(RESULT_NAME + "f" + str(round(x[0].fitness, 3)) + ".png", "PNG")
	x[0].currentImage.show()
	

	#faz o grafico de fitnessxgeracao, melhor e media da populacao
	plt.suptitle(RESULT_NAME)
	plt.xlabel("Geracao")
	plt.ylabel("Fitnes")
	leg1, leg2 = plt.plot(lista[0], "r--", lista[1], "g--")
	plt.figlegend((leg1, leg2), ("Melhor", "Media"), "upper right")
	plt.show()
Example #35
0
def visualise_results_by_agent(results, target_score,
                               file_to_save_results_graph):
    """Visualises the results of an agent playing"""

    agents = results.keys()

    fig, axes = plt.subplots(1, 2, sharex=False,
                             figsize=(14, 9))  # plt.subplots()

    lines = []

    for agent_name in agents:

        rolling_scores = results[agent_name][1]

        lines.append(rolling_scores)

        episodes_seen = len(rolling_scores)

        time_taken = results[agent_name][2]
        starting_point = time_taken / len(rolling_scores)
        time_axes = [
            starting_point * (t + 1.0) for t in range(len(rolling_scores))
        ]

        axes[0].plot(range(episodes_seen), rolling_scores)
        axes[1].plot(time_axes, rolling_scores)

    max_episodes_seen_by_any_agent = max([
        len(rolling_scores) for rolling_scores in
        [results[agent_name][1] for agent_name in agents]
    ])
    max_time_taken_by_any_agent = max(
        [results[agent_name][2] for agent_name in agents])

    min_score_achieved_by_any_agent = min([
        min(rolling_scores) for rolling_scores in
        [results[agent_name][1] for agent_name in agents]
    ])

    draw_horizontal_line_with_label(axes[0],
                                    y_value=target_score,
                                    x_min=0,
                                    x_max=max_episodes_seen_by_any_agent *
                                    1.02,
                                    label="Target \n score")
    draw_horizontal_line_with_label(axes[1],
                                    y_value=target_score,
                                    x_min=0,
                                    x_max=max_time_taken_by_any_agent * 1.02,
                                    label="Target \n score")

    hide_spines(axes[0], ['right', 'top'])
    hide_spines(axes[1], ['right', 'top'])

    set_graph_axis_limits(axes[0], 0, max_episodes_seen_by_any_agent,
                          min_score_achieved_by_any_agent, target_score)
    set_graph_axis_limits(axes[1], 0, max_time_taken_by_any_agent,
                          min_score_achieved_by_any_agent, target_score)

    plt.figlegend(lines,
                  labels=agents,
                  loc='lower center',
                  ncol=3,
                  labelspacing=0.)

    axes[0].set_title("Score vs. Episodes Played", y=1.03, fontweight='bold')
    axes[1].set_title("Score vs. Time Elapsed", y=1.03, fontweight='bold')

    set_graph_labels(axes[0],
                     xlabel='Rolling Episode Scores',
                     ylabel='Episode number')
    set_graph_labels(axes[1],
                     xlabel='Rolling Episode Scores',
                     ylabel='Time in Seconds')

    if file_to_save_results_graph is not None:
        plt.savefig(file_to_save_results_graph, bbox_inches="tight")
    plt.show()
Example #36
0
            label = round(
                dataFrameArrayCProbSum[voltage_array.index(xy[0])][0][o] * 100,
                2)
            ax.annotate('%s' % label, xy=xy, textcoords='data', fontsize=17)
        ax.set_ylim(0, np.amax(dcFractionSumArray) + 0.5)
        ax.set_ylabel("$\epsilon (V) / \sqrt{P_{DC}} $", fontsize=20)
        ax.set_xlabel("$U_{set} [mV]$", fontsize=20)
        ax.tick_params(axis='y', which='major', labelsize=17)
        ax.tick_params(axis='y', which='minor', labelsize=17)
        ax.tick_params(axis='x', which='major', labelsize=17)
        ax.tick_params(axis='x', which='minor', labelsize=17)
    #	ax.set_title("Sum Channel",fontsize=13)

#plt.figlegend( lines,labels=labels,loc = 'lower left', labelspacing=2.,prop={'size': 13})
plt.figlegend(lines2,
              labels=labels2,
              loc='lower left',
              labelspacing=0.1,
              prop={'size': 15})

##fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
#ax2.plot(x, z)
#ax3.plot(x, -z)

#print(dcFractionArray)
#plt.subplots_adjust(left=0.08, right=0.97, top=0.85, bottom=0.06, hspace=0.48, wspace=0.23)
#fig0.suptitle("Significance")
plt.show()

#ax0[1,0].plot([1, 2, 3, 4])
Example #37
0
def plot_data(tempo_results,
              xkey,
              ykey,
              interactive=True,
              mark_peri=False,
              show_legend=True):
    subplot = 1
    numsubplots = 2
    global axes
    axes = []
    global ax_types
    ax_types = []
    global ax_phase_wraps
    ax_phase_wraps = []
    global ax_jump_ranges
    ax_jump_ranges = []
    handles = []
    labels = []

    for usepostfit in [False, True]:  # Always use pre, then post
        TOAcount = 0
        # All subplots are in a single column
        if subplot == 1:
            axes.append(plt.subplot(numsubplots, 1, subplot))
        else:
            axes.append(plt.subplot(numsubplots, 1, subplot, sharex=axes[0]))

        if usepostfit:
            ax_types.append('post')
        else:
            ax_types.append('pre')

        ax_phase_wraps.append([])
        ax_jump_ranges.append([])

        # set tick formatter to not use scientific notation or an offset
        tick_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
        tick_formatter.set_scientific(False)
        axes[-1].xaxis.set_major_formatter(tick_formatter)

        xmin, xmax = axes[0].get_xlim()

        for ii, (lo, hi) in enumerate(tempo_results.freqbands):
            freq_label = get_freq_label(lo, hi)
            resids = tempo_results.residuals[freq_label]

            xlabel, xdata = resids.get_xdata(xkey)
            ylabel, ydata, yerr = resids.get_ydata(ykey, usepostfit,
                                                   tempo_results.phase_wraps)
            if len(xdata):
                # Plot the residuals
                handle = plt.errorbar(xdata, ydata, yerr=yerr, fmt='.', \
                                      label=freq_label, picker=5,
                                      c=colors[len(tempo_results.freqbands)][ii])

                if subplot == 1:
                    handles.append(handle[0])
                    labels.append(freq_label)
                TOAcount += xdata.size

        # Plot phase wraps
        text_offset = offset_copy(axes[-1].transData, x=5, y=-10, units='dots')
        if usepostfit:
            pw = tempo_results.phase_wraps
        elif tempo_history.current_index > 0:
            pw = tempo_history.tempo_results[tempo_history.current_index -
                                             1].phase_wraps
        else:
            pw = []
        for wrap_index in pw:
            wrap_mjd_hi = tempo_results.ordered_MJDs[wrap_index]
            if wrap_index > 0:
                wrap_mjd_lo = tempo_results.ordered_MJDs[wrap_index - 1]
            else:
                wrap_mjd_lo = wrap_mjd_hi
            if xkey == 'mjd':
                wrap_x = 0.5 * (wrap_mjd_hi + wrap_mjd_lo)
            elif xkey == 'year':
                wrap_x = mjd_to_year(0.5 * (wrap_mjd_hi + wrap_mjd_lo))
            elif xkey == 'numtoa':
                wrap_x = wrap_index - 0.5
            else:
                break
            wrap_color = {'pre': 'pink', 'post': 'red'}
            wrp = plt.axvline(wrap_x,
                              ls=':',
                              label='_nolegend_',
                              color=wrap_color[ax_types[-1]],
                              lw=1.5)
            wrp_txt = plt.text(wrap_x,
                               axes[-1].get_ylim()[1],
                               "%+d" % pw[wrap_index],
                               transform=text_offset,
                               size='x-small',
                               color=wrap_color[ax_types[-1]])
            ax_phase_wraps[-1].append([wrp, wrp_txt])

        # set up span selector for setting new jump ranges
        options.jump_spans[ax_types[-1]] = SpanSelector(
            axes[-1],
            select_jump_range,
            'horizontal',
            useblit=True,
            rectprops=dict(alpha=0.5, facecolor='orange'))
        options.jump_spans[ax_types[-1]].visible = options.jump_mode

        if subplot > 1:
            axes[0].set_xlim((xmin, xmax))

        # Finish off the plot
        plt.axhline(0, ls='--', label="_nolegend_", c='k', lw=0.5)
        axes[-1].ticklabel_format(style='plain', axis='x')

        if mark_peri and hasattr(tempo_results.outpar, 'BINARY'):
            # Be sure to check if pulsar is in a binary
            # Cannot mark passage of periastron if not a binary
            if usepostfit:
                binpsr = binary_psr.binary_psr(tempo_results.outpar.FILE)
            else:
                binpsr = binary_psr.binary_psr(tempo_results.inpar.FILE)
            xmin, xmax = axes[0].get_xlim()
            mjd_min = tempo_results.min_TOA
            mjd_max = tempo_results.max_TOA
            guess_mjds = np.arange(mjd_max + binpsr.par.PB, \
                                mjd_min - binpsr.par.PB, -binpsr.par.PB)
            for mjd in guess_mjds:
                peri_mjd = binpsr.most_recent_peri(float(mjd))
                if xkey == 'mjd':
                    plt.axvline(peri_mjd,
                                ls=':',
                                label='_nolegend_',
                                c='k',
                                lw=0.5)
                elif xkey == 'year':
                    print "plotting peri passage"
                    plt.axvline(mjd_to_year(peri_mjd),
                                ls=':',
                                label='_nolegend_',
                                c='k',
                                lw=0.5)
            axes[0].set_xlim((xmin, xmax))
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        subplot += 1

    # Plot jump ranges
    for jstart, jend in tempo_results.jump_ranges:
        plot_jump_range((jstart, jend))
#        axes[-1].set_ylim((ymin, ymax))

    if numsubplots > 1:
        # Increase spacing between subplots.
        plt.subplots_adjust(hspace=0.25)

    # Write name of input files used for timing on figure
    if interactive:
        fntext = "Solution %d of %d, TOA file: %s, Parameter file: %s" % \
          (tempo_history.current_index+1, tempo_history.get_nsolutions(),
           tempo_results.intimfn, tempo_results.inparfn)
        figure_text = plt.figtext(0.01,
                                  0.01,
                                  fntext,
                                  verticalalignment='bottom',
                                  horizontalalignment='left')

# Make the legend and set its visibility state
    leg = plt.figlegend(handles, labels, 'upper right')
    leg.set_visible(show_legend)
    leg.legendPatch.set_alpha(0.5)
    axes[0].xaxis.tick_top()
    plt.setp(axes[0].get_yticklabels()[0], visible=False)
    plt.setp(axes[1].get_yticklabels()[-1], visible=False)
    plt.setp(axes[0].get_yticklabels()[-1], visible=False)
    plt.setp(axes[1].get_yticklabels()[0], visible=False)
    plt.subplots_adjust(wspace=0.05,
                        hspace=0.0,
                        left=0.15,
                        bottom=0.1,
                        right=0.8,
                        top=0.9)

    nms = []
    fitmes = []
    for b in tempo_history.get_parfile():
        if tempo_history.get_parfile()[b].fit == None:
            tempo_history.get_parfile()[b].fit = 0
        if not any(b in s for s in tempy_io.no_fit_pars):
            nms.append(b)
            fitmes.append(tempo_history.get_parfile()[b].fit)
    rax = plt.axes([0.85, 0.1, 0.1, 0.8])
    rax.set_frame_on(False)
    options.fitcheck = CheckButtons(rax, nms, fitmes)
    options.fitcheck.on_clicked(update_fit_flag)
    redrawplot()
Example #38
0
def plot_line(x, y):
	plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))

numbers = [1000003, 2000003, 4000037, 8000009, 16000057, 32000011, 64000031, 128000003, 256000001, 512000009, 1024000009,2048000011]


partie1_pire_cas = 6 * np.array(numbers) - 6
partie1_millieur_cas = [6,6,6,6,6,6,6,6,6,6,6,6]

plt.title('Pire cas VS Millieur cas')
line1, = plt.plot(numbers, partie1_millieur_cas, 'go')
line2, = plt.plot(numbers, partie1_pire_cas, 'ro')
plot_line(numbers, partie1_millieur_cas)
plot_line(numbers, partie1_pire_cas)
plt.figlegend((line1, line2), ('millieur', 'pire'), 'upper left')
plt.xlabel('nombre')
plt.ylabel('temps')
plt.savefig('Pire cas VS Millieur cas.png')
plt.clf()
#plt.show()


partie1 = [0.017629, 0.020659, 0.040898, 0.081364, 0.162702, 0.327618, 0.653843, 1.319670, 2.627742, 5.220003, 10.406829, 20.833496]

plt.title('Algorithme1')
plt.plot(numbers, partie1, 'bo')
plot_line(numbers, partie1)
plt.xlabel('nombre')
plt.ylabel('temps')
plt.savefig('Algorithme1')
Example #39
0
def test_all():

    if pdf_output:
        from matplotlib.backends.backend_pdf import PdfPages
        pdf = PdfPages("test_dotplot.pdf")
    else:
        pdf = None

    # Basic dotplot with points only
    plt.clf()
    points = range(20)
    ax = plt.axes()
    fig = dot_plot(points, ax=ax)
    ax.set_title("Basic horizontal dotplot")
    close_or_save(pdf, fig)

    # Basic vertical dotplot
    plt.clf()
    points = range(20)
    ax = plt.axes()
    fig = dot_plot(points, ax=ax, horizontal=False)
    ax.set_title("Basic vertical dotplot")
    close_or_save(pdf, fig)

    # Tall and skinny
    plt.figure(figsize=(4,12))
    ax = plt.axes()
    vals = np.arange(40)
    fig = dot_plot(points, ax=ax)
    ax.set_title("Tall and skinny dotplot")
    ax.set_xlabel("x axis label")
    close_or_save(pdf, fig)

    # Short and wide
    plt.figure(figsize=(12,4))
    ax = plt.axes()
    vals = np.arange(40)
    fig = dot_plot(points, ax=ax, horizontal=False)
    ax.set_title("Short and wide dotplot")
    ax.set_ylabel("y axis label")
    close_or_save(pdf, fig)

    # Tall and skinny striped dotplot
    plt.figure(figsize=(4,12))
    ax = plt.axes()
    points = np.arange(40)
    fig = dot_plot(points, ax=ax, striped=True)
    ax.set_title("Tall and skinny striped dotplot")
    ax.set_xlim(-10, 50)
    close_or_save(pdf, fig)

    # Short and wide striped
    plt.figure(figsize=(12,4))
    ax = plt.axes()
    points = np.arange(40)
    fig = dot_plot(points, ax=ax, striped=True, horizontal=False)
    ax.set_title("Short and wide striped dotplot")
    ax.set_ylim(-10, 50)
    close_or_save(pdf, fig)

    # Basic dotplot with few points
    plt.figure()
    ax = plt.axes()
    points = np.arange(4)
    fig = dot_plot(points, ax=ax)
    ax.set_title("Basic horizontal dotplot with few lines")
    close_or_save(pdf, fig)

    # Basic dotplot with few points
    plt.figure()
    ax = plt.axes()
    points = np.arange(4)
    fig = dot_plot(points, ax=ax, horizontal=False)
    ax.set_title("Basic vertical dotplot with few lines")
    close_or_save(pdf, fig)

    # Manually set the x axis limits
    plt.figure()
    ax = plt.axes()
    points = np.arange(20)
    fig = dot_plot(points, ax=ax)
    ax.set_xlim(-10, 30)
    ax.set_title("Dotplot with adjusted horizontal range")
    close_or_save(pdf, fig)

    # Left row labels
    plt.clf()
    ax = plt.axes()
    lines = ["ABCDEFGH"[np.random.randint(0, 8)] for k in range(20)]
    points = np.random.normal(size=20)
    fig = dot_plot(points, lines=lines, ax=ax)
    ax.set_title("Dotplot with user-supplied labels in the left margin")
    close_or_save(pdf, fig)

    # Left and right row labels
    plt.clf()
    ax = plt.axes()
    points = np.random.normal(size=20)
    lines = ["ABCDEFGH"[np.random.randint(0, 8)] + "::" + str(k+1)
             for k in range(20)]
    fig = dot_plot(points, lines=lines, ax=ax, split_names="::")
    ax.set_title("Dotplot with user-supplied labels in both margins")
    close_or_save(pdf, fig)

    # Both sides row labels
    plt.clf()
    ax = plt.axes([0.1, 0.1, 0.88, 0.8])
    points = np.random.normal(size=20)
    lines = ["ABCDEFGH"[np.random.randint(0, 8)] + "::" + str(k+1)
             for k in range(20)]
    fig = dot_plot(points, lines=lines, ax=ax, split_names="::",
            horizontal=False)
    txt = ax.set_title("Vertical dotplot with user-supplied labels in both margins")
    txt.set_position((0.5, 1.06))
    close_or_save(pdf, fig)

    # Custom colors and symbols
    plt.clf()
    ax = plt.axes([0.1, 0.07, 0.78, 0.85])
    points = np.random.normal(size=20)
    lines = np.kron(range(5), np.ones(4)).astype(np.int32)
    styles = np.kron(np.ones(5), range(4)).astype(np.int32)
    #marker_props = {k: {"color": "rgbc"[k], "marker": "osvp"[k],
    #                    "ms": 7, "alpha": 0.6} for k in range(4)}
    # python 2.6 compat, can be removed later
    marker_props = dict((k, {"color": "rgbc"[k], "marker": "osvp"[k],
                        "ms": 7, "alpha": 0.6}) for k in range(4))
    fig = dot_plot(points, lines=lines, styles=styles, ax=ax,
            marker_props=marker_props)
    ax.set_title("Dotplot with custom colors and symbols")
    close_or_save(pdf, fig)

    # Basic dotplot with symmetric intervals
    plt.clf()
    ax = plt.axes()
    points = range(20)
    fig = dot_plot(points, intervals=np.ones(20), ax=ax)
    ax.set_title("Dotplot with symmetric intervals")
    close_or_save(pdf, fig)

    # Basic dotplot with symmetric intervals, pandas inputs.
    plt.clf()
    ax = plt.axes()
    points = pd.Series(range(20))
    intervals = pd.Series(np.ones(20))
    fig = dot_plot(points, intervals=intervals, ax=ax)
    ax.set_title("Dotplot with symmetric intervals (Pandas inputs)")
    close_or_save(pdf, fig)

    # Basic dotplot with nonsymmetric intervals
    plt.clf()
    ax = plt.axes()
    points = np.arange(20)
    intervals = [(1, 3) for i in range(20)]
    fig = dot_plot(points, intervals=intervals, ax=ax)
    ax.set_title("Dotplot with nonsymmetric intervals")
    close_or_save(pdf, fig)

    # Vertical dotplot with nonsymmetric intervals
    plt.clf()
    ax = plt.axes()
    points = np.arange(20)
    intervals = [(1, 3) for i in range(20)]
    fig = dot_plot(points, intervals=intervals, ax=ax, horizontal=False)
    ax.set_title("Vertical dotplot with nonsymmetric intervals")
    close_or_save(pdf, fig)

    # Dotplot with nonsymmetric intervals, adjust line properties
    plt.clf()
    ax = plt.axes()
    points = np.arange(20)
    intervals = [(1, 3) for x in range(20)]
    line_props = {0: {"color": "lightgrey",
                      "solid_capstyle": "round"}}
    fig = dot_plot(points, intervals=intervals, line_props=line_props, ax=ax)
    ax.set_title("Dotplot with custom line properties")
    close_or_save(pdf, fig)

    # Dotplot with two points per line and a legend
    plt.clf()
    ax = plt.axes([0.1, 0.1, 0.75, 0.8])
    points = 5*np.random.normal(size=40)
    lines = np.kron(range(20), (1,1))
    intervals = [(1,3) for k in range(40)]
    styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
    styles = [["Cat", "Dog"][i] for i in styles]
    fig = dot_plot(points, intervals=intervals, lines=lines, styles=styles,
            ax=ax, stacked=True)
    handles, labels = ax.get_legend_handles_labels()
    leg = plt.figlegend(handles, labels, "center right", numpoints=1,
                        handletextpad=0.0001)
    leg.draw_frame(False)
    ax.set_title("Dotplot with two points per line")
    close_or_save(pdf, fig)

    # Dotplot with two points per line and a legend
    plt.clf()
    ax = plt.axes([0.1, 0.1, 0.75, 0.8])
    fig = dot_plot(points, intervals=intervals, lines=lines,
                  styles=styles, ax=ax, stacked=True,
                  styles_order=["Dog", "Cat"])
    handles, labels = ax.get_legend_handles_labels()
    leg = plt.figlegend(handles, labels, "center right", numpoints=1,
                        handletextpad=0.0001)
    leg.draw_frame(False)
    ax.set_title("Dotplot with two points per line (reverse order)")
    close_or_save(pdf, fig)

    # Vertical dotplot with two points per line and a legend
    plt.clf()
    ax = plt.axes([0.1, 0.1, 0.75, 0.8])
    points = 5*np.random.normal(size=40)
    lines = np.kron(range(20), (1,1))
    intervals = [(1,3) for k in range(40)]
    styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
    styles = [["Cat", "Dog"][i] for i in styles]
    fig = dot_plot(points, intervals=intervals, lines=lines, styles=styles,
            ax=ax, stacked=True, horizontal=False)
    handles, labels = ax.get_legend_handles_labels()
    leg = plt.figlegend(handles, labels, "center right", numpoints=1,
                        handletextpad=0.0001)
    leg.draw_frame(False)
    ax.set_title("Vertical dotplot with two points per line")
    close_or_save(pdf, fig)

    # Vertical dotplot with two points per line and a legend
    plt.clf()
    ax = plt.axes([0.1, 0.1, 0.75, 0.8])
    styles_order = ["Dog", "Cat"]
    fig = dot_plot(points, intervals=intervals, lines=lines,
                  styles=styles, ax=ax, stacked=True,
                  horizontal=False, styles_order=styles_order)
    handles, labels = ax.get_legend_handles_labels()
    lh = dict(zip(labels, handles))
    handles = [lh[l] for l in styles_order]
    leg = plt.figlegend(handles, styles_order, "center right", numpoints=1,
                        handletextpad=0.0001)
    leg.draw_frame(False)
    ax.set_title("Vertical dotplot with two points per line (reverse order)")
    close_or_save(pdf, fig)

    # Vertical dotplot with two points per line and a legend
    plt.clf()
    ax = plt.axes([0.1, 0.1, 0.75, 0.8])
    points = 5*np.random.normal(size=40)
    lines = np.kron(range(20), (1,1))
    intervals = [(1,3) for k in range(40)]
    styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
    styles = [["Cat", "Dog"][i] for i in styles]
    fig = dot_plot(points, intervals=intervals, lines=lines, styles=styles,
            ax=ax, stacked=True, striped=True, horizontal=False)
    handles, labels = ax.get_legend_handles_labels()
    leg = plt.figlegend(handles, labels, "center right", numpoints=1,
                        handletextpad=0.0001)
    leg.draw_frame(False)
    plt.ylim(-20, 20)
    ax.set_title("Vertical dotplot with two points per line")
    close_or_save(pdf, fig)

    # Dotplot with color-matched points and intervals
    plt.clf()
    ax = plt.axes([0.1, 0.1, 0.75, 0.8])
    points = 5*np.random.normal(size=40)
    lines = np.kron(range(20), (1,1))
    intervals = [(1,3) for k in range(40)]
    styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
    styles = [["Cat", "Dog"][i] for i in styles]
    marker_props = {"Cat": {"color": "orange"},
                    "Dog": {"color": "purple"}}
    line_props = {"Cat": {"color": "orange"},
                  "Dog": {"color": "purple"}}
    fig = dot_plot(points, intervals=intervals, lines=lines, styles=styles,
            ax=ax, stacked=True, marker_props=marker_props,
            line_props=line_props)
    handles, labels = ax.get_legend_handles_labels()
    leg = plt.figlegend(handles, labels, "center right", numpoints=1,
                        handletextpad=0.0001)
    leg.draw_frame(False)
    ax.set_title("Dotplot with color-matched points and intervals")
    close_or_save(pdf, fig)

    # Dotplot with color-matched points and intervals
    plt.clf()
    ax = plt.axes([0.1, 0.1, 0.75, 0.8])
    points = 5*np.random.normal(size=40)
    lines = np.kron(range(20), (1,1))
    intervals = [(1,3) for k in range(40)]
    styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
    styles = [["Cat", "Dog"][i] for i in styles]
    marker_props = {"Cat": {"color": "orange"},
                    "Dog": {"color": "purple"}}
    line_props = {"Cat": {"color": "orange"},
                  "Dog": {"color": "purple"}}
    fig = dot_plot(points, intervals=intervals, lines=lines, styles=styles,
            ax=ax, stacked=True, marker_props=marker_props,
            line_props=line_props, horizontal=False)
    handles, labels = ax.get_legend_handles_labels()
    leg = plt.figlegend(handles, labels, "center right", numpoints=1,
                        handletextpad=0.0001)
    leg.draw_frame(False)
    ax.set_title("Dotplot with color-matched points and intervals")
    close_or_save(pdf, fig)

    # Dotplot with sections
    plt.clf()
    ax = plt.axes()
    points = range(30)
    lines = np.kron(range(15), (1,1)).astype(np.int32)
    styles = np.kron(np.ones(15), (0,1)).astype(np.int32)
    sections = np.kron((0,1,2), np.ones(10)).astype(np.int32)
    sections = [["Axx", "Byy", "Czz"][k] for k in sections]
    fig = dot_plot(points, lines=lines, styles=styles, sections=sections, ax=ax)
    ax.set_title("Dotplot with sections")
    close_or_save(pdf, fig)

    # Vertical dotplot with sections
    plt.clf()
    ax = plt.axes([0.1,0.1,0.9,0.75])
    points = range(30)
    lines = np.kron(range(15), (1,1)).astype(np.int32)
    styles = np.kron(np.ones(15), (0,1)).astype(np.int32)
    sections = np.kron((0,1,2), np.ones(10)).astype(np.int32)
    sections = [["Axx", "Byy", "Czz"][k] for k in sections]
    fig = dot_plot(points, lines=lines, styles=styles,
                  sections=sections, ax=ax, horizontal=False)
    txt = ax.set_title("Vertical dotplot with sections")
    txt.set_position((0.5, 1.08))
    close_or_save(pdf, fig)

    # Reorder sections
    plt.clf()
    ax = plt.axes()
    points = range(30)
    lines = np.kron(range(15), (1,1)).astype(np.int32)
    styles = np.kron(np.ones(15), (0,1)).astype(np.int32)
    sections = np.kron((0,1,2), np.ones(10)).astype(np.int32)
    sections = [["Axx", "Byy", "Czz"][k] for k in sections]
    fig = dot_plot(points, lines=lines, styles=styles, sections=sections, ax=ax,
            section_order=["Byy", "Axx", "Czz"])
    ax.set_title("Dotplot with sections in specified order")
    close_or_save(pdf, fig)

    # Reorder the lines.
    plt.figure()
    ax = plt.axes()
    points = np.arange(4)
    lines = ["A", "B", "C", "D"]
    line_order = ["B", "C", "A", "D"]
    fig = dot_plot(points, lines=lines, line_order=line_order, ax=ax)
    ax.set_title("Dotplot with reordered lines")
    close_or_save(pdf, fig)

    # Format labels
    plt.clf()
    points = range(20)
    lines = ["%d::%d" % (i, 100+i) for i in range(20)]
    fmt_left = lambda x : "lft_" + x
    fmt_right = lambda x : "rgt_" + x
    ax = plt.axes()
    fig = dot_plot(points, lines=lines, ax=ax, split_names="::",
                   fmt_left_name=fmt_left, fmt_right_name=fmt_right)
    ax.set_title("Horizontal dotplot with name formatting")
    close_or_save(pdf, fig)

    # Right names only
    plt.clf()
    points = range(20)
    lines = ["%d::%d" % (i, 100+i) for i in range(20)]
    ax = plt.axes()
    fig = dot_plot(points, lines=lines, ax=ax, split_names="::",
                   show_names="right")
    ax.set_title("Show right names only")
    close_or_save(pdf, fig)

    # Dotplot with different numbers of points per line
    plt.clf()
    ax = plt.axes([0.1, 0.1, 0.75, 0.8])
    points = 5*np.random.normal(size=40)
    lines = []
    ii = 0
    while len(lines) < 40:
        for k in range(np.random.randint(1, 4)):
            lines.append(ii)
        ii += 1
    styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
    styles = [["Cat", "Dog"][i] for i in styles]
    fig = dot_plot(points, lines=lines, styles=styles,
            ax=ax, stacked=True)
    handles, labels = ax.get_legend_handles_labels()
    leg = plt.figlegend(handles, labels, "center right", numpoints=1,
                        handletextpad=0.0001)
    leg.draw_frame(False)
    ax.set_title("Dotplot with different numbers of points per line")
    close_or_save(pdf, fig)

    if pdf_output:
        pdf.close()
    plt.close('all')
Example #40
0
    def on_event(self, event):
        """
            Some keyboard events for testing purposes (not used during training)
        """

        if event.type == pygame.QUIT:
            self._running = False
            quit()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                # PAUSE
                if self._paused:
                    # Unpause the simulation
                    self._paused = False
                else:
                    # When simulation is paused, a plot of the errors is shown to the user

                    # Transpose the error matrices to plot more easily
                    beacon_error = np.transpose(self.delta_beacon)
                    kalman_error = np.transpose(self.delta_kalman)
                    odometry_error = np.transpose(self.delta_odometry)

                    # Find out how many measurements
                    x = np.linspace(1, len(beacon_error[0]),
                                    len(beacon_error[0]))

                    plt.figure()
                    plt.title("Deviation from actual pose")

                    # Plot the X errors
                    plt.subplot(3, 1, 1)
                    plt.plot(x,
                             beacon_error[0],
                             '-',
                             x,
                             kalman_error[0],
                             '-',
                             x,
                             odometry_error[0],
                             '-',
                             linewidth=2)
                    plt.ylabel('X-coordinate')

                    # Plot the Y errors
                    plt.subplot(3, 1, 2)
                    plt.plot(x,
                             beacon_error[1],
                             '-',
                             x,
                             kalman_error[1],
                             '-',
                             x,
                             odometry_error[1],
                             '-',
                             linewidth=2)
                    plt.ylabel('Y-coordinate')

                    # Plot the angle errors
                    plt.subplot(3, 1, 3)
                    l1, l2, l3 = plt.plot(x,
                                          beacon_error[2],
                                          '-',
                                          x,
                                          kalman_error[2],
                                          '-',
                                          x,
                                          odometry_error[2],
                                          '-',
                                          linewidth=2)
                    plt.xlabel('number of elements')
                    plt.ylabel('Angle (degrees)')
                    plt.figlegend((l1, l2, l3),
                                  ('sensor', 'kalman filter', 'odometry'))

                    # Show the plot to the user
                    plt.show()

                    # Pause the simulation
                    self._paused = True

            if event.key == pygame.K_LEFT:
                self.robot.vel_left += self.velocity_base
            if event.key == pygame.K_RIGHT:
                self.robot.vel_left -= self.velocity_base
            if event.key == pygame.K_UP:
                self.robot.vel_right += self.velocity_base
            if event.key == pygame.K_DOWN:
                self.robot.vel_right -= self.velocity_base

            if self.robot.vel_left > self.velocity_max:
                self.robot.vel_left = self.velocity_max
            if self.robot.vel_right > self.velocity_max:
                self.robot.vel_right = self.velocity_max
            if self.robot.vel_left < self.velocity_min:
                self.robot.vel_left = self.velocity_min
            if self.robot.vel_right < self.velocity_min:
                self.robot.vel_right = self.velocity_min
Example #41
0
def plot(
    datasets,
    var_names,
    est_method=WidthEstimationMethod.MASS_WEIGHTED,
    figwidth=7.0,
    figlegend=None,
    line_colors="default",
    cumulant_scale_plot_lim=None,
):
    z = datasets[0].zt

    v1, v2 = var_names

    figheight = figwidth / 7.0 * 2.6

    fig, axes = plt.subplots(
        ncols=len(datasets) * 2,
        nrows=len(z),
        figsize=(figwidth * len(datasets), figheight * len(z)),
    )

    if line_colors == "default":
        line_colors = sns.color_palette(n_colors=len(datasets))
    else:
        assert len(line_colors) == len(datasets)

    loc_x = plticker.MultipleLocator(base=200)

    def sp(ds_, ax1, ax2, line_color, add_width_label_legend=False):
        cumulant_analysis.covariance_plot(ds_[v1],
                                          ds_[v2],
                                          log_scale=False,
                                          ax=ax1,
                                          line_color=line_color)
        ax1.set_title("")

        width_indicator = "floating_legend" if add_width_label_legend else "no_label"
        cumulant_analysis.covariance_direction_plot(
            ds_[v1],
            ds_[v2],
            ax=ax2,
            width_est_method=est_method,
            line_color=line_color,
            width_indicator=width_indicator,
        )
        ax2.set_title("")

        ax2.ticklabel_format(style="sci", axis="y", scilimits=(0, 0))
        ax2.get_legend().remove()
        ax2.xaxis.set_minor_locator(loc_x)
        ax2.axhline(0.0, linestyle="--", color="grey")

        ax2.grid(which="minor", axis="both", linestyle="--")
        if cumulant_scale_plot_lim is not None:
            ax2.set_xlim(cumulant_scale_plot_lim)
            ax1.set_xlim(2.5 * np.array(cumulant_scale_plot_lim) / 1.0e3)
            ax1.set_ylim(2.5 * np.array(cumulant_scale_plot_lim) / 1.0e3)

    # plot in order of decreasing height
    for n, z_ in enumerate(tqdm(z[::-1])):

        for n_d in range(len(datasets)):
            ds_ = datasets[n_d].sel(zt=z_).squeeze().rename(
                dict(xt="x", yt="y"))
            if n + 1 == len(z) and n_d + 1 == len(datasets):
                add_width_label_legend = True
            else:
                add_width_label_legend = False

            sp(
                ds_,
                axes[n, n_d * 2],
                axes[n, n_d * 2 + 1],
                line_color=line_colors[n_d],
                add_width_label_legend=add_width_label_legend,
            )

        # using fig.text instead of ax.text avoids matplotlib trying to scale
        # the subplot to fit the text
        fig.text(-0.6,
                 1.1,
                 "z={}m".format(z_.values),
                 transform=axes[n, 0].transAxes)

    for n_d in range(len(datasets)):
        ax = axes[0, n_d * 2]
        fig.text(
            1.7,
            1.4,
            datasets[n_d].name,
            transform=ax.transAxes,
            horizontalalignment="center",
        )

    fig.tight_layout()

    handles, labels = axes[0, 1].get_legend_handles_labels()
    labels = [label.split("=")[0].strip() + "$" for label in labels]
    labels = [
        f"{label}: principle dir."
        if r"{p}" in label else f"{label}: perpendicular dir."
        for label in labels
    ]
    if figlegend is True:
        plt.figlegend(
            handles,
            labels,
            loc="upper right",
            bbox_to_anchor=(1.0, 0.0),
            ncol=2,
        )

    return fig, axes
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("-c",
                        "--configuration",
                        required=True,
                        type=argparse.FileType("r"))
    parser.add_argument("--title", required=False, default="")
    parser.add_argument("--log", action="store_true", default=False)
    parser.add_argument(
        "--out",
        required=False,
        default=None,
        help=
        "Output file. If unspecified, the script will exit after printing the numbers."
    )
    parser.add_argument(
        "--genes",
        default=False,
        action="store_true",
        help=
        "Flag. If switched on, the gene level will be used instead of the transcript level."
    )
    parser.add_argument("-p",
                        "--procs",
                        default=multiprocessing.cpu_count(),
                        type=int)
    parser.add_argument("--transcripts", action="store_true", default=False)
    parser.add_argument("--division", action="store_true", default=False)
    # parser.add_argument("refmap", nargs=10, type=argparse.FileType("rt"))
    args = parser.parse_args()

    data = OrderedDict()

    options = parse_configuration(args.configuration)

    if options["colourmap"]["use"] is True:
        color_normalizer = matplotlib.colors.Normalize(0,
                                                       len(options["methods"]))
        color_map = cm.get_cmap(options["colourmap"]["name"])

    header = ["Method", "Division", "Fully", "Missed", "Fused"]
    print(*header, sep="\t")

    pool = multiprocessing.Pool(processes=args.procs)

    for label in options["methods"]:
        for aligner in options["divisions"]:
            if options["methods"][label][aligner] is not None:
                data[(label, aligner)] = [set(), set(), set()]
                orig_refmap = "{}.refmap".format(
                    re.sub(".stats$", "",
                           options["methods"][label][aligner][0]))
                with open(orig_refmap) as refmap:
                    for row in csv.DictReader(refmap, delimiter="\t"):
                        if args.genes is True:
                            if row["best_ccode"] in ("=", "_"):
                                data[(label, aligner)][0].add(row["ref_gene"])
                            elif row["best_ccode"][0] == "f":
                                data[(label, aligner)][2].add(row["ref_gene"])
                            # elif row["best_ccode"] in ("NA", "p", "P", "i", "I", "ri", "rI", "X", "x"):
                            #     data[(label, aligner)][1].add(row["ref_gene"])
                        else:
                            if row["ccode"] in ("=", "_"):
                                data[(label, aligner)][0].add(row["ref_id"])
                            elif row["ccode"][0] == "f":
                                data[(label, aligner)][2].add(row["ref_id"])
                filtered_refmap = "{}.refmap".format(
                    re.sub(".stats$", "",
                           options["methods"][label][aligner][1]))
                with open(filtered_refmap) as refmap:
                    for row in csv.DictReader(refmap, delimiter="\t"):
                        if args.genes is True:
                            if row["best_ccode"] in ("NA", "p", "P", "i", "I",
                                                     "ri", "rI", "X", "x"):
                                data[(label, aligner)][1].add(row["ref_gene"])
                        else:
                            if row["ccode"] in ("NA", "p", "P", "i", "I", "ri",
                                                "rI", "X", "x"):
                                data[(label, aligner)][1].add(row["ref_id"])
                for num in range(3):
                    data[(label, aligner)][num] = len(data[(label,
                                                            aligner)][num])
                orig_stats, filtered_stats = options["methods"][label][
                    aligner][:2]
            else:
                orig_stats, filtered_stats = None, None
            data[(label, aligner)] = pool.apply_async(
                parse_refmaps, (orig_stats, filtered_stats, args.transcripts))

    for label in options["methods"]:
        for aligner in options["divisions"]:
            data[(label, aligner)] = data[(label, aligner)].get()
            print(label, aligner, *data[(label, aligner)], sep="\t")

    # print(*data.items(), sep="\n")

    # Now print out the table

    if args.out is None:
        sys.exit(0)

    # divisions = sorted(options["divisions"].keys())

    if args.division is True:
        figsize = (14, 12)
    else:
        figsize = (6, 8)

    figure, axes = plt.subplots(nrows=1, ncols=3, dpi=300, figsize=figsize)
    figure.suptitle(args.title)

    handles = []
    labels = []

    factor = 10

    for pos, ax in enumerate(axes):
        ax.set_ylim(0, 2)
        max_x = max(data[_][pos] for _ in data) + 500
        min_x = max(0,
                    min(data[_][pos] for _ in data if data[_][pos] > 0) - 500)
        ax.set_ylim(min_x, max_x)
        if args.division is False:
            ax.set_xlim(0, 2.5)
        else:
            ax.set_xlim(-2, len(options["divisions"]) * factor)
        # ax.plot((1, max_x), (1, 1), 'k-')
        ax.tick_params(axis='both', which='major', labelsize=10)
        # ax.set_xticklabels([newticks[pos]], fontsize=15)
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)
        ax.spines["left"].set_visible(True)
        ax.spines["bottom"].set_visible(True)
        ax.tick_params(axis="y", left="on", right="off")
        if args.division is False:
            ax.tick_params(axis="x", top="off", bottom="off")
        else:
            ax.tick_params(axis="x", top="off", bottom="on")
        if pos == 0:
            if args.transcripts is True:
                ax.set_ylabel("Number of transcripts", fontsize=16)
            else:
                ax.set_ylabel("Number of genes", fontsize=16)
            ax.set_xlabel("Reconstructed\ngenes", fontsize=16)
        elif pos == 1:
            ax.set_xlabel("Missed\ngenes", fontsize=16)
        else:
            ax.set_xlabel("Fused\ngenes", fontsize=16)

        if args.division is True:
            ax.set_xticks([
                factor * (_ + 1 / 4) for _ in range(len(options["divisions"]))
            ])
            ax.set_xticklabels(options["divisions"], rotation=45, fontsize=14)

        if args.division is False:
            points = []
        else:
            points = defaultdict(list)

        for index, tup in enumerate(data.keys()):
            method, division = tup
            if options["colourmap"]["use"] is False:
                colour = options["methods"][method]["colour"]
                matched = re.match("\(([0-9]*), ([0-9]*), ([0-9]*)\)$", colour)
                if matched:
                    colour = "#{0:02x}{1:02x}{2:02x}".format(
                        clamp(int(matched.groups()[0])),
                        clamp(int(matched.groups()[1])),
                        clamp(int(matched.groups()[2])))
            elif options["methods"][method]["colour"] in ("black", "k"):
                colour = "black"
            else:
                colour = color_map(
                    color_normalizer(options["methods"][division]["index"]))

            marker = options["divisions"][division]["marker"]
            cat = "{} ({})".format(method, division)
            labels.append(cat)

            point = data[tup][pos]
            if args.division is False:
                points.append([point, cat, colour, marker])
            else:
                points[division].append([point, cat, colour, marker])

        if args.division is False:
            points = sorted(points, key=itemgetter(0))
            for index, point in enumerate(points):
                point, cat, colour, marker = point
                x_coord = 0.5 + (index % 4 / 2)
                handle = axes[pos].scatter(x_coord,
                                           point,
                                           alpha=1,
                                           label=cat,
                                           color=colour,
                                           marker=marker,
                                           edgecolor="k",
                                           s=150)
                handle.get_sketch_params()
                if pos == 0:
                    handles.append(handle)
                handle = mlines.Line2D([], [],
                                       markersize=5,
                                       color=colour,
                                       marker=marker,
                                       label=cat,
                                       alpha=0.6)
        else:

            max_last_xcoord = None

            for dindex, division in enumerate(options["divisions"].keys()):
                max_xcoord = -100
                min_xcoord = 100000
                dpoints = sorted(points[division], key=itemgetter(0))
                for index, point in enumerate(dpoints):
                    point, cat, colour, marker = point
                    if index % 3 == 0:
                        x_coord = factor * dindex
                    elif index % 3 == 2:
                        x_coord = factor * (dindex + 1 / 2)
                    else:
                        x_coord = factor * (dindex + 1 / 4)

                    max_xcoord = max(x_coord, max_xcoord)
                    min_xcoord = min(x_coord, min_xcoord)
                    # print(x_coord, point, cat)
                    handle = axes[pos].scatter(x_coord,
                                               point,
                                               alpha=1,
                                               label=cat,
                                               color=colour,
                                               marker=marker,
                                               edgecolor="k",
                                               s=150)
                    handle.get_sketch_params()
                    if pos == 0:
                        handles.append(handle)
                    handle = mlines.Line2D([], [],
                                           markersize=5,
                                           color=colour,
                                           marker=marker,
                                           label=cat,
                                           alpha=0.6)
                if max_last_xcoord is not None and min_xcoord < max_last_xcoord:
                    raise ValueError("Overlapping X values")
                max_last_xcoord = max_xcoord

    # Set the axis to log if necessary
    if args.log is True:
        plt.xscale("log")

    #
    # plot.plot((1, max(max(data[_]) + 1000 for _ in data)), (2, 2), 'k-')
    # plot.plot((1, max(max(data[_]) + 1000 for _ in data)), (3, 3), 'k-')

    handles = []
    labels = []
    for index, tup in enumerate(data.keys()):
        method, division = tup
        if options["colourmap"]["use"] is False:
            colour = options["methods"][method]["colour"]
            matched = re.match("\(([0-9]*), ([0-9]*), ([0-9]*)\)$", colour)
            if matched:
                colour = "#{0:02x}{1:02x}{2:02x}".format(
                    clamp(int(matched.groups()[0])),
                    clamp(int(matched.groups()[1])),
                    clamp(int(matched.groups()[2])))
        elif options["methods"][method]["colour"] in ("black", "k"):
            colour = "black"
        else:
            colour = color_map(
                color_normalizer(options["methods"][division]["index"]))

        # color = colors[int(index / 2)]
        marker = options["divisions"][division]["marker"]
        cat = "{} ({})".format(method, division)
        labels.append(cat)
        # handles.append(handle)
        for pos, point in enumerate(data[tup]):
            handle = axes[pos].scatter(point,
                                       1,
                                       alpha=1,
                                       label=cat,
                                       color=colour,
                                       marker=marker,
                                       edgecolor="k",
                                       s=150)
            handle.get_sketch_params()
            if pos == 0:
                handles.append(handle)
        handle = mlines.Line2D([], [],
                               markersize=5,
                               color=colour,
                               marker=marker,
                               label=cat,
                               alpha=0.6)

    div_labels = []
    for division in options["divisions"]:
        faux_line = mlines.Line2D(
            [], [],
            color="white",
            marker=options["divisions"][division]["marker"],
            markersize=14,
            markerfacecolor="black")
        div_labels.append((faux_line, division))

    for method in options["methods"]:
        if options["colourmap"]["use"] is False:
            colour = options["methods"][method]["colour"]
            matched = re.match("\(([0-9]*), ([0-9]*), ([0-9]*)\)$", colour)
            if matched:
                colour = "#{0:02x}{1:02x}{2:02x}".format(
                    clamp(int(matched.groups()[0])),
                    clamp(int(matched.groups()[1])),
                    clamp(int(matched.groups()[2])))
        elif options["methods"][method]["colour"] in ("black", "k"):
            colour = "black"
        else:
            colour = color_map(
                color_normalizer(options["methods"][method]["index"]))

        patch = mpatches.Patch(facecolor=colour, linewidth=1, edgecolor="k")
        div_labels.append((patch, method))

    if args.division is True:
        fs = 16
    else:
        fs = 10

    plt.figlegend(handles=[_[0] for _ in div_labels],
                  labels=[_[1] for _ in div_labels],
                  loc="lower center",
                  scatterpoints=1,
                  ncol=min(ceil(len(options["methods"]) * 2 / 4), 3),
                  fontsize=fs,
                  framealpha=0.5)
    plt.tight_layout(
        pad=0.5,
        h_pad=1,
        w_pad=1,
        rect=[
            0.05,  # Left
            0.15,  # Bottom
            0.95,  # Right
            0.95
        ])  # Top
    out = "{}.{}".format(os.path.splitext(args.out)[0], options["format"])
    plt.savefig(out, format=options["format"], transparent=True)
Example #43
0
def plot_wind_rose(speed, direction, title, label = ""):
    """
    Plot a wind rose for each year

    :param array speed: wind speed
    :param array direction : wind direction
    :param str title: plot title
    :param str label: optional label
    """
    import matplotlib.pyplot as plt

    binspeeds=np.array([0.,2.5,5.,7.5,10.,15.,20.,30.,100.])
    semi_separation=(2.5/180.)*np.pi

    # 30 degree bins
    
    angles=np.arange(0.0,360.+DEGREEBINS,DEGREEBINS)
    angles=[((i+(DEGREEBINS/2.))/180.)*np.pi for i in angles]

    # 2-D histogram (x, y, bins=[xbins,ybins])

    good=np.where((direction.mask == False) & (speed.mask == False))
    

    hist2d, xedge, yedge=np.histogram2d(np.deg2rad(direction[good]), speed[good], bins = [angles,binspeeds], normed = True)


    # normalisation is by bin area => (np.pi/6.)*5  angle*speed
    

    plot_angles=[i+semi_separation for i in angles[:-1]]

    LegendBars=[]
    LegendLines=[]

    # YlGnBu from ColorBrewer with 8 steps
    colours = ['#FFFFD9',\
                '#EDF8B1',\
                '#C7E9B4',\
                '#7FCDBB',\
                '#41B6C4',\
                '#1D91C0',\
                '#225EA8',\
                '#0C2C84']

    fig=plt.figure(figsize=(8,8.5))
    plt.clf()
    ax=fig.add_axes([0.1,0.15,0.8,0.8], polar=True)
    for yb,ybins in enumerate(yedge[:-1]):
        if yb==0:
            bars=ax.bar(plot_angles,hist2d[:,yb], \
                        width=(DEGREEBINS/180.)*np.pi-2.*semi_separation, \
                        bottom=0,color=colours[yb])
        else:
            # left,height, width, bottom
            bars=ax.bar(plot_angles,hist2d[:,yb], \
                        width=(DEGREEBINS/180.)*np.pi-2.*semi_separation, \
                        bottom=np.sum(hist2d[:,0:yb],axis=1),color=colours[yb])
        
        LegendBars+=[bars[0]]
        if yb != len(yedge[:-1])-1:
            LegendLines+=["%i-%i" %(binspeeds[yb],binspeeds[yb+1])]
        else:
            LegendLines+=[">%i" %(binspeeds[yb])]

    ax.set_theta_direction(-1)
    ax.set_theta_zero_location("N")
    plt.figlegend(LegendBars,LegendLines,loc=8,frameon=False,ncol=4, title="Wind Speed (m/s)")

    watermarkstring="/".join(os.getcwd().split('/')[4:])+'/'+os.path.basename( __file__ )+"   "+dt.datetime.strftime(dt.datetime.now(), "%d-%b-%Y %H:%M")
    plt.figtext(0.01,0.01,watermarkstring,size=6)
    plt.figtext(0.7,0.95,title)

    if label != "":
        plt.figtext(0.7,0.9, label)
    
    plt.show()

    return
Example #44
0
xf = [0] + [pa['Age_group[T.%s]' % a] for a in ages]
xm = [0] + [pa['Age_group[T.%s]:Sex[T.Male]' % a] for a in ages]
xf = np.asarray(xf)
xm = np.asarray(xm)
xm += pa['Sex[T.Male]']

# Plot the age and sex effects
plt.clf()
plt.axes([0.1, 0.1, 0.7, 0.8])
plt.grid(True)
plt.plot(an, xf, label="Female")
plt.plot(an, xf + xm, label="Male")
plt.xlabel("Age")
plt.ylabel("Log risk ratio for deaths")
ha, lb = plt.gca().get_legend_handles_labels()
leg = plt.figlegend(ha, lb, "center right")
leg.draw_frame(False)
pdf.savefig()

# Next we plot the male/female log risk ratio by age group.  This
# shows how much more likely a male is to die than a female in each
# month.  This effect holds for all age groups in all years.

plt.clf()
plt.grid(True)
plt.plot(an, xm, label="Male")
plt.xlabel("Age")
plt.ylabel("Male/female log risk ratio")
pdf.savefig()

# Next we consider the mortality risk by month for females and males.
Example #45
0
File: pics.py Project: zqcr/runlmc
    rest_xs = xss[test_ix[col]]
    rest_ys = yss[test_ix[col]]
    ax.scatter(rest_xs,
               rest_ys,
               c='magenta',
               edgecolors='none',
               s=marker_size,
               zorder=10,
               label='training')

    ax.set_xlim([0, 250])
    ax.set_title('output {} (95%)'.format(col))

    h, l = ax.get_legend_handles_labels()

plt.figlegend(h, l, loc="upper center", borderaxespad=0., ncol=6)

print('fx2007graph.pdf')
plt.savefig(outdir + 'fx2007graph.pdf', format='pdf', bbox_inches='tight')
plt.clf()

print('weather picture')

test_fx = ['cam', 'chi']
xss, yss, test_xss, test_yss, cols = weather()
kgen, rgen, slfmgen, indepgen = slfm_gp(len(xss), 2)

np.random.seed(1234)
fk = FunctionalKernel(D=len(xss),
                      lmc_kernels=kgen(),
                      lmc_ranks=rgen(),
Example #46
0
def custom_plot(fname,
                df_,
                x_key,
                y_keys,
                hue="key",
                hue_keys=None,
                OUTPUT_DATA=False,
                disable_legend=True):
    plt.close('all')
    print fname

    if len(df_) == 0:
        print "No records for this test in this data set"
        return

    yid = 1
    for y_key in y_keys:
        # print(df_)
        # if df_[y_key] == None:
        #     continue
        print str(yid) + " : " + y_key

        # Output data
        if OUTPUT_DATA:
            for t in [2, 4, 8, 16, 32, 64]:
                print "Threads: %d" % t

                df_t = df_
                temp = df_t[x_key] == t
                df_t = df_t[temp]

                s = "row/col"
                for k1 in hue_keys:
                    df_k1 = df_t
                    temp = df_k1[hue].str.contains(k1)
                    df_k1 = df_k1[temp]
                    x = df_k1[y_key].mean()
                    s += ", %s(%.2f)" % (k1, x)
                print s

                for k1 in ["WaitFree", "Linux"]:
                    df_k1 = df_t
                    temp = df_k1[hue].str.contains(k1)
                    df_k1 = df_k1[temp]
                    x = df_k1[y_key].mean()
                    s = "%s(%.2f)" % (k1, x)

                    for k2 in hue_keys:
                        df_k2 = df_t
                        temp = df_k2[hue].str.contains(k2)
                        df_k2 = df_k2[temp]
                        # print len(df_k2)

                        y = df_k2[y_key].mean()
                        s += ", %.2f" % (100 * (x - y) / y)
                    print s

        f, ax = plt.subplots(1, 1, figsize=(3.25, 1.75))
        ax = sns.barplot(x=x_key,
                         y=y_key,
                         hue=hue,
                         hue_order=hue_keys,
                         data=df_,
                         ax=ax)

        # title = (y_key.split(":")[3]).title()
        # ax.set_title(title)

        # manipulate the y_key string to create a more meaningful y-axis label
        ylabel = y_key[19:]
        if ":" not in ylabel:
            splitted = ylabel.split("_")
            ylabel = splitted[1] + "ed " + splitted[0].title() + " Operations"
        elif "fail" in ylabel:
            ylabel = "Total Failed Operations"
        elif "pass" in ylabel:
            ylabel = "Total Passed Operations"
        else:
            ylabel = "Total Operations"

        ax.set_xlabel("Threads")
        ax.set_ylabel(ylabel)

        # ax.set(ylim=(0, 3.5 * pow(10, 7)))
        ax.spines['left'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.yaxis.set_ticks_position('left')
        ax.xaxis.set_ticks_position('bottom')
        # ax.set_ylabel("Operations")

        # ax.legend(title = '')
        # ax.legend(loc = 'best');
        # ax.legend(bbox_to_anchor = (1.05, 1), loc = 2, borderaxespad = 0.)

        # for some reason, the lock free MCAS buffer always had '(2)' at the end in the legend
        for text in ax.legend(bbox_to_anchor=(1.05, 1),
                              loc=2,
                              borderaxespad=0.).get_texts():
            if '(2)' in text.get_text():
                text.set_text(text.get_text().split('(')[0])

        yid += 1

        directory = os.path.dirname("graphs/")
        if not os.path.exists(directory):
            os.mkdir(directory)

        if not disable_legend:
            figLegend = plt.figure(figsize=(6.25, .5))

            plt.figlegend(*ax.get_legend_handles_labels(),
                          ncol=6,
                          loc='center left')
            for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
                         ax.get_xticklabels() + ax.get_yticklabels()):
                item.set_fontsize(5)

            plt.savefig("graphs/" + fname + '_legend.pdf')
            plt.close()
            return
        else:
            # ax.legend_.remove()
            pass

        plt.savefig(
            "graphs/" + fname + "_" + ("_".join(y_key.split(":"))).title() +
            ".pdf",
            bbox_inches='tight')  # saves the current figure into a pdf page
        plt.close()
Example #47
0
def fit_model(df):
    channel = 20
    model = HDBSCAN(
        algorithm='best',
        #alpha=1.0,
        approx_min_span_tree=True,
        gen_min_span_tree=False,
        leaf_size=50,
        #memory=Memory(cachedir=None),
        metric='euclidean',
        min_cluster_size=4 * 24 * 14,
        min_samples=4 * 24,
        #p=None,
        core_dist_n_jobs=-1,
        cluster_selection_method="leaf",
        cluster_selection_epsilon=0.15,
    )

    def model_channel(i):
        model.fit(df.iloc[:, i:i + 1].values)
        pred = model.fit_predict(df.iloc[:, i:i + 1].values)
        test_df = pd.DataFrame()
        test_df['date_time'] = df.index
        test_df = test_df.sort_values(by='date_time')
        test_df['score'] = model.outlier_scores_
        test_df.score.fillna(0, inplace=True)
        test_df['usage'] = df.iloc[:, i:i + 1].values
        test_df['anomaly'] = pred
        test_df.loc[test_df.anomaly >= 0, 'anomaly'] = 1
        #outliers=test_df.loc[test_df['anomaly'] == -1]
        #outlier_index=list(outliers.index)
        channel_id = df.columns[i]
        test_df['channel_id'] = channel_id
        test_df['shift'] = test_df['usage'].shift(-1)
        test_df['percentage_change'] = (
            (test_df['usage'] - test_df['shift']) / test_df['usage']) * 100
        test_df = test_df.drop('shift', 1)
        test_df.to_csv(f"~/data/hdbscan_channel_{channel_id}.csv", index=False)
        return test_df

    # visualization
    fig, axes = plt.subplots(3, 3)
    fig.subplots_adjust(hspace=0.5)
    fig.suptitle('Outliers by Channel')
    for ax, i in zip(axes.flatten(), range(18, 27)):
        test_df = model_channel(i)
        print(test_df['anomaly'].value_counts())
        ax.set(title=f"Channel {i + 1}")
        #X_train, X_test = train_test_split(test_df, train_size=(2/3), random_state=1234, shuffle=False)
        a = test_df.loc[test_df['anomaly'] == -1, ['date_time',
                                                   'usage']]  #anomaly
        ax.plot(test_df['date_time'],
                test_df['usage'],
                color='blue',
                label='Normal')
        ax.scatter(a['date_time'], a['usage'], color='red', label='Anomaly')

    plt.gcf().autofmt_xdate()
    handles, labels = ax.get_legend_handles_labels()
    plt.figlegend(handles,
                  labels,
                  bbox_to_anchor=(0.5, 0.5, 0.5, 0.5),
                  loc='center right')
    plt.show()





ax1.set_xlabel('$k_h$')
ax1.set_ylabel('2D spectra')




plt.rc('legend', numpoints=1)
leg1 = plt.figlegend(
        [l_Etot[0], l_EK[0], l_EA[0]], 
        ['$E$', '$E_K$', '$E_A$'], 
        loc=(0.78, 0.7), 
        labelspacing = 0.2
)



ax1.set_xlim([0.1,150])
ax1.set_ylim([1e-5,2e1])


create_fig.save_fig()

plt.show()


Example #49
0
plt.plot(l2_error)
plt.xlabel('t')
plt.ylabel('RMSE')
plt.title('Error plot')
plt.show()

# PCA
pca = decomposition.PCA(n_components=1)
pca.fit(data.T)
predicted = pca.transform(predicted.T).T
target = pca.transform(target.T).T

plt.plot(x, predicted[0, :])
plt.plot(x, target[0, :])
plt.xlabel('t')
plt.figlegend(['predicted', 'target'], loc='upper left')
plt.title('Data plot PCA')
plt.show()

l2_error = norm(predicted - target, axis=0) / np.mean(norm(target, axis=0))
print(calculate_prediction_horizon(l2_error, 0.3))
plt.plot(l2_error)
plt.xlabel('t')
plt.ylabel('RMSE')
plt.title('Error plot PCA')
plt.show()

# graph_count = 4
# offset = 0
# for i in range(graph_count):
#     plt.subplot(graph_count / 2, 2, i + 1)
        partialSum = np.sum(omega[:,j,:]*(ratioEa[:,j,:]-multiplicityEa[:,j,:]), axis=1)
        lgs = []
        for i,a in enumerate(range(minAlfa,maxAlfa)): #alfa
            lgs.append(axarr[maxRanges-1-j].fill_between(co2, partialSum, color=cm(a/(maxAlfa-1)), label=labelAlfa[a]))
            lastOmegas[maxRanges-1-j,i] = partialSum[-1]
            partialSum -= omega[:,j,i]*(ratioEa[:,j,i]-multiplicityEa[:,j,i])
            epsilon[:,j,i] = omega[:,j,i]*(ratioEa[:,j,i]-multiplicityEa[:,j,i])

    myLegends = []
    myLabels = []#[r"$E_a$", r"$E^f + \sum_\alpha \;\epsilon_\alpha$"]
    myLegends += lgs
        
    for i in range(maxAlfa-1,minAlfa-1,-1): #alfa
        myLabels.append(labelAlfa[i])
    myLabels.append("Rel. err.")
    plt.figlegend(myLegends, myLabels, loc=(0.68,0.15), prop={'size':11})
    #plt.savefig("multiplicitiesOmegas"+ext+".svg", bbox_inches='tight')

if lmbdas:
    figS, axar = plt.subplots(2, sharex=True, figsize=(5,4))
    figS.subplots_adjust(top=0.95,left=0.15, right=0.95)
    inf.smallerFont(axar[0], 8)
    inf.smallerFont(axar[1], 8)

    p.minA = 0; p.maxA = 4; p.maxA = 4
    if p.rLib == "farkas":
        p.minA = 0; p.maxA = 7; p.maxA = 7
        labelAlfa[4] = labelAlfa[22]
        labelAlfa[5] = labelAlfa[23]
        labelAlfa[6] = labelAlfa[24]
    tempMavgS, omegaS, totalRateS, totalRateEventsS, ratesS, ratiosS = mi.getMavgAndOmega(p,temperatures,workingPath)
Example #51
0
              mew=0.5,
              style=['--o', '-s', '--v', '-^', '--<', '->'],
              grid=True)
    ax.set_title('Impact %d' % groupID, y=0.96)
    ax.set_ylim([-0.07, 1.05])

    if groupID % 5 != 0:
        ax.set_yticklabels([])
    else:
        ax.set_ylabel('Probability')

    if groupID < 5:
        ax.set_xlabel('(%s)' % labs[groupID], labelpad=-5)
        ax.set_xticklabels([])
    else:
        ax.set_xlabel('# baselines\n(%s)' % labs[groupID])

    if groupID == 0:
        ax.axvspan(4, 24, color='grey', alpha=0.2)
    # ax.set_xticks(np.unique(prob.index.get_level_values(1).values))
    # break

axarr[0, 0].set_title('Baseline')
pyplot.figlegend(ax.lines,
                 np.unique(prob.index.get_level_values(0).values),
                 loc='upper center',
                 ncol=6,
                 labelspacing=0.)
pyplot.savefig('experiment_performance.svg')
#pyplot.show()
Example #52
0
    def currdenfig(self,
                   title=None,
                   times=[0],
                   z_index=0,
                   leg_kwargs={},
                   **kwargs):
        """Plot current densities of the cell segments at times.

        **Arguments:**

        - *title*: Title for the figure

        - *times*: List of times at which the data should be sampled

             If multiple times are given, then subfigures will be generated.

        - *z_index*: z-index at which the current densities are taken

        - *leg_kwargs*: Dictionary of keyword arguments for
          :meth:`matplotlib.pyplot.legend`

             If *leg_kwargs* is *None*, then no legend will be shown.

        - *\*\*kwargs*: Additional arguments for  :meth:`barfig`
        """
        # Process the arguments.
        xlabel = kwargs.pop('xlabel', 'y-axis index (inlet to outlet)')
        name_template = self.cell + ('iprimeprime_seg[%i, ' + '%i]' %
                                     (z_index + 1))
        #description = self.get_description(name_template % 1)
        #unit = self.get_unit(name_template % 1)
        unit = self.get_unit(name_template % 1)
        #ylabel = kwargs.pop('ylabel', label_number(description, unit))
        ylabel = kwargs.pop('ylabel', label_number("Current density", unit))

        # Create the plot.
        ax = self.barfig(names=[name_template % (i_y + 1) for i_y in range(1)],
                         times=times,
                         xlabel=xlabel,
                         ylabel=ylabel,
                         leg_kwargs=None,
                         **kwargs)
        for a, time in zip(ax, times):
            a.axhline(self.get_values('cell.iprimeprime', time),
                      linestyle='--',
                      color='k',
                      label='Entire cell')

        # Decorate.
        if title is None:
            if self.n_z == 1:
                plt.title("Current Distribution of Cell Segments")
            else:
                plt.title("Current Distribution of Cell Segments\n"
                          "z-axis index %i (of %i)" % (z_index + 1, self.n_z))
        if leg_kwargs is not None:
            loc = leg_kwargs.pop('loc', 'best')
            if len(ax) == 1:
                ax[0].legend(loc=loc, **leg_kwargs)
            else:
                plt.figlegend(ax[0].lines, **leg_kwargs)
Example #53
0
def plotPCA(proj3D, X_r, PCs, ligs, colors, csvPath, fl_saveEPS, fl_savePNG,
            annotate):
    """
    Plot the PCA data on 2D plot
    """

    # Set some figure parameters
    plt.rcParams['xtick.major.pad'] = '8'
    plt.rcParams['ytick.major.pad'] = '8'

    # Main figure
    fig = plt.figure(figsize=(13, 12), dpi=100)

    if proj3D:
        ax = fig.add_subplot(111, projection="3d")
        for label, col, x, y, z in zip(ligs, colors, X_r[:, 0], X_r[:, 1],
                                       X_r[:, 2]):
            newCol = makeColor(col)
            Axes3D.scatter(ax,
                           x,
                           y,
                           z,
                           label=label,
                           c=newCol,
                           marker="o",
                           lw=1,
                           s=800)
        ax.set_xlabel("PC1 (" + '{0:g}'.format(PCs[0]) + " %)", fontsize=30)
        ax.set_ylabel("PC2 (" + '{0:g}'.format(PCs[1]) + " %)", fontsize=30)
        ax.set_zlabel("PC3 (" + '{0:g}'.format(PCs[2]) + " %)", fontsize=30)
        ax.xaxis.labelpad = 20
        ax.yaxis.labelpad = 20
        ax.zaxis.labelpad = 20
        ax.tick_params(axis="both", which="major", labelsize=20)
        imgPath = csvPath.replace(".csv", "_3D")
    else:
        ax = fig.add_subplot(111)
        for label, col, x, y in zip(ligs, colors, X_r[:, 0], X_r[:, 1]):
            newCol = makeColor(col)
            ax.scatter(x,
                       y,
                       label=label,
                       color=newCol,
                       marker="o",
                       lw=1,
                       s=800)
            if annotate:
                ax.annotate(label,
                            xy=(x, y - 0.05),
                            fontsize=30,
                            ha='center',
                            va='bottom')
        ax.set_xlabel("PC1 (" + '{0:g}'.format(PCs[0]) + " %)", fontsize=30)
        ax.set_ylabel("PC2 (" + '{0:g}'.format(PCs[1]) + " %)", fontsize=30)
        ax.tick_params(axis="both", which="major", labelsize=30)
        imgPath = csvPath.replace(".csv", "_2D")

    # figTitle = "PCA on " + csvPath + " (PC1=" + pcVals[0] + ", PC2=" +
    # pcVals[1] + ")"
    # ax.text(0.5, 1.04, figTitle, horizontalalignment="center", fontsize=30,
    #         transform=ax.transAxes)

    # Legend figure
    fig_legend = plt.figure(figsize=(13, 12), dpi=100)
    plt.figlegend(*ax.get_legend_handles_labels(),
                  scatterpoints=1,
                  loc="center",
                  fancybox=True,
                  shadow=True,
                  prop={"size": 30})

    # Save figures if in EPS and/or PNG format
    if fl_saveEPS:
        print("\nSAVING figures in EPS format\n")
        fig.savefig(imgPath + ".eps", bbox_inches="tight", dpi=1200)
        fig_legend.savefig(imgPath + "_legend.eps", dpi=1200)
    if fl_savePNG:
        print("\nSAVING figures in PNG format\n")
        fig.savefig(imgPath + ".png", bbox_inches="tight", dpi=300)
        fig_legend.savefig(imgPath + "_legend.png", dpi=300)

    # Otherwise show the plots
    if not fl_saveEPS and not fl_savePNG:
        print("\nSHOWING figures\n")
        plt.show()
plt.tick_params(labelsize=30)
plt.gca().axes.get_yaxis().set_visible(False)

###################
# PLOT 4 at t=200 #
###################
eta_hom = hom_data_for_python[:,3]
eta1_FV = FV_data_for_python[:,5]
eta2_FV = FV_data_for_python[:,6]

xmax=x_hom[np.argmax(eta_hom)]
shift=300
shift_FV=400

plt.subplot(133)
line1=plt.plot(x_hom+shift,eta_hom,'-k',linewidth=4)[0]
line2=plt.plot(x_FV+shift_FV,eta1_FV,'--b',linewidth=5)[0]
line3=plt.plot(x_FV+shift_FV,eta2_FV,'-r',linewidth=4)[0]
plt.ylim([0.75-0.0002, 0.7506])
plt.xlim([xmax+shift-DXLeft,xmax+shift+DXRight])
plt.tick_params(labelsize=30)
plt.gca().axes.get_yaxis().set_visible(False)

plt.figlegend(handles=(line1, line2, line3),
              labels=('Homogenized linear system',
                      'Shallow water model at y=0.25',
                      'Shallow water model at y=-0.25'),
              loc='upper center', ncol=3, labelspacing=20.,
              fontsize=30)
plt.savefig('homog_corr1.png',bbox_inches="tight")
Example #55
0
tf = [r['f'] for r in test_rouge_bl]
plt.plot(range(num_groups), tf)
if (model_type == EXTRACTIVE):
    lf = [r['f'] for r in label_rouge_bl]
    plt.plot(range(num_groups), lf)
    plt.plot(range(num_groups), [lf[g] - tf[g] for g in range(num_groups)])

#Create Directory to store the ROC Curves if it doesn't already exist
if not os.path.exists('Plots/DLB_Analysis'):
    os.makedirs('Plots/DLB_Analysis')
#Save ROC Curve
print("Saving DLB Analysis...")
DLB = {'p': tp, 'r': tr, 'f': tf}
json.dump(DLB, open('Plots/DLB_Analysis/' + model_name + '_DLB.json', 'w'))
if (model_type == EXTRACTIVE):
    plt.figlegend(labels=['Model', 'Labels', 'Difference'], loc='lower right')
plt.tight_layout()
plt.show()

if (model_type == EXTRACTIVE):
    print("Number of Sentences Predicted by Label Analysis")
    plt.figure(figsize=(8, 6))
    plt.subplot(221)
    plt.title("Precision vs # of Sent Pred by Label")
    tp = [r['p'] for r in test_rouge_ns]
    lp = [r['p'] for r in label_rouge_ns]
    plt.plot(range(1, max_sent + 1), tp)
    plt.plot(range(1, max_sent + 1), lp)
    plt.plot(range(1, max_sent + 1), [lp[g] - tp[g] for g in range(max_sent)])

    plt.subplot(222)
Example #56
0
def plot_bins(fig_path, plot_label, xscale, nbins_x, nbins_y, y_lim,
              xy_data_frames):
    def find_max_num_for_plot(bins_y, xy_data_frames, y_lim):
        max_num = 0
        for df in xy_data_frames:
            for elem in df.y_split:
                y_bins = numpy.linspace(y_lim[0],
                                        y_lim[1],
                                        num=nbins_y + 1,
                                        endpoint=True)
                freq, _ = numpy.histogram(elem, bins=y_bins)
                if max(freq) > max_num:
                    max_num = max(freq)
        return max_num

    will_del_index = []
    for i in xrange(xy_data_frames[0].num):
        will_del = False
        for df in xy_data_frames:
            if numpy.isnan(df.x[i]):
                will_del = True
            if numpy.isnan(df.y[i]):
                will_del = True
        will_del_index.append(will_del)
    for df in xy_data_frames:
        df.delete_elems_by_index(will_del_index)

    x_data = []
    for df in xy_data_frames:
        x_data = numpy.concatenate([x_data, df.x])
    bins_x = stats.mstats.mquantiles(
        x_data, numpy.linspace(0.0, 1.0, num=nbins_x + 1, endpoint=True))
    freq, _ = numpy.histogram(x_data, bins=bins_x)
    for df in xy_data_frames:
        df.ind = numpy.digitize(df.x, bins_x)
        y_split = []
        x_split = []
        for i in xrange(1, nbins_x + 1):
            y_split.append([df.y[j] for j in xrange(df.num) if df.ind[j] == i])
            x_split.append([df.x[j] for j in xrange(df.num) if df.ind[j] == i])
        df.y_split = y_split
        df.x_split = x_split
    max_num = find_max_num_for_plot(nbins_y, xy_data_frames, y_lim)
    max_num *= 1.1

    plot_label = plot_label + ', x_max=' + str(max_num)
    fig_bin, axes = plt.subplots(nrows=1,
                                 ncols=nbins_x,
                                 sharey=True,
                                 figsize=(24, 6))
    x_bin_num = 0
    for ax in axes.flat:
        y_data = []
        colors = []
        labels = []
        for df in xy_data_frames:
            y_data.append(df.y_split[x_bin_num])
            colors.append(df.color)
            labels.append(df.label)
        y_bins = numpy.linspace(y_lim[0],
                                y_lim[1],
                                num=nbins_y + 1,
                                endpoint=True)
        ax.hist(y_data,
                bins=y_bins,
                normed=0,
                histtype='bar',
                color=colors,
                label=labels,
                orientation="horizontal")
        ax.set_xscale(xscale)
        ax.set_xlim((0, max_num))
        ax.set_ylim(y_lim)
        ax.get_xaxis().set_ticks([])
        ax.set_xlabel("{0:.1f}-{1:.1f}".format(bins_x[x_bin_num],
                                               bins_x[x_bin_num + 1]))
        x_bin_num += 1
    fig_bin.suptitle(plot_label, fontsize=14)
    fig_bin.subplots_adjust(bottom=0.25)
    patches = []
    for df in xy_data_frames:
        patches.append(mpatches.Patch(color=df.color, label=df.label))
    plt.figlegend(handles=patches, labels=labels, loc=(0.1, 0.05))
    fig_bin.savefig(fig_path, dpi=100)
    plt.close(fig_bin)
Example #57
0
ax.set_ylim(window_rect[2], window_rect[3])

ax.yaxis.set_major_formatter(
    ticker.FuncFormatter(lambda y, pos: ('{{:.{:1d}f}}'.format(
        int(np.maximum(-np.log10(y), 0)))).format(y)))
ax.xaxis.set_major_formatter(
    ticker.FuncFormatter(lambda y, pos: ('{{:.{:1d}f}}'.format(
        int(np.maximum(-np.log10(y), 0)))).format(y)))

handles, labels = ax.get_legend_handles_labels()
handles = [handles[0], handles[2], handles[3], handles[4]]
labels = [labels[0], labels[2], labels[3], labels[4]]
#plt.figlegend(handles=handles,  labels=labels, loc="lower center", bbox_to_anchor=(0.25, 0.18))
plt.figlegend(handles=handles,
              labels=labels,
              loc="upper center",
              bbox_to_anchor=(0.7, 0.97),
              ncol=4,
              fontsize=10)

handles, labels = ax.get_legend_handles_labels()
handles = [handles[1], handles[7], handles[5], handles[6]]
labels = [labels[1], labels[7], labels[5], labels[6]]
#plt.figlegend(handles=handles,  labels=labels, loc="lower center", bbox_to_anchor=(0.5, 0.2), ncol=4)
plt.figlegend(handles=handles,
              labels=labels,
              loc="lower right",
              bbox_to_anchor=(0.96, 0.38),
              fontsize=11)

plt.tight_layout()
plt.show()
Example #58
0
    def plot_object(self, bands='all', savefig=False,
                    filename='mySN', orientation='horizontal',method='separate',
                    showModel=False,showFit=False,showMicro=False):
        """Plot the multiply-imaged SN light curves and show/save to a file.
            Each subplot shows a single-band light curve, for all images of the SN.

        Parameters
        ----------
        bands : str or list of str
            'all' = plot all bands; or provide a list of bands to plot
        savefig : bool
            boolean to save or not save plot
        filename : str
            if savefig is True, this is the output filename
        orientation : str
            'horizontal' = all subplots are in a single row
            'vertical' = all subplots are in a single column
        method : str
            Plots the result of separate, series, or color curve method
        showModel : bool
            If true, the underlying model before microlensing is plotted
            as well
        showFit : bool
            If true and it exists, the best fit model from
            self.images['image'].fits.model is plotted
        showMicro : bool
            If true and it exists, the simulated microlensing is plotted
            as well

        Returns
        -------
        figure : `~matplotlib.pyplot.figure`

        """




        colors=['r','g','b','k','m']
        i=0
        leg=[]

        if method=='series':
            if bands == 'all':
                bands = set(self.series.table['band'])

            nbands = len(bands)
            if orientation.startswith('v'):
                ncols = 1
                nrows = nbands
            else:
                ncols = nbands
                nrows = 1
            fig,axlist=plt.subplots(nrows=nrows, ncols=ncols,
                                    sharex=True, sharey=False,figsize=(10,10))
            if nbands==1:
                axlist = [axlist]
            for lc in np.sort([x for x in self.images.keys()]):
                temp=self.series.table[self.series.table['image']==lc]
                for b, ax in zip(bands, axlist):
                    if b==list(bands)[0]:
                        leg.append(
                            ax.errorbar(temp['time'][
                                            temp['band']==b],
                                        temp['flux'][
                                            temp['band']==b],
                                        yerr=temp['fluxerr'][
                                            temp['band']==b],
                                        markersize=4, fmt=colors[i]+'.'))
                    else:
                        ax.errorbar(temp['time'][
                                        temp['band']==b],
                                    temp['flux'][
                                        temp['band']==b],
                                    yerr=temp['fluxerr'][
                                        temp['band']==b],
                                    markersize=4, fmt=colors[i]+'.')
                    if showFit:
                        ax.plot(np.arange(np.min(temp['time'][temp['band']==b]),np.max(temp['time'][temp['band']==b]),1),
                                self.series.fits.model.bandflux(b,np.arange(np.min(temp['time'][temp['band']==b]),np.max(temp['time'][temp['band']==b]),1),
                                                                  zp=temp['zp'][temp['band']==b][0],
                                                                  zpsys=temp['zpsys'][temp['band']==b][0]),color='y')

                    ax.text(0.95, 0.95, b.upper(), fontsize='large',
                            transform=ax.transAxes, ha='right', va='top')


                i+=1
        elif method =='color':
            if bands=='all':
                if len([x for x in self.color.table.colnames if '-' in x and '_' not in x])!=1:
                    print("Want to plot color curves but need 2 bands specified.")
                    sys.exit(1)
                else:
                    colname=[x for x in self.color.table.colnames if '-' in x and '_' not in x][0]
                    bands=[colname[:colname.find('-')],colname[colname.find('-')+1:]]
            elif len(bands) !=2:
                print("Want to plot color curves but need 2 bands specified.")
                sys.exit(1)


            fig=plt.figure(figsize=(10,10))
            ax=fig.gca()
            for lc in np.sort([x for x in self.images.keys()]):
                temp=self.color.table[self.color.table['image']==lc]


                ax.errorbar(temp['time'],temp[bands[0]+'-'+bands[1]],yerr=temp[bands[0]+'-'+bands[1]+'_err'],
                            markersize=4, fmt=colors[i]+'.')

                ax.text(0.95, 0.95, bands[0].upper()+'-'+bands[1].upper(), fontsize='large',
                        transform=ax.transAxes, ha='right', va='top')

                i+=1
            if showFit:
                mod_time=np.arange(np.min(self.color.table['time']),np.max(self.color.table['time']),1)
                modCol=self.color.fits.model.color(bands[0],bands[1],self.color.table['zpsys'][0],mod_time)

                ax.plot(mod_time,modCol,color='y')
        else:
            if bands == 'all':
                bands = self.bands

            nbands = len(bands)
            if orientation.startswith('v'):
                ncols = 1
                nrows = nbands
            else:
                ncols = nbands
                nrows = 1
            fig,axlist=plt.subplots(nrows=nrows, ncols=ncols,
                                    sharex=True, sharey=True,figsize=(10,10))
            if nbands==1:
                axlist = [axlist]
            microAx={b:False for b in bands}
            for lc in np.sort([x for x in self.images.keys()]):
                for b, ax in zip(bands, axlist):
                    if b==list(bands)[0]:
                        leg.append(
                            ax.errorbar(self.images[lc].table['time'][
                                            self.images[lc].table['band']==b],
                                        self.images[lc].table['flux'][
                                            self.images[lc].table['band']==b],
                                        yerr=self.images[lc].table['fluxerr'][
                                            self.images[lc].table['band']==b],
                                        markersize=4, fmt=colors[i]+'.'))
                        if showMicro:
                            ax.set_ylabel('Flux',fontsize='large')
                    else:
                        ax.errorbar(self.images[lc].table['time'][
                                        self.images[lc].table['band']==b],
                                    self.images[lc].table['flux'][
                                        self.images[lc].table['band']==b],
                                    yerr=self.images[lc].table['fluxerr'][
                                        self.images[lc].table['band']==b],
                                    markersize=4, fmt=colors[i]+'.')

                    ax.text(0.95, 0.95, b.upper(), fontsize='large',
                            transform=ax.transAxes, ha='right', va='top')

                    if showFit:
                        time_model = np.arange(self.images[lc].table['time'].min(),
                                               self.images[lc].table['time'].max(),
                                               0.1)
                        ax.plot(time_model,self.images[lc].fits.model.bandflux(b,time_model,
                                    np.mean(self.images[lc].table['zp'][self.images[lc].table['band']==b]),
                                    self.images[lc].zpsys),'k-')
                    if showMicro:
                        time_model=np.arange(self.images[lc].table['time'].min(),
                                             self.images[lc].table['time'].max(),
                                             0.1)
                        if microAx[b] is False:
                            ax_divider = make_axes_locatable(ax)
                            ax_ml = ax_divider.append_axes("bottom", size="25%", pad=.4)
                            #ax_ml.set_xlabel('Days (Observer Frame)',fontsize='large')
                            if b==list(bands)[0]:
                                ax_ml.set_ylabel('Microlensing ($\mu$)',fontsize='large')
                            microAx[b]=ax_ml
                        else:
                            ax_ml=microAx[b]
                        ax_ml.plot(time_model,self.images[lc].simMeta['microlensing_params'](time_model/(1+self.images[lc].simMeta['sourcez'])),color=colors[i],linewidth=3)

                    if showModel:
                        # Plot the underlying model, including dust and lensing
                        # effects other than microlesning, as a black curve for
                        # each simulated SN image
                        time_model = np.arange(self.images[lc].table['time'].min(),
                                               self.images[lc].table['time'].max(),
                                               0.1)
                        time_shifted = time_model - self.images[lc].simMeta['td']


                        flux_magnified = self.model.bandflux(
                            b, time_shifted, self.images[lc].table['zp'][self.images[lc].table['band']==b][0],
                            self.images[lc].zpsys) * \
                                         self.images[lc].simMeta['mu']
                        ax.plot(time_model, flux_magnified, 'k-')


                i+=1


        plt.figlegend(leg,np.sort([x for x in self.images.keys()]), frameon=False,
                      loc='center right', fontsize='medium', numpoints=1)


        if not showMicro:
            fig.text(0.02, .5, 'Flux', va='center',
                rotation='vertical',fontsize='large')
        fig.text(0.5, 0.02, r'Observer-frame time (days)', ha='center',
                 fontsize='large')

        plt.suptitle('Multiply-Imaged SN "'+self.object+'"--'+self.telescopename,fontsize=16)
        if savefig:
            plt.savefig(filename+'.pdf',format='pdf',overwrite=True)
        return fig
Example #59
0
                                 recover_rate=0.25,
                                 infect_rate=infect_rates[i2])
            df1 = q3.Euler_Method(model=sis_model,
                                  h=h[i1],
                                  total_time=total_time,
                                  max_steps=max_steps)
            df2 = q3.Heun_Method(model=sis_model,
                                 h=h[i1],
                                 total_time=total_time,
                                 max_steps=max_steps)
            q3.draw_subplot(axes[i1, i2], [df1, df2],
                            'h=%.2f b=%.2f' % (h[i1], infect_rates[i2]),
                            y_max=100)

    # Make a custom legend for all subplots
    custom_lines = [
        Line2D([0], [0], color=df1.data.line_color, lw=2),
        Line2D([0], [0], color=df2.data.line_color, lw=2)
    ]
    plt.figlegend(custom_lines, [df1.data.method_name, df2.data.method_name],
                  loc='lower center',
                  ncol=3)
    plt.subplots_adjust(left=0.1,
                        right=0.9,
                        top=0.9,
                        bottom=0.1,
                        wspace=0.4,
                        hspace=0.5)

    plt.show()
Example #60
0
if '--plot' in sys.argv:
    import matplotlib.pyplot as plt
    plt.clf()
    plt.subplot(2, 2, 1)
    h = plt.plot(states1.t, states1.T, 'g-', states2.t, states2.T, 'b-')
    # plt.legend(['Reactor 1','Reactor 2'], 2)
    plt.xlabel('Time (s)')
    plt.ylabel('Temperature (K)')

    plt.subplot(2, 2, 2)
    plt.plot(states1.t, states1.P / 1e5, 'g-', states2.t, states2.P / 1e5,
             'b-')
    # plt.legend(['Reactor 1','Reactor 2'], 2)
    plt.xlabel('Time (s)')
    plt.ylabel('Pressure (Bar)')

    plt.subplot(2, 2, 3)
    plt.plot(states1.t, states1.V, 'g-', states2.t, states2.V, 'b-')
    # plt.legend(['Reactor 1','Reactor 2'], 2)
    plt.xlabel('Time (s)')
    plt.ylabel('Volume (m$^3$)')

    plt.figlegend(h, ['Reactor 1', 'Reactor 2'], loc='lower right')
    plt.tight_layout()
    plt.show()
else:
    print(
        """To view a plot of these results, run this script with the option -plot"""
    )