Ejemplo n.º 1
0
def test_nan_failure():
    x = np.array([0, 1])
    y = np.array([np.nan, np.nan])

    line = plt.plot(x, y, label='test')[0]
    with assert_raises(Exception):
        labelLine(line, 0.5)
def visualise_circuit_with_plt(circuit, time_between_frames=0.5, legend=False):
    matplotlib.use('Tkagg')
    xmin, xmax, ymin, ymax = circuit.getExtremeLatLongs()
    xvals = []
    i = 0

    plt.xlim(left=xmin - 0.0001, right=xmax + 0.0001)
    plt.ylim(bottom=ymin - 0.0001, top=ymax + 0.0001)

    for edge in circuit.edges:
        i += 1
        plt.plot(np.array(edge.path.lats),
                 np.array(edge.path.longs),
                 label=str(i))

        if legend:
            s = 0
            for x in edge.path.lats:
                s += x
            xvals.append(s / edge.path.len)
            labelLine(plt.gca().get_lines()[-1], s / edge.path.len)

        plt.pause(time_between_frames)

    plt.show()
Ejemplo n.º 3
0
def test_negative_spacing():
    plt.clf()
    x = np.linspace(1, -1)
    y = x**2

    line = plt.plot(x, y)[0]

    # Should not throw an error
    labelLine(line, 0.2, label='Test')
Ejemplo n.º 4
0
	def Update_Extrinsic_DefectsDiagram_Plot(self):
		
		# Update defect formation energy of dopant
		self.extrinsic_defect_plots[self.extrinsic_defect].set_ydata(self.extrinsic_defects_enthalpy_data[self.extrinsic_defect])
		
		# Remove labels before redrawing them at new positions
		#self.ternary_defects_diagram_plot_drawing.texts.clear()
		labelLine(self.extrinsic_defect_plots[self.extrinsic_defect], x=(self.ECBM-self.EVBM)/2., align=False)
		
		# Draw defects diagram canvas
		self.ternary_defects_diagram_plot_canvas.draw()
Ejemplo n.º 5
0
	def Initialize_Extrinsic_DefectsDiagram_Plot(self):
		
		# Plot defect formation energy of dopant
		defect_label = r"$"+self.extrinsic_defect.split("_")[0]+"_{"+self.extrinsic_defect.split("_")[-1]+"}$"
		self.extrinsic_defect_plots[self.extrinsic_defect], = self.ternary_defects_diagram_plot_drawing.plot(self.fermi_energy_array - self.EVBM, self.extrinsic_defects_enthalpy_data[self.extrinsic_defect], label = defect_label)
		
		# Create label for each defect	
		labelLine(self.extrinsic_defect_plots[self.extrinsic_defect], x=(self.ECBM-self.EVBM)/2., align=False)
		
		# Draw defects diagram canvas
		self.ternary_defects_diagram_plot_canvas.draw()
Ejemplo n.º 6
0
def test_nan_warning():
    x = np.array([0, 1, 2, 3])
    y = np.array([np.nan, np.nan, 0, 1])

    line = plt.plot(x, y, label='test')[0]

    with warnings.catch_warnings(record=True) as w:
        labelLine(line, 0.5)
        assert issubclass(w[-1].category, UserWarning)
        assert "could not be annotated" in str(w[-1].message)

    with warnings.catch_warnings(record=True) as w:
        labelLine(line, 2.5)
        assert len(w) == 0
Ejemplo n.º 7
0
    def show_faces(self, labels=False):
        """
        Shows the underlying map overlaid with the faces. Useful for debugging.
        Also, the labels might look a bit crowded, but just zoom in on the
        figure to make everything look pretty.
        :returns:   None
        """
        # Generate the basemap.
        basemap = self.df.plot(color="w", edgecolor="lightgrey")

        # Plot each vertex. If the user wants labels, label the vertices as well.
        for vertex in self.adjacency:
            basemap.plot(vertex.x, vertex.y, "ko", markersize=4)
            if labels:
                basemap.text(vertex.x, vertex.y, vertex.label)

        # Since labellines doesn't like things being out of order, change the
        # ordering of the x and y coordinates based on which one's bigger.
        for face in self.faces:
            for edge in face:
                x = []

                if edge.tail.x > edge.head.x:
                    x = [edge.head.x, edge.tail.x]
                    y = [edge.head.y, edge.tail.y]
                else:
                    x = [edge.tail.x, edge.head.x]
                    y = [edge.tail.y, edge.head.y]

                # Plot the line.
                line, = basemap.plot(x, y, "black")

                # If the user wants the lines to be labeled, add a label in the
                # middle of the line.
                if labels:
                    labelLine(line,
                              abs(edge.head.x + edge.tail.x) / 2,
                              label=f"({edge.head.label},{edge.tail.label})")

            x, y = [e.head.x for e in face], [e.head.y for e in face]

            if len(x) < 10:
                basemap.fill(x, y, "red", alpha=0.25)

        plt.axis("off")
        plt.show()
Ejemplo n.º 8
0
def test_label_range():
    x = np.linspace(0, 1)
    line = plt.plot(x, x**2)[0]

    # This should fail
    with assert_raises(Exception):
        labelLine(line, -1)
    with assert_raises(Exception):
        labelLine(line, 2)

    # This should work
    labelLine(line, 0.5)
Ejemplo n.º 9
0
    # Add year under month for each label
    ticks[i] = str(months[month]) + '\n' + str(new_tick.year)

# Set new ticks
ax.set_xticklabels(ticks)

# Set Y-axis to start from 0
plt.ylim(0, 10)

# Get label lines
lines = plt.gca().get_lines()

# Draw in-line labels one by one
for line in lines:

    # Divide the number of posts by two and use the mid-point as label position
    labelLine(line, (len(posts) / 2), align=True)

