Beispiel #1
0
def plot_sentiment(df_sentiment):
    """ ---------------------------------------------------------
    CREDITS TO: 
    http://stackoverflow.com/questions/31313606/pyplot-matplotlib
    -bar-chart-with-fill-color-depending-on-value 
    ------------------------------------------------------------

    This function plot the sentiment analysis for the country. 
    
    It takes as input:
    
    @df_sentiment"""

    # Set up colors : red to green
    plt.figure(figsize=(17, 6))
    y = np.array(df_sentiment['sentiment'])
    colors = cm.YlGn(y / float(max(y)))
    plot = plt.scatter(y, y, c=y, cmap='YlGn')
    plt.clf()
    clb = plt.colorbar(plot)
    clb.ax.set_title("Sentiment")

    # Display bar plot : country frequency vs. country name, with color indicating polarity score
    plt.bar(range(df_sentiment.shape[0]),
            df_sentiment['mention'],
            tick_label=df_sentiment.index,
            color=colors)
    plt.xticks(rotation=45, ha='right')
    plt.xlabel("Country")
    plt.ylabel("Mentions")
    plt.title('Sentiment analysis per country', fontsize=15)
    plt.show()
Beispiel #2
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()
Beispiel #3
0
def get_cmaps_biasCNN():
    """ 
  Create color maps
  """

    nsteps = 8
    colors_all_1 = np.moveaxis(
        np.expand_dims(cm.Greys(np.linspace(0, 1, nsteps)), axis=2), [0, 1, 2],
        [0, 2, 1])
    colors_all_2 = np.moveaxis(
        np.expand_dims(cm.GnBu(np.linspace(0, 1, nsteps)), axis=2), [0, 1, 2],
        [0, 2, 1])
    colors_all_3 = np.moveaxis(
        np.expand_dims(cm.YlGn(np.linspace(0, 1, nsteps)), axis=2), [0, 1, 2],
        [0, 2, 1])
    colors_all_4 = np.moveaxis(
        np.expand_dims(cm.OrRd(np.linspace(0, 1, nsteps)), axis=2), [0, 1, 2],
        [0, 2, 1])
    colors_all = np.concatenate((colors_all_1[np.arange(2, nsteps, 1), :, :],
                                 colors_all_2[np.arange(2, nsteps, 1), :, :],
                                 colors_all_3[np.arange(2, nsteps, 1), :, :],
                                 colors_all_4[np.arange(2, nsteps, 1), :, :],
                                 colors_all_2[np.arange(2, nsteps, 1), :, :]),
                                axis=1)

    int_inds = [3, 3, 3, 3]
    colors_main = np.asarray(
        [colors_all[int_inds[ii], ii, :] for ii in range(np.size(int_inds))])
    colors_main = np.concatenate((colors_main, colors_all[5, 1:2, :]), axis=0)
    # plot the color map
    #plt.figure();plt.imshow(np.expand_dims(colors_main,axis=0))
    colors_sf = np.moveaxis(
        np.expand_dims(cm.GnBu(np.linspace(0, 1, 8)), axis=2), [0, 1, 2],
        [0, 2, 1])
    colors_sf = colors_sf[np.arange(2, 8, 1), :, :]

    return colors_main, colors_sf
Beispiel #4
0
def plot(data, fname='capacity-factors-usa.png'):
    labels, values = zip(*sorted(data['val'].items()))
    labels = [label.capitalize() for label in labels]
    values = np.array(values)
    width = 0.35
    index = np.arange(len(labels))

    fig, ax = plt.subplots()
    colors = cm.YlGn(values / 100.0)
    bars = ax.bar(index, values, width, color=colors)

    plt.title(data['title'])
    ax.set_ylabel('Capacity factor (%)')
    ax.set_xticks(index)
    ax.set_xticklabels(labels)
    ax.set_yticks(np.arange(0, 101, 10))
    ax.grid(color='0.7', linestyle='--', axis='y')
    plt.xticks(rotation=90)
    plt.tight_layout()

    if fname:
        plt.savefig(fname)
    else:
        plt.show()
