def plot_box_like_distrib(X,
                          mapping,
                          ax,
                          color,
                          marker,
                          label,
                          val_color=50,
                          max_val=np.inf,
                          div=1.,
                          reverse=False):
    Y_med, Y_25, Y_75 = [], [], []
    X_ = []
    for k in X:
        if k < max_val:
            X_.append(k)
            if reverse:
                Y_med.append(100 - 100 * np.median(mapping[k]) / div)
                Y_25.append(100 - 100 * np.percentile(mapping[k], 25) / div)
                Y_75.append(100 - 100 * np.percentile(mapping[k], 75) / div)
            else:
                Y_med.append(100 * np.median(mapping[k]) / div)
                Y_25.append(100 * np.percentile(mapping[k], 25) / div)
                Y_75.append(100 * np.percentile(mapping[k], 75) / div)

    ax.plot(X_,
            Y_med,
            '-o',
            color=cm.Paired(color),
            marker=marker,
            label=label,
            lw=2,
            ms=8)
    ax.fill_between(X_, Y_25, Y_75, color=cm.Paired(color), alpha=.2)
    return Y_med, Y_25, Y_75
Пример #2
0
 def __base_bar(self, ax, data):
     """
     Plot stacked bar chart with `origin`, `thresed`, `final` data
     """
     kwa = self.__bar_kwa(mcm.Paired(.6), y="origin")
     data.plot(ax=ax, **kwa)
     kwa = self.__bar_kwa(mcm.Paired(.3), y="thresed", ha="x")
     data.plot(ax=ax, **kwa)
     kwa = self.__bar_kwa(mcm.Paired(.1), y="final", ha="o")
     data.plot(ax=ax, **kwa)
Пример #3
0
def roc_plot(outfile, plot_x, plot_y, ids=None):
    if ids is None:
        ids = []

   
    fig = plt.figure()
    fig.add_subplot(111, aspect="equal")

    colors = [cm.Paired(256 / 11 * i) for i in range(11)]
    
    if type(plot_x[0]) == type(np.array([])):
        for i,(x,y) in enumerate(zip(plot_x, plot_y)):
            plt.plot(x, y, color=colors[(i * 2) % 10 + 1])
    else:
        plt.plot(plot_x,plot_y, color=colors[(0 * 2) % 10 + 1])
    
    plt.axis([0,1,0,1])
    plt.xlabel("1 - Specificity")
    plt.ylabel("Sensitivity")

    if len(ids) > 0:
         plt.legend(ids, loc=(1.03,0.2))

    if not os.path.splitext(outfile)[-1] in VALID_EXTENSIONS:
        outfile += ".png"
      
    plt.savefig(outfile, dpi=300, bbox_inches='tight')
    plt.close(fig)