# Set axis labels
plt.xlabel('Date', fontsize=13)  # Set x-axis label
plt.ylabel('Languages', fontsize=13)  # Set y-axis label

# Save the figure to PDF to the directory with the data
plt.savefig('regplot_rich.pdf', bbox_inches='tight')

# Show the plot
plt.show()

# Print status
print("[INFO] ... Done.")
Ejemplo n.º 10
0
            covs[35][:, 3],
            ':k',
            linewidth=3,
        )

        ax.set_xlabel('Length [mm]')
        ax.set_ylabel('$\Theta_k$ [-]')
        ax.axis((0.0, zcoord[-1], 1e-3, 1))
        ax.legend(loc='best')
        ax.legend(frameon=False)

        #Get lines data
        lines = plt.gca().get_lines()

        #Label each line
        labelLine(lines[0], 3, label='H$^*$', align=False, fontsize=20)
        labelLine(lines[1], 7, label='CO$^*$', align=False, fontsize=20)

        labelLine(lines[2], 5, label='H$^*$', align=False, fontsize=20)
        labelLine(lines[3], 7, label='CO$^*$', align=False, fontsize=20)

        labelLine(lines[4], 7, label='H$^*$', align=False, fontsize=20)
        labelLine(lines[5], 7, label='CO$^*$', align=False, fontsize=20)

    if vis == 4:

        #SA results for full mech.
        sa_all = wgs_nib_full_sa['sm_all']

        ax = fig.add_subplot(111)
        ax.plot(wgs_nib_full_sa['Tout'],
Ejemplo n.º 11
0
def plot_decision_boundary_distances(model,
                                     X,
                                     Y,
                                     feat_crosses=None,
                                     axis_lines=False,
                                     save=False):
    """
    Plots decision boundary

    Args:
        model: neural network layer and activations in lambda function
        X: Data in shape (num_of_examples x features)
        feat_crosses: list of tuples showing which features to cross
        axis_lines: Draw axis lines at x=0 and y=0(bool, default False)
        save: flag to save plot image
    """

    # first plot the data to see what is the size of the plot
    plt.scatter(X[:, 0], X[:, 1], s=200, c=np.squeeze(Y))

    # get the x and y range of the plot
    x_ticks = plt.xticks()[0]
    y_ticks = plt.yticks()[0]

    plt.clf()  # clear figure after getting size

    # Generate a grid of points between min_x_point-0.5 and max_x_point+0.5 with 1000 points in between,
    # similarly, for y points
    xs = np.linspace(min(x_ticks) - 0.5, max(x_ticks) + 0.5, 1000)
    ys = np.linspace(max(y_ticks) + 0.5, min(y_ticks) - 0.5, 1000)
    xx, yy = np.meshgrid(xs, ys)  # create data points
    # Predict the function value for the whole grid

    prediction_data = np.c_[xx.ravel(), yy.ravel()]
    # add feat_crosses if provided
    if feat_crosses:
        for feature in feat_crosses:
            prediction_data = np.c_[prediction_data,
                                    prediction_data[:, feature[0]] *
                                    prediction_data[:, feature[1]]]

    Z = model(prediction_data)
    Z = Z.reshape(xx.shape)

    # Plot the contour and training examples
    plt.style.use('seaborn-whitegrid')
    c = plt.contour(xx, yy, Z,
                    cmap='Blues')  # draw a blue colored decision boundary
    plt.title('Distances from Decision Boundary', size=18)
    plt.xlabel('$x_1$', size=20)
    plt.ylabel('$x_2$', size=20)
    if axis_lines:
        plt.axhline(0, color='black')
        plt.axvline(0, color='black')

    # color map 'cmap' maps 0 labeled data points to red and 1 labeled points to green
    cmap = matplotlib.colors.ListedColormap(["red", "green"],
                                            name='from_list',
                                            N=None)
    plt.scatter(X[:, 0],
                X[:, 1],
                s=200,
                c=np.squeeze(Y),
                marker='x',
                cmap=cmap)  # s-> size of marker

    points = X  # data points from to which perpendicular lines are drawn
    v = c.collections[0].get_paths(
    )[0].vertices  # returns two points from the decision line(visible start & end point)
    P1 = np.expand_dims(np.asarray((v[0, 0], v[0, 1])),
                        axis=0)  # the visible start point of the line
    P2 = np.expand_dims(np.asarray((v[-1, 0], v[-1, 1])),
                        axis=0)  # the visible end point of the line

    inter_points, distances = point_on_line(P1, P2, points)

    # combine the intersection points so that they're in the format required by `plt.plot` so
    # each list item is:
    # [(x_1,x_2), (y_1, y_2), len_of_line]
    perpendicular_line_points = [
        list(zip(a, b)) + [c]
        for a, b, c in zip(points, inter_points, distances)
    ]

    # plot and label perpendicular lines to the decision boundary one by one
    # labelLine function comes from https://github.com/cphyc/matplotlib-label-lines/tree/master/labellines/baseline
    for line in perpendicular_line_points:
        x_points = np.clip(
            line[0], a_min=-0.5,
            a_max=1.5)  # clip lines going out of bounds of visible area
        y_points = np.clip(line[1], a_min=-0.5, a_max=1.5)
        len = line[2]
        plt.plot(x_points, y_points, 'm--',
                 label='{:.2f}'.format(len))  # print label to 2 decimal places
        labelLine(plt.gca().get_lines()[-1], x=sum(x_points) /
                  2)  # label of the line should be centered, so (x_1+x_2)/2

    if save:
        plt.savefig('decision_boundary_with_distances.png',
                    bbox_inches='tight')

    plt.tight_layout()
    plt.show()