Exemplo n.º 1
0
def create_colors(lr):
    n_cts = lr.classes_.shape[0]
    color_norm = colors.Normalize(vmin=-n_cts / 3, vmax=n_cts)
    ct_arr = np.arange(n_cts)
    ct_colors = cm.YlOrRd(color_norm(ct_arr))

    return ct_colors
Exemplo n.º 2
0
def plotFluxControlIn3D(r, upperLimit=1, lowerLimit=-1, figsize=(9, 7)):
    '''
    Display the flux control coefficients as a 3D plot

    Args:
        r : reference
           roadrunner instance
        upperlimit : float 
           optional parameter, sets the lower z axis limit
        upperlimit : float
           optional parameter, sets the upper z axis limit
        figsize : tuble of float
           optional: width and heigh of plot in inches

    Example:
       >>> teUtils.plotting.plotFluxControlIn3D (r)
    '''

    import matplotlib.cm as cm
    import matplotlib.colors as colors

    fig = _plt.figure(figsize=figsize)
    ax = fig.add_subplot(111, projection='3d')

    hist = r.getScaledFluxControlCoefficientMatrix()

    xedges = _np.arange(float(hist.shape[0]) + 1)
    yedges = _np.arange(float(hist.shape[1]) + 1)

    # Construct arrays for the anchor positions
    # Note: _np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
    # ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid
    # with indexing='ij'.
    xpos, ypos = _np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
    xpos = xpos.flatten('F')
    ypos = ypos.flatten('F')
    zpos = _np.zeros_like(xpos)

    # Construct arrays with the dimensions for the 16 bars.
    dx = 0.5 * _np.ones_like(zpos)
    dy = dx.copy()
    dz = hist.flatten()

    offset = dz + _np.abs(dz.min())
    fracs = offset.astype(float) / offset.max()
    norm = colors.Normalize(fracs.min(), fracs.max())
    colors = cm.YlOrRd(norm(fracs))

    ax.set_zlim3d(lowerLimit, upperLimit)
    ax.set_zlabel('Control Coefficient')
    ax.set_xlabel('Fluxes')
    ax.set_ylabel('Enzymes')
    ax.w_xaxis.set_ticks(_np.arange(float(hist.shape[0]) + 1))
    ax.w_xaxis.set_ticklabels(r.getReactionIds())
    ax.w_yaxis.set_ticks(_np.arange(float(hist.shape[1]) + 1))
    ax.w_yaxis.set_ticks(ypos + dy / 2.)
    ax.w_yaxis.set_ticklabels(r.getReactionIds())

    ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors, zsort='average')
Exemplo n.º 3
0
def plot_by_group_simple(file_name,
                         coordinates,
                         column,
                         original_table,
                         labels,
                         with_legend=True,
                         hot_colors=False):

    original_table_labels = original_table[column].loc[labels]

    df = pd.DataFrame(
        dict(x=coordinates[:, 0],
             y=coordinates[:, 1],
             label=list(original_table_labels)))
    grouped_labels = sorted(list(set(original_table_labels)))
    # Plot
    plt.figure(figsize=(20, 12), dpi=200)

    fig, ax = plt.subplots()
    ax.margins(0.05)  # Optional, just adds 5% padding to the autoscaling

    if hot_colors == False:
        colors = cm.tab20(np.linspace(0, 1, len(grouped_labels)))
    else:
        colors = cm.YlOrRd(np.linspace(0, 1, len(grouped_labels)))

    plt.ylim((-80, 80))
    plt.xlim((-80, 80))

    for i, l in enumerate(grouped_labels):

        subset = df.loc[df['label'] == l]

        if with_legend == True:
            ax.scatter(subset['x'],
                       subset['y'],
                       marker='o',
                       label=l,
                       s=0.05,
                       c=colors[i, :],
                       alpha=0.5)
        else:
            ax.scatter(subset['x'],
                       subset['y'],
                       marker='o',
                       s=0.05,
                       c=colors[i, :],
                       alpha=0.5)

    if with_legend == True:
        ax.legend(loc='upper right', prop={'size': 7})
    path = 'results_lsa/' + file_name
    plt.savefig(path, dpi=200)