Beispiel #5
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()
Beispiel #6
0
    def update_tree_values(self):
        """
        Update the tree created in add_tree_node with values of Nsa, Ns, Ps, Qsa and Usa. Colour each of the nodes
        with a colour representing their values.
        Note that nodes on the tree are represented as (s_t, a_(t-1), p_t) which means that when calling Qsa, Usa
        or Nsa (ones involving a) we need to use (s_(t-1), a_(t-1), p_(t-1)), as opposed to Ns and Ps, where we use
        (s_t, p_t).
        """
        tree_itr = self.tree.traverse()
        root = next(tree_itr)   # skip the first two nodes the root and the root's root (not sure why there's 2?)
        root_face = TextFace(u'(s\u209C, a\u209C\u208B\u2081, agent\u209C) = ({}, {}, {}, Ns={})'.format(
            [float(dim) / g_accuracy for dim in root.name],
            root.action, root.agent, self.Ns[root.name]))
        root_face.background.color = '#FF0000'
        root.add_face(root_face, column=0, position="branch-top")

        for node in tree_itr:
            s, a, agent = node.up.name, node.action, node.up.agent
            p_from_a = node.agent
            state = [float(dim) / g_accuracy for dim in node.name]
            # note that (s, a) is the same as node.name (since parent state & action taken from there = child state)
            try:
                delattr(node, "_faces")     # need to remove previously added faces otherwise they stack
            except:
                pass
            _, v = self.nnet.predict(np.array(state), p_from_a)

            # -------- ADD ANNOTATION FOR STATE LOSS AND ACTION TAKEN ----------
            loss = self.env.state_loss(state=state)
            # unicode to get subscripts
            loss_face = TextFace(u'(x\u209C, u\u209C\u208B\u2081, agent\u209C) = ({0}, {1}, {2}),  c(x\u209C) = {3:.3f}, v_pred = {4:.3f}'.format(self.env.round_state(state=state), a, p_from_a, loss, v))
            c_loss = cm.viridis(255+int(loss*255))  # viridis goes from 0-255
            c_loss = "#{0:02x}{1:02x}{2:02x}".format(*[int(round(i * 255)) for i in [c_loss[0], c_loss[1], c_loss[2]]])
            loss_face.background.color = c_loss   # need rgb colour in hex, "#FFFFFF"=(255, 255, 255)
            node.add_face(loss_face, column=0, position="branch-top")

            # -------- ADD ANNOTATION FOR ACTION VALUE WRT agent, Q --------
            #print("s={}, a={}, agent={}".format(s, a, agent))
            if (s, a) in self.Qsa:

                #print(self.Ns[s])
                #print(self.Nsa[(s, a)])
                #print(self.Ps[s][a])
                q = self.Qsa[(s, a)] if agent == 0 else -self.Qsa[(s, a)]
                ucb = self.args.cpuct * self.Ps[s][a]*np.sqrt(self.Ns[s])/(1+self.Nsa[(s, a)])
                u = self.Usa[(s, a)]
            else:
                q = 0
                ucb = self.args.cpuct * self.Ps[node.name][a]*np.sqrt(self.Ns[s] + EPS)
                u = ucb
            q_formula = '(Q(x))' if agent == 0 else '(-Q(x))'
            QA_face = TextFace("U\u209C = {:.3f}{} + {:.3f}(ucb) = {:.3f}".format(q, q_formula, ucb, u))

            c_value = cm.viridis(255+int((q+ucb)*255))  # plasma goes from 0-255
            c_value = "#{0:02x}{1:02x}{2:02x}".format(
                *[int(round(i * 255)) for i in [c_value[0], c_value[1], c_value[2]]])
            QA_face.background.color = c_value
            node.add_face(QA_face, column=0, position="branch-bottom")

            # -------- ADD ANNOTATION FOR NUMBER OF VISITS -------
            # have to use node.name for printing Ns
            ns = 0 if node.name not in self.Ns else self.Ns[node.name]
            N_face = TextFace(" Nsa(x\u209C\u208B\u2081, u\u209C)={}, Ns(x)={}".format(self.Nsa[(s, a)], ns))

            c_vis = cm.YlGn(int(255*(1-self.Nsa[(s, a)]/(self.args.numMCTSSims*2))))  # YlGn goes from 0-255
            c_vis = "#{0:02x}{1:02x}{2:02x}".format(*[int(round(i * 255)) for i in [c_vis[0], c_vis[1], c_vis[2]]])
            N_face.background.color = c_vis
            node.add_face(N_face, column=1, position="branch-bottom")
    freq = [0.0] * 10
    #print (bins)
    for idx in range(len(freq_list)):
        bins_ = bins_list[idx]
        freq_ = freq_list[idx]
        for i in range(len(bins_)):
            if (bins_[i] <= bins[i + 1] and bins_[i] >= bins[i]):
                freq[i] += freq_[i]
    repr_bins = []  # 10 bins for plotting, take average of each period
    for i in range(len(bins) - 1):
        repr_bins.append((bins[i] + bins[i + 1]) / 2.0)

    return repr_bins, freq


colors = cm.YlGn(np.linspace(0, 1, 25))

a = np.loadtxt("act_d_bins.txt")

b = np.loadtxt("act_d_freq.txt")
a = a[:15640]
b = b[:15640]
a = a[:, :
      -1]  # temporary remove last point of bins list. match dimension for plotting.
print("weight shapes")
print(a.shape)
print(b.shape)

a = np.array(np.vsplit(a, 20))
b = np.array(np.vsplit(b, 20))
bins_g_1 = []
freq_g_1 = []
for i in range(25):
    bins,freq = merg_hist(epochs_d_1_1[i], epochs_d_1_2[i] )
    bins_d_1.append(bins)
    freq_d_1.append(freq)
    bins,freq = merg_hist(epochs_d_2_1[i], epochs_d_2_2[i] )
    bins_d_2.append(bins)
    freq_d_2.append(freq)
    bins,freq = merg_hist(epochs_g_1_1[i], epochs_g_1_2[i] )
    bins_g_1.append(bins)
    freq_g_1.append(freq)

#print (bins_d_1)
print ("plotting d1 ")
colors = cm.YlGn(np.linspace(0, 1, len(bins_d_1)))
for i in range(25):
    if (i<=2 or i >= 22):
        plt.plot(bins_d_1[i], freq_d_1[i],marker="+", color=colors[i], label="epoch_"+str(i))
    else :
        plt.plot(bins_d_1[i], freq_d_1[i],marker="+", color=colors[i])
plt.legend(loc="upper left", ncol=1)
plt.savefig ("d_1.pdf")
plt.clf()

print ("plotting d2 ")
colors = cm.YlGn(np.linspace(0, 1, len(bins_d_2)))
for i in range(25):
    if (i<=2 or i >= 22):
        plt.plot(bins_d_2[i], freq_d_2[i],marker="+", color=colors[i], label="epoch_"+str(i))
    else :