Пример #4
0
def plot_cube(cube, name='voxel', angle=20, IMG_DIM=80, num_class=12):
    from mpl_toolkits.mplot3d import Axes3D

    # cube = normalize(cube)
    # Note that cm.Paired has 12 colors and Set2 has 8 colors
    # cube[np.where(cube > num_class)] = 10
    if num_class == 12:
        cube[cube < 0] = 0
        cube[cube == 255] = 0
        facecolors = cm.Paired((np.round(cube) / 13))
        facecolors[:, :, :, -1] = 0.2 * np.tanh(
            cube * 1000) + 0.7 * (cube > 5) + 0.1 * (cube == 2)
    elif num_class == 4:
        facecolors = cm.Dark2((np.round(cube) / 9))
        facecolors[:, :, :, -1] = 0.4 * np.tanh(cube * 1000)
    elif num_class == 3:
        # cube[cube == -1] = 3
        cube[cube < 0] = 0
        facecolors = cm.Set2((np.round(cube) / 9))
        facecolors[:, :, :,
                   -1] = 0.03 * np.tanh(cube * 1000) + 0.6 * (cube == 1)
    elif num_class == 1:
        cube[cube < 0] = 0
        facecolors = cm.Dark2((np.round(cube) / 1))
        facecolors[:, :, :, -1] = 0.5 * (cube == 1)

    # make the alpha channel more similar to each others while 0 is still 0
    facecolors = explode(facecolors)
    filled = facecolors[:, :, :, -1] != 0

    x, y, z = expand_coordinates(
        np.indices(np.array(filled.shape) + 1).astype(float))

    # Here is a loop for generating demo files
    for idx, val in enumerate(np.arange(160, 170, 10)):
        fig = plt.figure(figsize=(45 / 2.54, 45 / 2.54))  # , dpi=150)
        # plot
        ax1 = fig.add_subplot(111, projection='3d')
        # For samples in SUNCG, 20, -40 is a good choice for visualization
        # ax1.view_init(np.abs(90-val/2), val)
        ax1.view_init(angle, val)
        ax1.set_xlim(right=IMG_DIM * 2)
        ax1.set_ylim(top=IMG_DIM * 2)
        ax1.set_zlim(top=IMG_DIM * 2)
        ax1.set_axis_off()
        ax1.voxels(x,
                   y,
                   z,
                   filled,
                   facecolors=facecolors,
                   edgecolors=np.clip(2 * facecolors - 0.5, 0, 1),
                   linewidth=0.5)

        # plt.show()
        plt.savefig(name + '_' + format(idx, '03d') + '.png',
                    bbox_inches='tight',
                    pad_inches=0,
                    transparent=True)
        plt.close(fig)
    """
Пример #5
0
def plotSimDataPQTime(fig, time_snapshots, time_sim, p_sim, q_sim, compression='negative'):

  # Get snapshots from sim data
  time_snap, p_snap = getDataTimeSnapshots(time_snapshots, time_sim, p_sim)
  time_snap, q_snap = getDataTimeSnapshots(time_snapshots, time_sim, q_sim)

  # Activate the figure
  plt.figure(fig.number)

  # Plot sigma_a vs. time
  if (compression == 'positive'):
    p_data = list(map(lambda p : -p, p_sim))
    q_data = list(map(lambda q : -q, q_sim))
    plt.plot(time_sim, p_data, '--r', label='$p$ (sim)')
    plt.plot(time_sim, q_data, '--b', label='$q$ (sim)')
  else:
    plt.plot(time_sim, p_sim, '--r', label='$p$ (sim)')
    plt.plot(time_sim, q_sim, '--b', label='$q$ (sim)')

  # Plot filled circles at time snapshots
  for ii in range(0, len(time_snap)):

    # Choose the Paired colormap
    plt_color = cm.Paired(float(ii)/len(time_snap))
    if (compression == 'positive'):
      plt.plot(time_snap[ii], -p_snap[ii], 'o', color=plt_color) 
      plt.plot(time_snap[ii], -q_snap[ii], 'o', color=plt_color) 
    else:
      plt.plot(time_snap[ii], p_snap[ii], 'o', color=plt_color) 
      plt.plot(time_snap[ii], q_snap[ii], 'o', color=plt_color) 

  return time_snap, p_snap, q_snap
Пример #6
0
def visualize_2D_gmm(points, w, mu, stdev, model_id, c, export=False):
    '''
    plots points and their corresponding gmm model in 2D
    Input:
        points: N X 2, sampled points
        w: n_gaussians, gmm weights
        mu: 2 X n_gaussians, gmm means
        stdev: 2 X n_gaussians, gmm standard deviation (assuming diagonal covariance matrix)
    Output:
        None
    '''
    n_gaussians = mu.shape[1]
    N = int(np.round(points.shape[0] / n_gaussians))
    # Visualize data
    axes = plt.gca()
    colors = cmx.Accent(np.linspace(
        0, 1, n_gaussians)) if id == 'human' else cmx.Paired(
            np.linspace(0, 1, n_gaussians))
    for i in range(n_gaussians):
        idx = range(i * N, (i + 1) * N)
        for j in range(4):
            axes.add_patch(
                patches.Ellipse(mu[:, i],
                                width=(j + 1) * stdev[0, i],
                                height=(j + 1) * stdev[1, i],
                                alpha=0.4,
                                fill=True,
                                color=colors[i]))
    plt.xlabel('Dim 1')
    plt.ylabel('Dim 2')
Пример #7
0
def plotExtractedStress(test_name, pdf_name, sim_data, I1_data, X_OPERATION,
                        x_scale, X_VARIABLE_LABEL, J2_data, Y_OPERATION,
                        y_scale, Y_VARIABLE_LABEL, capX_data, alpha_I1_data,
                        yieldParams):

    print "Variables: ", X_VARIABLE_LABEL, ", ", Y_VARIABLE_LABEL

    # Convert and scale data if needed
    x_data = map(
        lambda xx: convertAndScaleData(np.asarray(xx), X_OPERATION, x_scale),
        I1_data)
    y_data = map(
        lambda yy: convertAndScaleData(np.asarray(yy), Y_OPERATION, y_scale),
        J2_data)

    # Choose a paired colormap
    colors = map(lambda ii: cm.Paired(ii), np.linspace(0.0, 1.0, len(x_data)))

    # Create a figure
    fig = plt.figure(figsize=(8, 6))
    res = map(
        lambda X, alpha, COLOR, time, PEAKI1,
        FSLOPE, STREN, YSLOPE: computeAndPlotYieldSurface(
            yieldParams, time, PEAKI1, FSLOPE, STREN, YSLOPE, X, alpha,
            X_OPERATION, x_scale, Y_OPERATION, y_scale, COLOR, pdf_name),
        capX_data, alpha_I1_data, colors, sim_data.time, sim_data.PEAKI1,
        sim_data.FSLOPE, sim_data.STREN, sim_data.YSLOPE)

    #ax1 = plt.subplot(111)
    x_data = np.array(x_data)
    y_data = np.array(y_data)
    plt.quiver(x_data[:-1],
               y_data[:-1],
               x_data[1:] - x_data[:-1],
               y_data[1:] - y_data[:-1],
               scale_units='xy',
               angles='xy',
               scale=1.0,
               width=0.001,
               headwidth=7,
               headlength=10,
               linewidth=0.5,
               edgecolor='r',
               color='k')
    #plt.plot(x_data, y_data, 'r-', linewidth = 1)
    plt.xlabel(X_VARIABLE_LABEL, fontsize=16)
    plt.ylabel(Y_VARIABLE_LABEL, fontsize=16)
    plt.title(test_name, fontsize=16)

    # Legend text (material parameters)
    legend_text = yieldParams['legend']
    plt.subplots_adjust(right=0.75)
    plt.figtext(0.77, 0.90, legend_text, ha='left', va='top', size='x-small')
    plt.grid()

    plt.savefig(pdf_name + ".pdf", bbox_inches='tight')
    #plt.show()
    plt.close(fig)

    return
Пример #8
0
def plot_shelxe_contrast(shelxe_contrast, png_file, add_legend=False):
    '''Plot contrast vs. cycle number from SHELXE.'''

    fig, ax = plt.subplots(figsize=(6, 4))
    for l, solvent_fraction in enumerate(sorted(shelxe_contrast.keys()), 1):
        contrast_vals = shelxe_contrast[solvent_fraction]
        cycles_orig, contrast_orig = contrast_vals['original']
        cycles_other, contrast_other = contrast_vals['inverted']

        lb_orig = 'Orig. {}'.format(solvent_fraction)
        lb_inv = 'Inv. {}'.format(solvent_fraction)
        color = cm.Paired(float(l) / 12)
        ax.plot(cycles_orig, contrast_orig, lw=1, c=color, label=lb_orig)
        ax.plot(cycles_other,
                contrast_other,
                ls='dashed',
                label=lb_inv,
                lw=1,
                c=color)

    plt.xlabel('Cycle', fontsize=14)
    plt.ylabel('Contrast', fontsize=14)
    plt.tick_params(labelsize=14)
    if add_legend:
        lgd = ax.legend(bbox_to_anchor=[.2, 1.02], loc=3, ncol=2)
        plt.savefig(png_file, bbox_extra_artists=(lgd, ), bbox_inches='tight')
    else:
        plt.savefig(png_file, bbox_inches='tight')

    plt.close()
Пример #9
0
def test_dna_assembly_example(tmpdir):

    spreadsheet_path = os.path.join('examples', 'examples_data',
                                    "dna_assembly.xls")

    colors = (cm.Paired(0.21 * i % 1.0) for i in range(30))

    resources = resources_from_spreadsheet(
        spreadsheet_path=spreadsheet_path, sheetname="resources")

    processes = [
        tasks_from_spreadsheet(spreadsheet_path=spreadsheet_path,
                               sheetname="process",
                               resources_dict=resources,
                               tasks_color=next(colors),
                               task_name_prefix="WU%d_" % (i + 1))
        for i in range(5)
    ]

    print("NOW OPTIMIZING THE SCHEDULE, BE PATIENT...")
    new_processes = schedule_processes_series(
        processes, est_process_duration=5000, time_limit=6)

    # PLOT THE TASKS DEPENDENCY TREE
    ax = plot_tasks_dependency_graph(processes[0])
    ax.set_title("PLAN OF A WORK UNIT")
    ax.figure.savefig("basic_example_work_unit.pdf", bbox_inches="tight")

    # PLOT THE OPTIMIZED SCHEDULE
    ax = plot_schedule([t for process in new_processes for t in process])
    ax.figure.set_size_inches((8, 5))
    ax.set_xlabel("time (min)")
    ax.figure.savefig(os.path.join(str(tmpdir),
                                   "basic_example_schedule.png"),
                      bbox_inches="tight")
Пример #10
0
	def create_roc_plots(self, pwm_file, fg_fasta, bg_fasta, name):
		motifs = dict([(m.id, m) for m in pwmfile_to_motifs(pwm_file)])
		
		jobs = {}
		for id,m in motifs.items():
			jobs[id] = self.job_server().submit(get_roc_values, (motifs[id],fg_fasta,bg_fasta,))
	
		roc_img_file = os.path.join(self.imgdir, "%s_%s_roc.png")
		
		for id in motifs.keys():
			error, x, y = jobs[id]()
			if error:
				self.logger.error("Error in thread: %s" % error)
				sys.exit(1)

			fig = plt.figure()
			try:
				# matplotlib >= 0.99
				rect = fig.patch # a rectangle instance
			except:
				# matplotlib 0.98
				rect = fig.figurePatch # a rectangle instance
				
			plt.xlim(0,0.2)
			plt.ylim(0,1.0)
			colors = [cm.Paired(256 / 11 * i) for i in range(11)]
			plt.plot(x, y, color=colors[(0 * 2) % 10 + 1])
			plt.axis([0,1,0,1])
			plt.xlabel("1 - Specificity")
			plt.ylabel("Sensitivity")
			plt.savefig(roc_img_file % (id,name), format="png")
Пример #11
0
def plot_pie(grid, std, rstd, Na, title, stride, shift):
    pb = perc_better(std, rstd)

    std = std / Na

    f1 = std[(std <= 0.023)].shape[0]
    f2 = std[(std > 0.023) & (std <= 0.05)].shape[0]
    f3 = std[(std > 0.05)].shape[0]

    labels = ['s <= 0.023', '0.023 < s <= 0.05', 's > 0.05']
    fracs = [f1, f2, f3]

    x_pos = np.arange(len(labels))
    print(x_pos)
    print(fracs)

    from matplotlib import cm
    cs = cm.Paired([0.2, 0.9, 0.42])

    plt.subplot(grid, aspect=0.002)
    plt.bar(x_pos, fracs, align='center', alpha=0.5)
    plt.xticks(x_pos, labels)

    plt.title(title + ' (Improv.: ' + "{:.1f}".format(pb) + '%;' +
              str(int((pb / 100.0) * rstd.shape[0])) + ')',
              bbox={
                  'facecolor': '0.8',
                  'pad': 5
              })
Пример #12
0
def plot_shelxe_fom_mapcc(fom_mapcc, png_file):
    '''Plot contrast vs. cycle number from SHELXE.'''

    fig, (ax1, ax2) = plt.subplots(2, figsize=(6, 4), sharex=True)
    for l, solvent_fraction in enumerate(sorted(fom_mapcc.keys()), 1):
        vals = fom_mapcc[solvent_fraction]
        orig, other = vals['original'], vals['inverted']

        lb_orig = 'Orig. {}'.format(solvent_fraction)
        lb_inv = 'Inv.'
        color = cm.Paired(float(l) / 12)
        x = range(len(orig['resol']))
        ax1.plot(x, orig['fom'], lw=1, label=lb_orig, c=color)
        ax1.plot(x, other['fom'], ls='dashed', label=lb_inv, lw=1, c=color)
        ax2.plot(x, orig['mapcc'], lw=1, label=lb_orig, c=color)
        ax2.plot(x, other['mapcc'], ls='dashed', label=lb_inv, lw=1, c=color)

    plt.xlabel('Resolution / $\mathregular{\AA}$')
    ax1.set_ylabel('<FOM>')
    ax2.set_ylabel('<mapCC>')
    ax1.xaxis.set_major_formatter(
        ticker.FuncFormatter(lambda x, p: orig['resol'][p]))
    lgd = ax1.legend(bbox_to_anchor=[1.02, 1.], loc=2, ncol=2, fontsize=10)

    plt.savefig(png_file, bbox_extra_artists=(lgd, ), bbox_inches='tight')
    plt.close()
Пример #13
0
def plot_packet_size_cdf_ssl(conn, node):
    cur = conn.cursor()
    cur.execute('''SELECT port,packet_size,count
                   FROM packet_sizes_per_port
                   WHERE node_id = %s
                   AND (port = 443
                        OR port = 993
                        OR port = 465
                        OR port = 995
                        OR port = 636
                        OR port = 5223)''',
                (node,))
    port_data = defaultdict(dict)
    for row in cur:
        port_data[row[0]][row[1]] = row[2]
    xs = range(1500)

    fig = plt.figure()
    fig.suptitle('CDF of SSL packet sizes for router %s' % node)
    ax = fig.add_subplot(111)
    for seq, (port, samples) in enumerate(port_data.items()):
        ys = []
        total = 0
        for idx in range(1500):
            if idx in samples:
                total += samples[idx]
            ys.append(total)
        ys = map(lambda y: y/float(total), ys)
        plt.plot(xs, ys, label='Port %d' % port, color=cm.Paired(seq*100))
    ax.legend(loc='lower right', prop={'size':10})
    ax.set_xlabel('Packet size')
    ax.set_ylabel('CDF')
    plt.savefig('%s_packet_size_cdf.pdf' % node)
Пример #14
0
 def LinePlot(self, axis, data_x, data_y, labels, ax_label):
     from matplotlib import cm as cm
     import numpy as np
     axis.cla()
     colors = cm.Paired(np.linspace(0, 1, len(data_x) + 2))
     for ii in range(0, len(data_x)):
         axis.plot(data_x[ii],
                   data_y[ii],
                   lw=3,
                   c=colors[ii],
                   label=labels[ii],
                   zorder=-1)
         axis.scatter(data_x[ii],
                      data_y[ii],
                      color=colors[ii],
                      alpha=0.75,
                      s=150,
                      lw=1.00,
                      edgecolor='black')
     axis.set_xlabel(ax_label[0], fontsize=Abstract2DPlot.font_size)
     axis.set_ylabel(ax_label[1], fontsize=Abstract2DPlot.font_size)
     axis.tick_params(axis='x',
                      colors='black',
                      labelsize=Abstract2DPlot.font_size,
                      width=2)
     axis.tick_params(axis='y',
                      colors='black',
                      labelsize=Abstract2DPlot.font_size,
                      width=2)
     axis.legend(fontsize=Abstract2DPlot.font_size)
     for ax in ['top', 'bottom', 'left', 'right']:
         axis.spines[ax].set_linewidth(3)
     return
Пример #15
0
def WriteMapParti(p, i):

    shortname = (p[1].replace(' ', '')).encode('ascii',
                                               'ignore').replace('.', '')
    c = np.multiply(cm.Paired(i * 10)[:3], 255)
    s = '''
    function pop_''' + shortname + '''(feature, layer) {					
    var popupContent = '<table><tr><th scope="row">Navn</th><td>' + Autolinker.link(String(feature.properties['Navn'])) + '</td></tr><tr><th scope="row">Postnummer</th><td>' + Autolinker.link(String(feature.properties['Postnummer'])) + '</td></tr><tr><th scope="row">By</th><td>' + Autolinker.link(String(feature.properties['By'])) + '</td></tr><tr><th scope="row">Dato</th><td>' + Autolinker.link(String(feature.properties['Dato'])) + '</td></tr></table>';
    layer.bindPopup(popupContent);
    }

    function doStyle''' + shortname + '''(feature) {
    return {
    color: '#000000',
    fillColor: '#''' + '%02x%02x%02x' % (c[0], c[1], c[2]) + '''',
    weight: 1.3,
    dashArray: '',
    opacity: 0.466666666667,
    fillOpacity: 0.466666666667
    };'''

    s += '''}
    var exp_''' + shortname + '''JSON = new L.geoJson(exp_''' + shortname + ''',{
    onEachFeature: pop_''' + shortname + ''',
    style: doStyle''' + shortname + '''
    });
    layerOrder[layerOrder.length] = exp_''' + shortname + '''JSON;
        '''

    #    for (index = 0; index < layerOrder.length; index++) {
    #    feature_group.removeLayer(layerOrder[index]);feature_group.addLayer(layerOrder[index]);
    #   }
    #    //add comment sign to hide this layer on the map in the initial view.
    #    feature_group.addLayer(exp_'''+shortname+'''JSON);
    return s
Пример #16
0
def main():
    w2v_path = sys.argv[1]
    w2v = Word2Vec.load(w2v_path)

    vec_list = []
    country_list = []
    for line in sys.stdin:
        country = line.strip()

        try:
            vec = w2v.wv.get_vector(country).reshape(w2v.vector_size)
        except:
            vec = None

        if vec is not None:
            vec_list.append(vec)
            country_list.append(country)

    clusters = KMeans(n_clusters=5).fit_predict(vec_list)
    vec_reduced = TSNE(n_components=2).fit_transform(vec_list)
    print(vec_reduced.shape)

    plt.figure(figsize=(12, 9))
    plt.scatter(vec_reduced[:, 0],
                vec_reduced[:, 1],
                c=['w' for _ in clusters])
    for d, l, c in zip(vec_reduced, clusters, country_list):
        plt.text(d[0], d[1], f'{l}:{c}', fontdict={'color': cm.Paired(l)})
    plt.savefig('knock99.png')
Пример #17
0
def collate_family_defining(filename):
    """
    scan a filename and list all 'FAMILY-DEFINING' features
    """

    oh = open(filename, "rU")

    doms = []
    for line in oh:
        if "FAMILY-DEFINING" in line:
            line = line.strip().split()
            doms.append(line[5])

    set_of_doms = set(doms)
    for d in set_of_doms:
        print("%s\t%s" % (doms.count(d), d))

    cols = cm.Paired(
        numpy.arange(len(set_of_doms)) / (len(set_of_doms) * 1.0))[:, :-1]
    print(cols)

    print(cols)

    print()
    print("Suggested ColourMap:")
    print("col_map = {")
    for i, d in enumerate(set_of_doms):
        print("\t'%s': '%s'," % (d, '#%02x%02x%02x' % tuple(cols[i] * 255)))
    print("\t}")

    oh.close()
Пример #18
0
def plot_multiclass_roc_curve(y_true, y_score, n_classes):
    print "x"
    '''
    Compute ROC curve and ROC area for each class
    '''
    fpr = dict()
    tpr = dict()
    roc_auc = dict()

    for i in range(n_classes):
        fpr[i], tpr[i], _ = roc_curve(y_true[:, i], y_score[:, i])
        roc_auc[i] = auc(fpr[i], tpr[i])

    all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))

    mean_tpr = np.zeros_like(all_fpr)
    for i in range(n_classes):
        mean_tpr += interp(all_fpr, fpr[i], tpr[i])

    mean_tpr /= n_classes

    fpr["macro"] = all_fpr
    tpr["macro"] = mean_tpr
    roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])

    lw = 2
    plt.figure(figsize=(9, 9))
    plt.plot(fpr["macro"],
             tpr["macro"],
             label='macro-average ROC curve (area = {0:0.2f})'
             ''.format(roc_auc["macro"]),
             color='green',
             linestyle=':',
             linewidth=4)

    colors = cycle(cm.Paired(np.linspace(0, 1, n_classes)))
    for i, color in zip(range(n_classes), colors):
        plt.plot(fpr[i],
                 tpr[i],
                 color=color,
                 lw=lw,
                 label='ROC curve of class {0} (area = {1:0.2f})'
                 ''.format(i, roc_auc[i]))

    plt.plot([0, 1], [0, 1], 'k--', color='red', lw=lw)
    plt.xlim([-0.01, 1.01])
    plt.ylim([-0.01, 1.01])
    plt.annotate('Random Guess', (.5, .48), color='red')
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver Operating Characteristic')
    plt.legend(loc="lower right")
    plt.show()
Пример #19
0
def plotSimDataSigmaTime(fig,
                         time_snapshots,
                         time_sim,
                         sigma_a_sim,
                         sigma_r_sim,
                         sigma_ar_sim,
                         labelxx='$\sigma_a$ (sim)',
                         labelyy='$\sigma_r$ (sim)',
                         labelxy='$\sigma_{ar}$ (sim)',
                         compression='negative'):

    # Get snapshots from data
    time_snap, sigma_a_snap = getDataTimeSnapshots(time_snapshots, time_sim,
                                                   sigma_a_sim)
    time_snap, sigma_r_snap = getDataTimeSnapshots(time_snapshots, time_sim,
                                                   sigma_r_sim)
    time_snap, sigma_ar_snap = getDataTimeSnapshots(time_snapshots, time_sim,
                                                    sigma_ar_sim)

    # Activate the figure
    plt.figure(fig.number)

    # Plot sigma_a vs. time
    if (compression == 'positive'):
        sigma_a_data = list(map(lambda p: -p, sigma_a_sim))
        sigma_r_data = list(map(lambda p: -p, sigma_r_sim))
        sigma_ar_data = list(map(lambda p: -p, sigma_ar_sim))
        plt.plot(time_sim, sigma_a_data, '--r', label=labelxx)
        plt.plot(time_sim, sigma_r_data, '--b', label=labelyy)
        plt.plot(time_sim, sigma_ar_data, '--g', label=labelxy)
    else:
        plt.plot(time_sim, sigma_a_sim, '--r', label=labelxx)
        plt.plot(time_sim, sigma_r_sim, '--b', label=labelyy)
        plt.plot(time_sim, sigma_ar_sim, '--g', label=labelxy)

    # Plot filled circles at time snapshots
    for ii in range(0, len(time_snap)):

        # Choose the Paired colormap
        plt_color = cm.Paired(float(ii) / len(time_snap))
        if (compression == 'positive'):
            plt.plot(time_snap[ii], -sigma_a_snap[ii], 'o', color=plt_color)
            plt.plot(time_snap[ii], -sigma_r_snap[ii], 'o', color=plt_color)
        else:
            plt.plot(time_snap[ii], sigma_a_snap[ii], 'o', color=plt_color)
            plt.plot(time_snap[ii], sigma_r_snap[ii], 'o', color=plt_color)
            #plt.plot(time_snap[ii], sigma_ar_snap[ii], 'o', color=plt_color)

    return time_snap, sigma_a_snap, sigma_r_snap, sigma_ar_snap
Пример #20
0
def _create_categorical_colors(n_categories: int):
    if n_categories > 51:
        raise ValueError(
            f"Maximum number of colors (51) exceeded: `{n_categories}`.")
    colors = [cm.Set1(i) for i in range(cm.Set1.N)][:n_categories]
    colors += [cm.Set2(i)
               for i in range(cm.Set2.N)][:n_categories - len(colors)]
    colors += [cm.Set3(i)
               for i in range(cm.Set3.N)][:n_categories - len(colors)]
    colors += [cm.tab10(i)
               for i in range(cm.tab10.N)][:n_categories - len(colors)]
    colors += [cm.Paired(i)
               for i in range(cm.Paired.N)][:n_categories - len(colors)]

    return _convert_to_hex_colors(colors)
Пример #21
0
def autocolor_quote_sources(quote, hues=(0.635, 0.047, 0.117),
                            saturations=(0.9, 0.7, 0.5, 0.3),
                            min_lum=0.2, max_lum=0.8):
    """Auto-add a `_report_color` field to the sources in in quote.sources.

    Sources at the same depth share the same luminance
    """

    colors = itertools.cycle([
        rgb_to_hex(*[255*e**0.4 for e in cm.Paired(0.21 * i % 1.0)][:3])
        for i in range(30)
    ])
    for name, source in sorted(quote.sources.items()):
        color = next(colors)
        source._report_color = color
def plot_model_results_hor(model,
                           init_pos,
                           nb,
                           ax,
                           col,
                           space=2,
                           values=None,
                           error_bars=None,
                           hatch=''):
    if values is None:
        a, b, c, d, e, f = model.retrieve_the_cat()
    else:
        a, b, c, d, e, f = values
    p1 = init_pos + .2
    p2 = init_pos + .2
    ax.barh(p1,
            a / float(a + b) * 100 - 1,
            left=1,
            height=1.6,
            color=cm.Paired(.4),
            lw=2)
    ax.barh(p2,
            -e / float(e + f) * 100 + 1,
            left=-1,
            height=1.6,
            color=cm.Paired(0),
            lw=2)
    if not error_bars is None:
        ax.errorbar([a / float(a + b) * 100, -e / float(e + f) * 100],
                    [p1, p2],
                    xerr=[error_bars[0], error_bars[4]],
                    fmt='none',
                    ecolor='k',
                    linewidth=3,
                    mew=3,
                    alpha=.7)
Пример #23
0
def decision_boundary(data_set, classifier):

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    h = 0.01
    X, labels = data_set
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))

    output_data = classifier.evaluate(np.c_[xx.ravel(), yy.ravel()])
    Z = np.array(output_data).reshape(xx.shape)
    ax.contourf(xx, yy, Z, cm="Paited")

    # Replot the scatter data
    data_separated, total_class = separate_data_by_class(data_set)
    data_visual = []
    for item in data_separated.values():
        data_visual.append(item)

    # Building Color based on max class
    # print(total_class)
    x = np.arange(total_class)
    ys = [i + x + (i * x)**2 for i in range(total_class)]
    COLORS = cm.Paired(np.linspace(0, 1, len(ys)))

    i = 1
    for d, color in zip(data_visual, COLORS):
        x, y = d
        ax.scatter(x, y, alpha=0.8, color=color, s=20, label=i)
        i += 1

    # Limit X, Y Axis
    ax.axis((0, 1, 0, 1))

    # Shrink 10% figure from top
    box = ax.get_position()
    ax.set_position(
        [box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])

    plt.title('Data set visualization')
    plt.legend(title="Class Legend",
               loc='upper center',
               ncol=int(total_class / 3) + 1,
               bbox_to_anchor=(0.5, -0.05))
    plt.show()
Пример #24
0
def colors_cycle(lightness_factor=1.0, color_shift=0):
    if MATPLOTLIB_AVAILABLE:
        cycle = itertools.cycle([
            cm.Paired(color_shift + 0.21 * i % 1.0)
            for i in range(30)
        ])
        return (
            '#%02x%02x%02x' % tuple([int(255 * c * lightness_factor)
                                    for c in rgb_tuple[:3]])
            for rgb_tuple in cycle
        )
    else:
        return itertools.cycle([
            "#f1cccc", "#f1e5cc", "#e3f1cc", "#ccf1e3", "#ccd7f1", "#e0ccf1",
            "f1cce7"
        ])
def generate_map(typ, y_min, x_min, y_max, x_max, g_max, list_traj,
                 dico_annotation):
    """
    Generate Open Street Map HTML page
    """
    xmean = np.mean([x_min, x_max])
    ymean = np.mean([y_min, y_max])
    if typ == 1:
        list_traj = sorted(list_traj, key=itemgetter(6), reverse=True)
    elif typ == 2:
        list_traj = sorted(list_traj, key=itemgetter(6), reverse=True)
    my_map = folium.Map(location=[ymean, xmean],
                        tiles='Stamen Terrain',
                        zoom_start=6)
    town_set = set()
    dico_traj_size = dict()
    for data in list_traj:
        #data
        y1, x1, y2, x2, m1, m2, g = data
        #get color
        cm_object = cm.Paired(1. * g / g_max)
        rgb = cm_object[:3]
        hexa = colors.rgb2hex(rgb)
        #trajectory
        folium.PolyLine([(y1, x1), (y2, x2)], color=hexa, weight=g,
                        opacity=1).add_to(my_map)

        #marker
        if m1 not in town_set:
            folium.Marker(
                [y1, x1],
                popup=m1 + "\n" +
                dico_annotation[m1.encode('iso8859_15')][0]).add_to(my_map)
            town_set.add(m1)
        if m2 not in town_set:
            folium.Marker(
                [y2, x2],
                popup=m2 + "\n" +
                dico_annotation[m2.encode('iso8859_15')][0]).add_to(my_map)
            town_set.add(m2)
    for key in dico_annotation.keys():
        if key.decode('iso8859_15') not in town_set:
            pass
            #folium.Marker([dico_annotation[m2.encode('iso8859_15')][1], dico_annotation[m2.encode('iso8859_15')][2]], popup=key+"\n"+dico_annotation[m2.encode('iso8859_15')][0]; color="black").add_to(my_map)
    filename = 'map_' + str(typ) + '.html'
    my_map.save(filename)
    webbrowser.open(filename)
Пример #26
0
def plot_stacked_histograms(counts, edges, fhand=None, axes=None, vlines=None,
                            no_interactive_win=False, figsize=None,
                            mpl_params=None, bin_labels=None, **kwargs):
    'counts should be a dictionary'
    if mpl_params is None:
        mpl_params = {}

    print_figure = False
    if axes is None:
        print_figure = True
    axes, canvas, fig = _get_mplot_axes(axes, fhand, figsize=figsize)

    width = edges[1:] - edges[:-1]
    bottom = None
    for idx, (label, this_counts) in enumerate(counts.items()):
        color = cm.Paired(1. * idx / len(counts))
        axes.bar(edges[:-1], this_counts, width=width, bottom=bottom,
                 color=color, label=label, **kwargs)
        if bottom is None:
            bottom = this_counts
        else:
            bottom += this_counts

    if bin_labels is not None:
        assert len(bin_labels) == len(list(edges)) - 1
        ticks = edges[:-1] + width / 2
        axes.set_xticks(ticks)
        xticklabels = list(map(str, bin_labels))
        axes.set_xticklabels(xticklabels, rotation='vertical')

    if vlines is not None:
        ymin, ymax = axes.get_ylim()
        axes.vlines(vlines, ymin=ymin, ymax=ymax)

    for function_name, params in mpl_params.items():
        function = getattr(axes, function_name)
        function(*params.get('args', []), **params.get('kwargs', {}))

    if len(counts) > 1:
        axes.legend()

    fig.tight_layout()

    if print_figure:
        _print_figure(canvas, fhand, no_interactive_win=no_interactive_win)

    return
Пример #27
0
def draw_geometry(omgeo, coords, num, colormap=None):
    colors = []
    if colormap:
        mint = min(colormap.values())
        maxt = max(colormap.values())
        colormap = dict( (key,((colormap[key]-mint)/maxt)) for key in colormap.keys() )
    for omkey, omgeo in omgeo:
        if omgeo.position.z > 1200: continue
        if(colormap):
            if omkey in colormap:
                colors.append( cm.Paired(colormap[omkey]) )
            else:
                colors.append( (0,0,0,0) )
    if( colormap ):
        basic_scatter(num,coords, colors, [mint,maxt])
    else:
        basic_scatter(num,coords, colors)
Пример #28
0
def VisualizeHidden(embed_tsne, embed_pca, label, types, title):

    embed_tsne = (embed_tsne - min(embed_tsne[:, 0])) / (
        max(embed_tsne[:, 0]) - min(embed_tsne[:, 0]))
    embed_pca = (embed_pca - min(embed_pca[:, 0])) / (max(embed_pca[:, 0]) -
                                                      min(embed_pca[:, 0]))
    label_unique = np.unique(label)
    colors = cm.Paired(np.linspace(0, 1, len(label_unique)))
    fig = plt.figure()
    plot_time = 0
    for this_label, c, this_type in zip(label_unique, colors, types):
        id = (label == this_label).nonzero()
        plt.scatter(embed_tsne[id, 0],
                    embed_tsne[id, 1],
                    color=c,
                    label=str(this_type))
        plot_time += 1
    lgd = plt.legend(loc='upper left', scatterpoints=1)
    plt.xlim((-0.1, 1))

    fig.savefig(title + '_TSNE.png',
                bbox_extra_artists=(lgd, ),
                bbox_inches='tight')

    fig = plt.figure()
    ax = p3.Axes3D(fig)
    plot_time = 0
    for this_label, c, this_type in zip(label_unique, colors, types):
        id = (label == this_label).nonzero()
        ax.scatter(embed_pca[id, 0],
                   embed_pca[id, 1],
                   embed_pca[id, 2],
                   color=c,
                   label=str(this_type))
        plot_time += 1
    lgd = plt.legend(loc='upper left',
                     bbox_to_anchor=(1.01, 1),
                     scatterpoints=1)
    plt.xlim((-0.1, 1))

    fig.savefig(title + '_PCA.png',
                bbox_extra_artists=(lgd, ),
                bbox_inches='tight')

    return embed_tsne, embed_pca
Пример #29
0
def posterior_viz(gp):
    """
	Visualization and exploration of posterior distribution, after model has
	been fit to observations. 

	Visualizes (1) the observed data along with (2) several draws from the learned posterior
	distribution and (3) the full poster confidence intervals. 

	Output plot is saved in current directory. 

	Parameters
	----------
	gp: GaussianProcess

	"""

    if not gp.is_fitted:
        raise ValueError("""
			You probably want to fit this model to some observations.
			Otherwise, the visualizations won't be very interesting.
			""")

    fig = plt.figure()
    gs = GridSpec(2, 1)
    ax1 = fig.add_subplot(gs[0, 0])
    plt.plot(gp.x_observed, gp.y_observed, 'k+', markersize=15)
    for i in range(0, 5):
        f = gp.sample(1)[0]
        plt.plot(gp.x_test, f, '--', color=cm.Paired(i * 30), linewidth=1)

    ax1 = fig.add_subplot(gs[1, 0])
    plt.plot(gp.x_observed, gp.y_observed, 'k+', markersize=15)
    plt.xlim([min(gp.x_test), max(gp.x_test)])
    (mean, upper_conf, lower_conf) = gp.predict()
    plt.plot(gp.x_test, mean, 'k-', linewidth=1, alpha=.5)
    ax1.fill_between(gp.x_test,
                     upper_conf,
                     lower_conf,
                     alpha=.5,
                     color="#3690C0",
                     linewidth=0)
    plt.savefig('gp_posterior.png')
Пример #30
0
 def TrajPlot(self, axis, traj_data_x, traj_data_y, traj_data_z,
              traj_label):
     from matplotlib import cm as cm
     import numpy as np
     axis.cla()
     axis.set_xlim([-1, 1])
     axis.set_ylim([-1, 1])
     axis.set_zlim([-1, 1])
     # draw sphere
     u, v = np.mgrid[0:2 * np.pi:200j, 0:np.pi:100j]
     x = np.cos(u) * np.sin(v)
     y = np.sin(u) * np.sin(v)
     z = np.cos(v)
     axis.plot_wireframe(x, y, z, color="gray", linewidth=0.1)
     axis.set_xticks([-1, 0, 1])
     axis.set_yticks([-1, 0, 1])
     axis.set_zticks([-1, 0, 1])
     colors = cm.Paired(np.linspace(0, 1, len(traj_data_x) + 2))
     for ii in range(len(traj_data_x)):
         axis.plot(traj_data_x[ii],
                   traj_data_y[ii],
                   traj_data_z[ii],
                   c=colors[ii],
                   lw=3,
                   label=traj_label[ii])
     axis.legend(fontsize=Abstract2DPlot.font_size)
     axis.tick_params(axis='x',
                      colors='black',
                      labelsize=Abstract2DPlot.font_size,
                      width=2)
     axis.tick_params(axis='y',
                      colors='black',
                      labelsize=Abstract2DPlot.font_size,
                      width=2)
     axis.tick_params(axis='z',
                      colors='black',
                      labelsize=Abstract2DPlot.font_size,
                      width=2)
     axis.set_xlabel(r'M$_x$', fontsize=Abstract2DPlot.font_size)
     axis.set_ylabel(r'M$_y$', fontsize=Abstract2DPlot.font_size)
     axis.set_zlabel(r'M$_z$', fontsize=Abstract2DPlot.font_size)
     return