Exemplo n.º 4
0
def plot_tangent_one_file(bspline_course, tangent_bspline, normal_bspline,
                          bspline_course_tck_3, tangent_bspline_tck_3,
                          normal_bspline_tck_3, bspline_course_tck_5,
                          tangent_bspline_tck_5, normal_bspline_tck_5):
    greens = cm.YlGn(np.linspace(0, 1, 10))
    reds = cm.YlOrRd(np.linspace(0, 1, 10))

    pyplot.figure(figsize=(8, 7))
    pyplot.ylabel('x-axis component of the vector', fontsize=12)
    pyplot.xlabel('x(m)', fontsize=12)
    pyplot.plot(bspline_course_tck_3.x,
                tangent_bspline_tck_3.x,
                '-',
                color=reds[9],
                label='Tangent 3rd Degree B-spline')
    pyplot.plot(bspline_course_tck_5.x,
                tangent_bspline_tck_5.x,
                '--',
                color=reds[6],
                label='Tangent 5th Degree B-spline')
    pyplot.plot(bspline_course.x,
                tangent_bspline.x,
                '-',
                color=reds[3],
                label='Tangent Bezier curve')

    pyplot.plot(bspline_course_tck_3.x,
                normal_bspline_tck_3.x,
                '-',
                color=greens[9],
                label='Normal 3rd Degree B-spline')
    pyplot.plot(bspline_course_tck_5.x,
                normal_bspline_tck_5.x,
                '--',
                color=greens[6],
                label='Normal 5th Degree B-spline')
    pyplot.plot(bspline_course.x,
                normal_bspline.x,
                '-',
                color=greens[3],
                label='Normal Bezier curve')
    pyplot.legend(loc='upper right',
                  bbox_to_anchor=(2, 1.0),
                  shadow=False,
                  ncol=2,
                  fontsize=12)
    pyplot.show()
Exemplo n.º 5
0
def get_hurricane():
    u = np.array([[2.444, 7.553], [0.513, 7.046], [-1.243, 5.433],
                  [-2.353, 2.975], [-2.578, 0.092], [-2.075, -1.795],
                  [-0.336, -2.870], [2.609, -2.016]])
    u[:, 0] -= 0.098
    codes = [1] + [2] * (len(u) - 2) + [2]
    u = np.append(u, -u[::-1], axis=0)
    codes += codes

    return mpath.Path(3 * u, codes, closed=False)


low = cm.GnBu_r(np.linspace(0.01, 0.9, 128))
mid = np.ones((50, 4))
high = cm.YlOrRd(np.linspace(0.1, 0.95, 128))
colors = np.vstack((low, mid, high))
bwr = LinearSegmentedColormap.from_list('my_colormap', colors)  #, N=24)
bwr.set_over = 'darkbrown'
bwr.set_under = 'magemta'
bwr.set_bad = 'k'

plevs = [950, 850, 500, 300, 200]


def metpy_read_wrf(tidx, froms, froms0, fwrf, lons_out, lats_out):

    wrfin = Dataset(fwrf)

    ds = xr.Dataset()
Exemplo n.º 6
0
def plot_smoothing_tangent_normal(course):
    arc_length = compute_arc_length(course)
    #d_hz = arc_length / len(course.x)
    d_hz = arc_length / 1000

    smoothing = 0.0
    b1 = bspline3Dtck(course, 3, smoothing, d_hz)
    db1 = deriv_bspline3Dtck(1, course, 3, smoothing, d_hz)
    tangent_b1, normal_b1, binormal_b1 = getParallelTransportVectors(db1)
    b1x, error1 = compute_position_error(course, b1)

    smoothing = 0.0000001
    b2 = bspline3Dtck(course, 3, smoothing, d_hz)
    db2 = deriv_bspline3Dtck(1, course, 3, smoothing, d_hz)
    tangent_b2, normal_b2, binormal_b2 = getParallelTransportVectors(db2)
    b2x, error2 = compute_position_error(course, b2)

    smoothing = 0.0000003
    b3 = bspline3Dtck(course, 3, smoothing, d_hz)
    db3 = deriv_bspline3Dtck(1, course, 3, smoothing, d_hz)
    tangent_b3, normal_b3, binormal_b3 = getParallelTransportVectors(db3)
    b3x, error3 = compute_position_error(course, b3)

    smoothing = 0.0000006
    b4 = bspline3Dtck(course, 3, smoothing, d_hz)
    db4 = deriv_bspline3Dtck(1, course, 3, smoothing, d_hz)
    tangent_b4, normal_b4, binormal_b4 = getParallelTransportVectors(db4)
    b4x, error4 = compute_position_error(course, b4)

    smoothing = 0.0000012
    b5 = bspline3Dtck(course, 3, smoothing, d_hz)
    db5 = deriv_bspline3Dtck(1, course, 3, smoothing, d_hz)
    tangent_b5, normal_b5, binormal_b5 = getParallelTransportVectors(db5)
    b5x, error5 = compute_position_error(course, b5)

    greens = cm.YlGn(np.linspace(0, 1, 10))
    reds = cm.YlOrRd(np.linspace(0, 1, 10))

    pyplot.figure(figsize=(8, 7))
    pyplot.ylabel('Absolute position error (mm)', fontsize=12)
    pyplot.xlabel('x(m)', fontsize=12)
    #pyplot.plot(b1x, error1,'r-', label='s=0')
    pyplot.plot(b2x, error2, 'r--', label='s=1E-7')
    pyplot.plot(b3x, error3, 'y-', label='s=3E-7')
    pyplot.plot(b4x, error4, 'g--', label='s=6E-7')
    pyplot.plot(b5x, error5, 'b-', label='s=12E-7')
    pyplot.legend(loc='upper right',
                  bbox_to_anchor=(1.0, 1.0),
                  shadow=False,
                  ncol=1,
                  fontsize=12)
    pyplot.show()

    pyplot.figure(figsize=(8, 7))
    pyplot.ylabel('y(m)', fontsize=12)
    pyplot.xlabel('x(m)', fontsize=12)
    pyplot.plot(b2.x, b2.y, 'r--', label='s=1E-7')
    pyplot.plot(b3.x, b3.y, 'y-', label='s=3E-7')
    pyplot.plot(b4.x, b4.y, 'g--', label='s=6E-7')
    pyplot.plot(b5.x, b5.y, 'b-', label='s=12E-7')
    pyplot.plot(course.x,
                course.y,
                'k*',
                markersize=8,
                label='Tow Course received')
    pyplot.legend(loc='lower right',
                  bbox_to_anchor=(1.0, 0.00),
                  shadow=False,
                  ncol=1,
                  fontsize=12)
    pyplot.show()

    pyplot.figure(figsize=(8, 7))
    pyplot.ylabel('x-axis component of the vector', fontsize=12)
    pyplot.xlabel('x(m)', fontsize=12)
    pyplot.plot(b1.x, tangent_b1.x, '-', color=reds[9], label='Tangent s=0')
    pyplot.plot(b2.x,
                tangent_b2.x,
                '--',
                color=reds[8],
                label='Tangent s=1E-7')
    pyplot.plot(b3.x, tangent_b3.x, '-', color=reds[7], label='Tangent s=3E-7')
    pyplot.plot(b4.x,
                tangent_b4.x,
                '--',
                color=reds[6],
                label='Tangent s=6E-7')
    pyplot.plot(b5.x,
                tangent_b5.x,
                '-',
                color=reds[3],
                label='Tangent s=12E-7')

    pyplot.plot(b1.x, normal_b1.x, '-', color=greens[9], label='Normal s=0')
    pyplot.plot(b2.x,
                normal_b2.x,
                '--',
                color=greens[8],
                label='Normal s=1E-7')
    pyplot.plot(b3.x, normal_b3.x, '-', color=greens[7], label='Normal s=3E-7')
    pyplot.plot(b4.x,
                normal_b4.x,
                '--',
                color=greens[6],
                label='Normal s=6E-7')
    pyplot.plot(b5.x,
                normal_b5.x,
                '-',
                color=greens[3],
                label='Normal s=12E-7')
    pyplot.legend(loc='upper right',
                  bbox_to_anchor=(1.7, 1.0),
                  shadow=False,
                  ncol=2,
                  fontsize=12)

    pyplot.show()
Exemplo n.º 7
0
def display_closestwords_tsnescatterplot(model, word, topn, size,
                                         approved_drugs, other_drugs,
                                         drug_stages):

    arr = np.empty((0, size), dtype='f')
    word_labels = [word]
    close_words = model.wv.similar_by_word(word, topn)
    arr = np.append(arr, np.array([model.wv[word]]), axis=0)
    for wrd_score in close_words:
        wrd_vector = model.wv[wrd_score[0]]
        word_labels.append(wrd_score[0])
        arr = np.append(arr, np.array([wrd_vector]), axis=0)

    tsne = TSNE(n_components=2, random_state=0)
    np.set_printoptions(suppress=True)
    Y = tsne.fit_transform(arr)
    x_coords = Y[:, 0]
    y_coords = Y[:, 1]

    plt.figure()
    # plt.scatter(x_coords, y_coords,5,'gray',alpha=0.3) # to plot a scatter dot for every word
    colors = [cm.YlOrRd(x)
              for x in np.linspace(0, 1, 6)]  # split colormap into 6
    for label, x, y in zip(word_labels, x_coords, y_coords):
        # plt.annotate(label, xy=(x, y), xytext=(0, 0), textcoords='offset points') # to plot every word in text
        if label in approved_drugs:
            plt.text(x,
                     y,
                     label,
                     bbox=dict(facecolor=colors[5], alpha=0.5),
                     fontsize=text_size)
        elif label in other_drugs:
            label_stage = drug_stages[other_drugs.index(
                label)]  # find index of the drug to return its stage in trials
            if label_stage == 0:
                plt.text(x,
                         y,
                         label,
                         bbox=dict(facecolor=colors[int(label_stage)],
                                   alpha=0.5),
                         fontsize=text_size)
            elif label_stage == 1:
                plt.text(x,
                         y,
                         label,
                         bbox=dict(facecolor=colors[int(label_stage)],
                                   alpha=0.5),
                         fontsize=text_size)
            elif label_stage == 2:
                plt.text(x,
                         y,
                         label,
                         bbox=dict(facecolor=colors[int(label_stage)],
                                   alpha=0.5),
                         fontsize=text_size)
            elif label_stage == 3:
                plt.text(x,
                         y,
                         label,
                         bbox=dict(facecolor=colors[int(label_stage)],
                                   alpha=0.5),
                         fontsize=text_size)
            elif label_stage == 4:
                plt.text(x,
                         y,
                         label,
                         bbox=dict(facecolor=colors[int(label_stage)],
                                   alpha=0.5),
                         fontsize=text_size)

    plt.xlim(x_coords.min() + 0.5, x_coords.max() + 0.5)
    plt.ylim(y_coords.min() + 0.5, y_coords.max() + 0.5)
    plt.show()
Exemplo n.º 8
0
def plot_by_group(file_name,
                  coordinates,
                  column,
                  original_table,
                  labels,
                  with_legend=True,
                  hot_colors=False):
    original_table_treated = original_table[[column, 'product',
                                             'count']].set_index('product')
    #    labels = [str(label) for label in list(labels)]
    original_table_labels = original_table_treated[column].loc[labels]
    original_table_size = original_table_treated['count'].loc[labels]

    df = pd.DataFrame(
        dict(x=coordinates[:, 0],
             y=coordinates[:, 1],
             size=(40 * np.asarray(original_table_size) /
                   np.max(np.asarray(original_table_size)))**2,
             label=list(original_table_labels)))
    grouped_labels = sorted(list(set(original_table_labels)))
    # Plot
    plt.figure(figsize=(20, 12), dpi=200)

    fig, ax = plt.subplots()
    ax.margins(0.05)  # Optional, just adds 5% padding to the autoscaling

    if hot_colors == False:
        colors = cm.tab20(np.linspace(0, 1, len(grouped_labels)))
    else:
        colors = cm.YlOrRd(np.linspace(0, 1, len(grouped_labels)))

    plt.ylim((-80, 80))
    plt.xlim((-80, 80))

    for i, l in enumerate(grouped_labels):

        subset = df.loc[df['label'] == l]

        if l == -1:
            ax.scatter(subset['x'],
                       subset['y'],
                       marker='o',
                       label=l,
                       s=subset['size'],
                       c='black',
                       alpha=0.5)
        else:

            if with_legend == True:
                ax.scatter(subset['x'],
                           subset['y'],
                           marker='o',
                           label=l,
                           s=subset['size'],
                           c=colors[i, :],
                           alpha=0.5)
            else:
                ax.scatter(subset['x'],
                           subset['y'],
                           marker='o',
                           s=subset['size'],
                           c=colors[i, :],
                           alpha=0.5)

    if with_legend == True:
        ax.legend(loc='upper right', prop={'size': 7})
    path = 'results_glove3/' + file_name
    plt.savefig(path, dpi=200)
def _kripp_subplot(krippendorph_summary,
                   axis,
                   what,
                   is_agreement,
                   cutoff=None):
    """"""
    minx = np.min(krippendorph_summary.loc[:, f'n_matches'])
    maxx = np.max(krippendorph_summary.loc[:, f'n_matches'])
    if is_agreement:

        # annotate agreement ranges
        _annotate_krippendorph_ranges(axis=axis,
                                      minx=minx,
                                      maxx=maxx,
                                      shades=False)

    mx = 0
    for min_iou in [0.75, 0.5, 0.25]:
        ksummary = krippendorph_summary.loc[
            krippendorph_summary.loc[:, 'min_iou'] >= min_iou - 0.005, :]
        ksummary = ksummary.loc[ksummary.loc[:,
                                             'min_iou'] < min_iou + 0.005, :]
        x = ksummary.loc[:, f'n_matches']
        if is_agreement:
            y = ksummary.loc[:, what]
        else:
            # y = 100 * ksummary.loc[:, what] / np.max(
            #     ksummary.loc[:, what].values)
            y = ksummary.loc[:, what]
            mx = np.max([np.max(y), mx])
        axis.plot(
            x,
            y,
            marker='o',
            # marker='o' if min_iou == miniou else '.',
            linestyle='-',
            # linestyle='-' if min_iou == miniou else '--',
            # linewidth=2. if min_iou == miniou else 1.,
            linewidth=1.5,
            c=mcmap.YlOrRd(min_iou + 0.2),
            # alpha=1. if min_iou == miniou else 0.7,
            label='min_iou=%.2f' % min_iou)

    axis.xaxis.set_major_locator(MaxNLocator(integer=True))
    if is_agreement:
        ymin = -0.02  # -0.22
        ymax = 1.02
    else:
        ymin = -mx * 0.02
        ymax = mx * 1.02
        # axis.set_ylim(0, 100)
        axis.set_ylim(ymin=0)
    minx = minx * 0.98
    maxx = maxx * 1.02
    if cutoff is not None:
        axis.fill_betweenx(y=[ymin, ymax],
                           x1=minx,
                           x2=cutoff - 0.2,
                           color='gray',
                           alpha=0.2)
    axis.set_ylim(ymin, ymax)
    axis.set_xlim(minx, maxx)
    axis.legend(fontsize=8)
    axis.set_title(what.replace('_', ' '), fontsize=14, fontweight='bold')
    axis.set_xlabel(f'At least x participants per anchor', fontsize=12)
    axis.set_ylabel(
        # 'Krippendorph Alpha' if is_agreement else '% anchors kept',
        'Krippendorph Alpha' if is_agreement else 'No. of anchors',
        fontsize=12)
Exemplo n.º 10
0
#bounds = np.linspace(0,120,21)
#norm = colors.BoundaryNorm(bounds, ncolors=256)
#print norm(100)

#sys.exit()

for key, value in patches.iteritems():
    print key + " " + str(color[key])
    if radflux == 'diffuse':
        ax.add_collection(PatchCollection(value,\
            facecolor=cm.YlGnBu_r(norm(color[key])),\
            cmap=cm.YlGnBu_r, edgecolor='k', linewidth=1., zorder=2))
    else:
        ax.add_collection(PatchCollection(value,\
            facecolor=cm.YlOrRd(norm(color[key])),\
            cmap=cm.YlOrRd, edgecolor='k', linewidth=1., zorder=2))

#    ax.add_collection(PatchCollection(value, facecolors=color[key], cmap=cm.RdYlBu, edgecolor='k',
#        linewidth=1., zorder=2, norm=norm))

### Plot colorbar
#set room for colorbar
fig.subplots_adjust(right=0.85)

axcb = fig.add_axes([0.87, 0.15, 0.03, 0.7])

cb = mpl.colorbar.ColorbarBase(axcb,
                               cmap=cmap,
                               norm=norm,
                               boundaries=bounds,