Пример #1
1
def shots4time(player="Noah", team="CHI", s_date="20091001", f_date="20151231", path="D:\Gal\Work\Results"):
    """ """
    actions_1, played_games_1 = actions_raster(
        players=[player], team=team, s_date=s_date, f_date=f_date, path=path, action=c.Shot
    )
    actions_2, played_games_2 = time_raster(player, team, s_date, f_date, path)
    actions_3, played_games_3 = actions_raster(
        players=[player], team=team, s_date=s_date, f_date=f_date, path=path, action=c.FreeThrow
    )

    plt.hold(1)
    # plt.title(player+','+team)
    # plt.plot(actions_1, played_games_1, 'b.')
    # plt.plot(actions_3, played_games_3, 'm.')

    plt.figure(1)
    plt.plot(actions_histogram(actions_1), "b")
    plt.plot(actions_histogram(actions_2), "r")
    plt.plot(actions_histogram(actions_3), "m")

    plt.figure(2)
    plt.title(player + "," + team)
    plt.figtext(0, 0.5, "blue - shots \n" + "red - presentce on court\n" + "magenta - freethrows")
    plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_1), 3)), "b")
    plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_2), 3)), "r")
    plt.plot(tf.normalize(tf.movingAverage(actions_histogram(actions_3), 3)), "m")
    plt.xlabel("Time (in half minutes)")
    plt.ylabel("Points")
    plt.grid(axis="x")
    plt.xticks(np.arange(1, 5) * c.Q_LEN / 30)
    plt.show()
Пример #2
1
def plot_magnitude_time_scatter(catalogue, plot_error=False, filename=None, filetype="png", dpi=300, fmt_string="o"):
    """
    Creates a simple scatter plot of magnitude with time
    :param catalogue:
        Earthquake catalogue as instance of :class:
        hmtk.seismicity.catalogue.Catalogue
    :param bool plot_error:
        Choose to plot error bars (True) or not (False)
    :param str fmt_string:
        Symbology of plot
    """
    plt.figure(figsize=DEFAULT_SIZE)
    dtime = catalogue.get_decimal_time()
    if len(catalogue.data["sigmaMagnitude"]) == 0:
        print "Magnitude Error is missing - neglecting error bars!"
        plot_error = False

    if plot_error:
        plt.errorbar(
            dtime, catalogue.data["magnitude"], xerr=None, yerr=catalogue.data["sigmaMagnitude"], fmt=fmt_string
        )
    else:
        plt.plot(dtime, catalogue.data["magnitude"], fmt_string)
    plt.xlabel("Year", fontsize="large")
    plt.ylabel("Magnitude", fontsize="large")
    plt.title("Magnitude-Time Plot", fontsize="large")

    _save_image(filename, filetype, dpi)
    plt.show()
    return
Пример #3
1
def plot_observed_recurrence(
    catalogue, completeness, dmag, end_year=None, figure_size=DEFAULT_SIZE, filename=None, filetype="png", dpi=300
):
    """
    Plots the observed recurrence taking into account the completeness
    """
    # Get completeness adjusted recurrence table
    if isinstance(completeness, float):
        # Unique completeness
        completeness = np.array([[np.min(catalogue.data["year"]), completeness]])
    if not end_year:
        end_year = catalogue.update_end_year()
    catalogue.data["dtime"] = catalogue.get_decimal_time()
    cent_mag, t_per, n_obs = get_completeness_counts(catalogue, completeness, dmag)
    obs_rates = n_obs / t_per
    cum_obs_rates = np.array([np.sum(obs_rates[i:]) for i in range(len(obs_rates))])

    plt.figure(figsize=figure_size)
    plt.semilogy(cent_mag, obs_rates, "bo", label="Incremental")
    plt.semilogy(cent_mag, cum_obs_rates, "rs", label="Cumulative")
    plt.xlim([cent_mag[0] - 0.1, cent_mag[-1] + 0.1])
    plt.xlabel("Magnitude", fontsize=16)
    plt.ylabel("Annual Rate", fontsize=16)
    plt.legend(fontsize=14)
    plt.tick_params(labelsize=12)
    _save_image(filename, filetype, dpi)
    plt.show()
def plot_sat_mod_plume(sat, mod, month, tmin, tmax):
    """Plots the plume region off of the Columbia river. """
    plt.figure(figsize=(16, 8))
    plt.subplot(1, 2, 1)
    p1 = plt.pcolor(lon_p, lat_p, sat, vmin=tmin, vmax=tmax, cmap="Spectral_r")
    plt.colorbar(p1, label="Temperature $^o$C")
    plt.plot(coast_x, coast_y, "black")
    plt.xlim(min(lon_p), max(lon_p))
    plt.ylim(min(lat_p), max(lat_p))
    plt.xlabel("Longitude")
    plt.ylabel("Latitude")
    plt.title("Plume, Satellite, " + month + " 2005")

    plt.subplot(1, 2, 2)
    p2 = plt.pcolor(lon_p, lat_p, mod, vmin=tmin, vmax=tmax, cmap="Spectral_r")
    plt.colorbar(p2, label="Temperature $^o$C")
    plt.plot(coast_x, coast_y, "black")
    plt.xlim(min(lon_p), max(lon_p))
    plt.ylim(min(lat_p), max(lat_p))
    plt.xlabel("Longitude")
    plt.ylabel("Latitude")
    plt.title("Plume, SELFE Model, " + month + " 2005")
    plt.tight_layout()
    plt.savefig("Images/Plume/sat_mod_" + month + ".png", dpi=300)
    plt.close()
Пример #5
1
    def drawTwoPatterns(self, ori_image, fin_image, name, idx):
        plt.cla()
        ori_image = ori_image.reshape((self.rows, self.cols))
        fin_image = fin_image.reshape((self.rows, self.cols))
        row_labels = range(self.rows)
        col_labels = range(self.cols)

        charDict = {0: "h", 1: "v", 2: "m"}
        fname = "pics_err/{0}_{1}x{2}_{3}".format(name, self.rows, self.cols, charDict[idx])
        # target_fname = "pics/dropPatt_{0}x{1}_{2}_p{3}_output.png".format(self.rows, self.cols, charDict[idx], 0.0)

        # target_img = misc.imread(target_fname, mode='L')

        fig = plt.figure()
        # interpolation='sinc',  interpolation='nearest',
        # plt.subplot(121)
        plt.imshow(ori_image, cmap=plt.get_cmap("gray"), interpolation="nearest", vmin=0, vmax=1)
        # plt.xticks(range(self.cols), col_labels)
        # plt.yticks(range(self.rows), row_labels)
        # plt.title("f = " + nfactor)
        frame1 = plt.gca()
        frame1.axes.get_xaxis().set_visible(False)
        frame1.axes.get_yaxis().set_visible(False)
        fig.savefig(fname + "_input.png", bbox_inches="tight")  # , dpi=fig.dpi

        fig = plt.figure()
        plt.imshow(fin_image, cmap=plt.get_cmap("gray"), interpolation="nearest", vmin=0, vmax=1)
        # plt.xticks(range(self.cols), col_labels)
        # plt.yticks(range(self.rows), row_labels)
        # plt.title("f = " + nfactor)
        frame1 = plt.gca()
        frame1.axes.get_xaxis().set_visible(False)
        frame1.axes.get_yaxis().set_visible(False)
        fig.savefig(fname + "_output.png", bbox_inches="tight")  # , dpi=fig.dpi
 def figureEvents(self):
     longitudes = np.array([event.longitude() for event in self.events])
     latitudes = np.array([event.latitude() for event in self.events])
     plt.figure(1)
     plt.clf()
     img = plt.figure()
     plt.plot(longitudes, latitudes, "o", markerfacecolor="k", markeredgecolor="k", markersize=1)
     importantPointsLongitude = []
     importantPointsLatitude = []
     try:
         importantPointsLongitude = [poi.longitude() for poi in self.stops if not isnan(poi.longitude())]
         importantPointsLatitude = [poi.latitude() for poi in self.stops if not isnan(poi.latitude())]
     except AttributeError:
         importantPointsLongitude = []
         importantPointsLatitude = []
     plt.plot(
         importantPointsLongitude,
         importantPointsLatitude,
         "o",
         markerfacecolor="b",
         markeredgecolor="k",
         markersize=10,
     )
     plt.xlabel("Longitude")
     plt.ylabel("Latitude")
     plt.title(
         "Number of events : {0}, Number of Important places : {1}".format(
             len(self.events), len(importantPointsLongitude)
         )
     )
     # img.savefig("image.png",dpi = 500)
     return img
Пример #7
1
    def CalculateDiffusionConstants(self, dt_per_step, masses, new_only=False):
        import MC_on_pmf

        if not hasattr(self, "diffusion_dir"):
            self.diffusion_dir = os.path.join(self.basedir, "diffusion")
        if not os.path.isdir(self.diffusion_dir):
            os.system("mkdir -p {0}".format(self.diffusion_dir))
        for w in self.windows:
            if new_only == True and hasattr(w, "diffusion_constants"):
                continue
            w.diffusion_constants = []
            data = w.ReadDataFile()
            t = npy.array(data[0]) * dt_per_step
            for cv, xl, m, cv_val, cv_K in zip(self.cv_list, data[1], masses, w.cv_values, w.spring_constants):

                def fun2(t, D, a, b):
                    return _fun(t, cv_K, m, self.temperature, D, a, b)

                x = npy.array(xl)
                # x=x-cv_val
                x = x - npy.mean(x)
                Cx = MC_on_pmf.autocorrelation(x) * npy.mean(x * x)
                t = t - t[0]
                # n=3*npy.argmin(Cx)
                # print n,len(t),len(Cx)
                n = 100
                p, c = curve_fit(fun2, t[:n], Cx[:n], [1.0, 0.0, 1.0])
                plt.figure()
                plt.plot(t[:n], Cx[:n])
                plt.plot(t[:n], fun2(t, *p)[:n], "--", color="r")
                outname = "Ds_cv_{0}_{1}.png".format("_".join([str(el) for el in w.cv_values]), cv.name)
                plt.savefig(os.path.join(self.diffusion_dir, outname))
                plt.close()
                D = p[0]  # D is in A^2/ps
                w.diffusion_constants.append(D)
Пример #8
1
def part2_4():
    data = np.loadtxt("./data/ex1data1.txt", delimiter=",")
    x = data[:, 0]
    y = data[:, 1]
    m = len(y)
    y = y.reshape(m, 1)
    X = np.c_[np.ones((m, 1)), x]
    theta0_vals = np.linspace(-10, 10, 100)
    theta1_vals = np.linspace(-1, 4, 100)
    J_vals = np.zeros((len(theta0_vals), len(theta1_vals)))
    for i, v0 in enumerate(theta0_vals):
        for j, v1 in enumerate(theta1_vals):
            t = np.array((v0, v1))
            J_vals[i, j] = compute_cost(X, y, t)[0]

    fig = plt.figure()
    ax = fig.gca(projection="3d")
    R, P = np.meshgrid(theta0_vals, theta1_vals)
    ax.plot_surface(R, P, J_vals)
    plt.savefig("2-4_surface.png")

    fig = plt.figure()
    plt.contour(R, P, J_vals.T, np.logspace(-2, 3, 20))
    plt.xlabel(r"${\Theta}_0$")
    plt.ylabel(r"${\Theta}_1$")
    plt.savefig("2-4_contour.png")
Пример #9
1
 def plotOutputs(self, _h5data):
     count = 0
     indexMapping = {}
     for i, meas in enumerate(self.outputs.get_varNames()):
         print "[%d] %s" % (i, meas)
         indexMapping[count] = i
         count += 1
     try:
         value = raw_input("Select which variable do you want to plot: ")
         lindex = value.split()
     except ValueError:
         print "Mal! Mal! Mal! Verdadera mal! Por no decir borchenoso!"
     values = []
     for idx in lindex:
         idx = int(idx)
         values.append(self.outputs.get_varNames()[indexMapping[idx]])
     plt.figure(1)
     for meas in values:
         lasenyal = _h5data.get_senyal(meas)
         plt.plot(lasenyal.get_sampleTime(), lasenyal.get_signalReal())
     plt.legend(values)
     plt.ylabel(lasenyal.component)
     plt.xlabel("Time (s)")
     plt.grid(b=True, which="both")
     plt.show()
Пример #10
1
def make_fish(zoom=False):
    plt.close(1)
    plt.figure(1, figsize=(6, 4))
    plt.plot(plot_limits["pitch"], plot_limits["rolldev"], "-g", lw=3)
    plt.plot(plot_limits["pitch"], -plot_limits["rolldev"], "-g", lw=3)
    plt.plot(pitch.midvals, roll.midvals, ".b", ms=1, alpha=0.7)

    p, r = make_ellipse()  # pitch, off nominal roll
    plt.plot(p, r, "-c", lw=2)

    gf = -0.08  # Fudge on pitch value for illustrative purposes
    plt.plot(greta["pitch"] + gf, -greta["roll"], ".r", ms=1, alpha=0.7)
    plt.plot(greta["pitch"][-1] + gf, -greta["roll"][-1], "xr", ms=10, mew=2)

    if zoom:
        plt.xlim(46.3, 56.1)
        plt.ylim(4.1, 7.3)
    else:
        plt.ylim(-22, 22)
        plt.xlim(40, 180)
    plt.xlabel("Sun pitch angle (deg)")
    plt.ylabel("Sun off-nominal roll angle (deg)")
    plt.title("Mission off-nominal roll vs. pitch (5 minute samples)")
    plt.grid()
    plt.tight_layout()
    plt.savefig("fish{}.png".format("_zoom" if zoom else ""))
Пример #11
1
def plot_graph(G, a, b, node_lable="False", edge_lable="False"):
    """()->None
    dsc: plots figure from given networkx graph object and saves it
    """
    colors = []
    for v in G:
        if v in a and v in b:
            colors.append("b")
        elif v in a:
            colors.append("r")
        elif v in b:
            colors.append("g")
        else:
            colors.append("y")
    time_stamp = str(datetime.now())
    plt.figure(figsize=(120, 120))
    # pos = nx.graphviz_layout(G, prog="neato")
    # pos = graphviz_layout(G, prog="twopi", root='AsYouKnow_Bob')
    if not node_lable and not edge_lable:
        draw(G, pos, node_size=100, font_size=4, edge_color="k", alpha=0.8, node_color=colors, linewidths=0, width=0.2)
    elif node_lable:
        sizes = [v for k, v in get_node_attributes(C, "read").items()]
        sizes = [((i / float(max(sizes))) * 200) for i in sizes]  # max size is 200
        draw(
            G, pos, node_size=sizes, font_size=4, edge_color="k", alpha=0.8, node_color=colors, linewidths=0, width=0.2
        )
    plt.axis("off")
    # plt.savefig("./figures/friends_graph_%s.svg" % time_stamp, format='SVG')
    plt.savefig("./figures/friends_graph_%s.png" % time_stamp, format="PNG")
Пример #12
0
    def plot_benchmark(benchmark, step_no, column, label):
        fig_filename = "%s-step%d-%s.png" % (benchmark.name, step_no, column)

        # create paths
        fig_full_path = os.path.join(fig_base_path, fig_filename)
        fig_rel_path = "vbench/figures/%s" % fig_filename

        # plot the figure
        plt.figure(figsize=(10, 6))
        ax = plt.gca()
        try:
            benchmark.plot(DB_PATH, ax=ax, y=column, ylabel=label, step_no=step_no)
        except TypeError:
            pass
        ylo, yhi = ax.get_ylim()
        plt.ylim([0.0, 1.1 * yhi])
        start, end = ax.get_xlim()
        plt.xlim([start - 30, end + 30])
        for label in ax.xaxis.get_ticklabels():
            label.set_rotation(66)

        plt.savefig(fig_full_path, bbox_inches="tight")

        plt.close("all")
        return fig_rel_path
    def __init__(self, *args, **kwargs):
        super(NuPICPlotOutput, self).__init__(*args, **kwargs)
        # turn matplotlib interactive mode on (ion)
        plt.ion()
        plt.figure(figsize=(14, 10))
        gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
        # plot title, legend, etc
        plt.title("tan prediction example")
        plt.ylabel("tan (rad)")
        # The shifter will align prediction and actual values.
        self.shifter = InferenceShifter()
        # Keep the last WINDOW predicted and actual values for plotting.
        self.actual_history = deque([0.0] * WINDOW, maxlen=360)
        self.predicted_history = deque([0.0] * WINDOW, maxlen=360)
        if self.show_anomaly_score:
            self.anomaly_score = deque([0.0] * WINDOW, maxlen=360)
        # Initialize the plot lines that we will update with each new record.
        if self.show_anomaly_score:
            plt.subplot(gs[0])
        self.actual_line, = plt.plot(range(WINDOW), self.actual_history)
        self.predicted_line, = plt.plot(range(WINDOW), self.predicted_history)
        plt.legend(tuple(["actual", "predicted"]), loc=3)
        if self.show_anomaly_score:
            plt.subplot(gs[1])
            self.anomaly_score_line, = plt.plot(range(WINDOW), self.anomaly_score, "r-")
            plt.legend(tuple(["anomaly score"]), loc=3)

        # Set the y-axis range.
        self.actual_line.axes.set_ylim(-30, 30)
        self.predicted_line.axes.set_ylim(-30, 30)
        if self.show_anomaly_score:
            self.anomaly_score_line.axes.set_ylim(-1, 1)
Пример #14
0
def train_test_plot(data, plot=False):
    trainX, trainY, testX, testY = splitData(data)
    clf = ensemble.GradientBoostingRegressor(**params)
    clf.fit(trainX, trainY)
    mse = mean_squared_error(testY, clf.predict(testX))
    print ("MSE: %.4f" % mse)

    if plot:
        ###############################################################################
        # Plot training deviance

        # compute test set deviance
        test_score = np.zeros((params["n_estimators"],), dtype=np.float64)

        for i, y_pred in enumerate(clf.staged_predict(testX)):
            test_score[i] = clf.loss_(testY, y_pred)

        plt.figure(figsize=(12, 6))
        plt.subplot(1, 2, 1)
        plt.title("Deviance")
        plt.plot(np.arange(params["n_estimators"]) + 1, clf.train_score_, "b-", label="Training Set Deviance")
        plt.plot(np.arange(params["n_estimators"]) + 1, test_score, "r-", label="Test Set Deviance")
        plt.legend(loc="upper right")
        plt.xlabel("Boosting Iterations")
        plt.ylabel("Deviance")

    return clf
Пример #15
0
def main():
    usage = "usage: %prog [options] <peaks1_bed> <peaks2_bed> <out_pdf>"
    parser = OptionParser(usage)
    parser.add_option("--l1", dest="label1", default="peaks1", help="Label for peak set 1")
    parser.add_option("--l2", dest="label2", default="peaks2", help="Label for peak set 2")
    (options, args) = parser.parse_args()

    if len(args) != 3:
        parser.error("Must provide two peaks BED files and output PDF")
    else:
        peaks1_bed = args[0]
        peaks2_bed = args[1]
        out_pdf = args[2]

    # count individual
    peaks1_count = count_peaks(peaks1_bed)
    peaks2_count = count_peaks(peaks2_bed)

    # count overlap
    copeaks_count = 0
    p = subprocess.Popen("intersectBed -u -a %s -b %s" % (peaks1_bed, peaks2_bed), stdout=subprocess.PIPE, shell=True)
    for line in p.stdout:
        copeaks_count += 1
    p.communicate()

    plt.figure()
    venn_diag = venn2(
        subsets=(peaks1_count - copeaks_count, peaks2_count - copeaks_count, copeaks_count),
        set_labels=[options.label1, options.label2],
        set_colors=["#e41a1c", "#A1A838"],
    )
    plt.savefig(out_pdf)
    plt.close()
Пример #16
0
    def display_curve(self, figure=True):
        """
        Display the exponential transformation of the free response reciever operating characteristic curve.

        This is the curve that this class is generating information about

        :param figure: if the graph should be displayed in a new figure.

        :return: None
        """
        if figure:
            plt.figure()
        # thresh = np.linspace(-.1, end*1.1, 50000)
        thresh = np.sort(np.array(self.false))
        true_pos = np.zeros_like(thresh)
        false_neg = np.zeros_like(thresh)
        true_neg = np.zeros_like(thresh)
        false_pos = np.zeros_like(thresh)
        for true in self.true:
            true_pos[thresh < true] += 1
            false_neg[thresh >= true] += 1
        for false in self.false:
            false_pos[thresh < false] += 1
            true_neg[thresh >= false] += 1
        sensitivity = true_pos / (true_pos + false_neg)
        plt.plot(
            1 - np.exp(-false_pos / self.n), sensitivity, "-", label=self.name + "\nAUC: {0}".format(self.estimation)
        )
        plt.legend(loc="lower right")
        plt.title("Exponential Transformation of FROC Curve")
        plt.xlabel("Projected fraction of false positive images")
        plt.ylabel("True Positive Rate (Sensitivity)")
Пример #17
0
    def _spikes_diagnosis(self, signal_mask=None, navigation_mask=None):
        """Plots a histogram to help in choosing the threshold for
        spikes removal.

        Parameters
        ----------
        signal_mask: boolean array
            Restricts the operation to the signal locations not marked
            as True (masked)
        navigation_mask: boolean array
            Restricts the operation to the navigation locations not
            marked as True (masked).

        See also
        --------
        spikes_removal_tool

        """
        self._check_signal_dimension_equals_one()
        dc = self.data
        if signal_mask is not None:
            dc = dc[..., ~signal_mask]
        if navigation_mask is not None:
            dc = dc[~navigation_mask, :]
        der = np.abs(np.diff(dc, 1, -1))
        plt.figure()
        plt.hist(np.ravel(der.max(-1)), 100)
        plt.xlabel("Threshold")
        plt.ylabel("Counts")
        plt.draw()
Пример #18
0
def plot_images(data_list, data_shape="auto", fig_shape="auto"):
    """
    plotting data on current plt object.
    In default,data_shape and fig_shape are auto.
    It means considered the data as a sqare structure.
    """
    n_data = len(data_list)
    if data_shape == "auto":
        sqr = int(n_data ** 0.5)
        if sqr * sqr != n_data:
            data_shape = (sqr + 1, sqr + 1)
        else:
            data_shape = (sqr, sqr)
    plt.figure(figsize=data_shape)

    for i, data in enumerate(data_list):
        plt.subplot(data_shape[0], data_shape[1], i + 1)
        plt.gray()
        if fig_shape == "auto":
            fig_size = int(len(data) ** 0.5)
            if fig_size ** 2 != len(data):
                fig_shape = (fig_size + 1, fig_size + 1)
            else:
                fig_shape = (fig_size, fig_size)
        Z = data.reshape(fig_shape[0], fig_shape[1])
        plt.imshow(Z, interpolation="nearest")
        plt.tick_params(labelleft="off", labelbottom="off")
        plt.tick_params(axis="both", which="both", left="off", bottom="off", right="off", top="off")
        plt.subplots_adjust(hspace=0.05)
        plt.subplots_adjust(wspace=0.05)
Пример #19
0
def test_devectorize_axes():
    np.random.seed(0)

    x, y = np.random.random((2, 1000))

    # save vectorized version
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(x, y)
    output = BytesIO()
    fig.savefig(output)
    output.seek(0)
    im1 = image.imread(output)
    plt.close()

    # save devectorized version
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(x, y)
    devectorize_axes(ax, dpi=200)
    output = BytesIO()
    fig.savefig(output)
    output.seek(0)
    im2 = image.imread(output)
    plt.close()

    assert_(im1.shape == im2.shape)
    assert_((im1 != im2).sum() < 0.1 * im1.size)
Пример #20
0
def CoAddFinal(frames, mode="mean", display=True):
    # co-add FINSIHED, reduced spectra
    # only trick: resample on to wavelength grid of 1st frame
    files = np.loadtxt(frames, dtype="string", unpack=True)

    # read in first file
    wave_0, flux_0 = np.loadtxt(files[0], dtype="float", skiprows=1, unpack=True, delimiter=",")

    for i in range(1, len(files)):
        wave_i, flux_i = np.loadtxt(files[i], dtype="float", skiprows=1, unpack=True, delimiter=",")

        # linear interp on to wavelength grid of 1st frame
        flux_i0 = np.interp(wave_0, wave_i, flux_i)

        flux_0 = np.dstack((flux_0, flux_i0))

    if mode == "mean":
        flux_out = np.squeeze(flux_0.sum(axis=2) / len(files))
    if mode == "median":
        flux_out = np.squeeze(np.median(flux_0, axis=2))

    if display is True:
        plt.figure()
        plt.plot(wave_0, flux_out)
        plt.xlabel("Wavelength")
        plt.ylabel("Co-Added Flux")
        plt.show()

    return wave_0, flux_out
Пример #21
0
 def png(self, start_timestamp, end_timestamp):
     self.load(start_timestamp, end_timestamp)
     plt.figure(figsize=(10, 7.52))
     plt.rc("axes", labelsize=12, titlesize=14)
     plt.rc("font", size=10)
     plt.rc("legend", fontsize=7)
     plt.rc("xtick", labelsize=8)
     plt.rc("ytick", labelsize=8)
     plt.axes([0.08, 0.08, 1 - 0.27, 1 - 0.15])
     for plot in self.plots:
         plt.plot(self.timestamps, self.plots[plot], self.series_fmt(plot), label=self.series_label(plot))
     plt.axis("tight")
     plt.gca().xaxis.set_major_formatter(
         matplotlib.ticker.FuncFormatter(lambda x, pos=None: time.strftime("%H:%M\n%b %d", time.localtime(x)))
     )
     plt.gca().yaxis.set_major_formatter(
         matplotlib.ticker.FuncFormatter(lambda x, pos=None: locale.format("%.*f", (0, x), True))
     )
     plt.grid(True)
     plt.legend(loc=(1.003, 0))
     plt.xlabel("Time/Date")
     plt.title(
         self.description()
         + "\n%s to %s"
         % (
             time.strftime("%H:%M %d-%b-%Y", time.localtime(start_timestamp)),
             time.strftime("%H:%M %d-%b-%Y", time.localtime(end_timestamp)),
         )
     )
     output_buffer = StringIO.StringIO()
     plt.savefig(output_buffer, format="png")
     return output_buffer.getvalue()
Пример #22
0
    def bootstrap(self, bootstrap_sample_size=1, seed=None):
        """
        Use bootstrapping to calculate the variance of the difference of two EFROC studies.

        :param bootstrap_sample_size: Number of times to resample. Defaults to 1.
        :param seed: Seed to initially pass to the random number generator. Defaults to None.

        :return: an ND Array of the bootstrapped differences.
        """
        difference_list = []
        gen = random.Random()
        gen.seed(seed)
        for count in xrange(bootstrap_sample_size):
            difference_list.append(self._resample_and_compare(gen))
            if seed is not None:
                random.jumpahead(seed)
        difference_array = np.array(difference_list)
        self.variance = np.var(difference_array)

        plt.figure()
        plt.hist(difference_array, np.ceil(np.sqrt(bootstrap_sample_size)), histtype="stepfilled")
        plt.title("Bootstrapped Estimation of $\delta A_{FE}$")
        plt.xlabel("$\delta A_{FE}$")
        plt.ylabel("Count")
        return difference_array
Пример #23
0
def my_box_plot(self):
    plt.figure()
    plt.plot(self.data[["Income"]])
    plt.title("Plot of Per Capita GDP in " + str(year))
    plt.xlabel("Country Index")
    plt.ylabel("Per Capita GDP")
    plt.savefig("plot_{}.png".format(self.year))
Пример #24
0
    def __init__(self, image):
        self.config = QSettings("GuLinux", "PySpectra")
        self.__init_rotate_dialog__()
        self.original = image.astype(float)
        self.rotated = self.original
        self.background = np.zeros((1, 1), float)
        self.image_view = plt.imshow(self.original, cmap="gray")
        self.brotate = Button(self.image_view.figure.add_axes([0, 0.95, 0.1, 0.05]), "Rotate")
        self.bselect_background = Button(self.image_view.figure.add_axes([0.1, 0.95, 0.25, 0.05]), "Select Background")
        self.bsave = Button(self.image_view.figure.add_axes([0.1 + 0.25, 0.95, 0.1, 0.05]), "Save")
        self.brotate.on_clicked(lambda ev: self.rotate_dialog.show())
        self.bsave.on_clicked(self.save)
        self.bselect_background.on_clicked(self.select_bg)
        self.RS = RectangleSelector(
            self.image_view.axes,
            self.bg_selected,
            drawtype="box",
            useblit=True,
            button=[1, 3],  # don't use middle button
            minspanx=5,
            minspany=5,
            spancoords="pixels",
            interactive=True,
        )

        plt.figure()
        self.image_plot = plt.axes()
        self.degrees = 0
        self.draw_plot()
        plt.show()
Пример #25
0
def plotwaves():
    global snd, s1, s2, sampleFreq, radios, freqArray, p

    timeArray = numpy.arange(0, float(snd.shape[0]), 1)  # time base
    timeArray = timeArray / sampleFreq
    timeArray = timeArray * 1000  # scale to milliseconds
    pyplot.figure(1)

    pyplot.subplot(211)
    pyplot.plot(timeArray, s1, color="K")
    pyplot.ylabel("Amplitude")
    pyplot.xlabel("Time (ms)")

    timeArray2 = numpy.arange(0, len(radios), 1)  # time base
    pyplot.subplot(212)
    pyplot.plot(timeArray2, radios, color="C")
    pyplot.ylabel("Amplitude")
    pyplot.xlabel("Time (ms)")

    pyplot.figure(2)
    pyplot.subplot(111)
    pyplot.plot(freqArray / 1000, 10 * numpy.log10(p), color="C")

    pyplot.draw()
    pyplot.show()
    return
Пример #26
0
 def generate_line_chart(self, data, node_type, field, append_table=True):
     output = []
     common.bash("mkdir -p ../visualizer/include/pic")
     common.bash("mkdir -p ../visualizer/include/csv")
     common.printout("LOG", "generate %s line chart" % node_type)
     for field_column, field_data in data.items():
         pyplot.figure(figsize=(9, 4))
         for node, node_data in field_data.items():
             pyplot.plot(node_data, label=node)
         pyplot.xlabel("time(sec)")
         pyplot.ylabel("%s" % field_column)
         # Shrink current axis's height by 10% on the bottom
         pyplot.legend(loc="center left", bbox_to_anchor=(1, 0.5), prop={"size": 6})
         pyplot.grid(True)
         pyplot.suptitle("%s" % field_column)
         pic_name = "%s_%s_%s.png" % (node_type, field, re.sub("[/%]", "", field_column))
         pyplot.savefig("../visualizer/include/pic/%s" % pic_name)
         pyplot.close()
         line_table = []
         csv = self.generate_csv_from_json(field_data, "line_table", field_column)
         csv_name = "%s_%s_%s.csv" % (node_type, field, re.sub("[/%]", "", field_column))
         with open("../visualizer/include/csv/%s" % csv_name, "w") as f:
             f.write(csv)
         # output.append("<div class='cetune_pic' id='%s_%s_pic'><button><a href='./include/csv/%s'>Download detail csv table</a></button><img src='./include/pic/%s' alt='%s' style='height:400px; width:1000px'></div>" % (field, re.sub('[/%]','',field_column), csv_name, pic_name, field_column))
         output.append(
             "<div class='cetune_pic' id='%s_%s_pic'><img src='./include/pic/%s' alt='%s' style='height:400px; width:1000px'><button><a href='./include/csv/%s'>Download detail csv table</a></button></div>"
             % (field, re.sub("[/%]", "", field_column), pic_name, field_column, csv_name)
         )
     return output
Пример #27
0
def heatmap(vals, size=6, aspect=1):
    """
    Plot a heatmap from matrix data
    """
    plt.figure(figsize=(size, size))
    plt.imshow(vals, cmap="gray", aspect=aspect, interpolation="none", vmin=0, vmax=1)
    plt.axis("off")
Пример #28
0
def comp_roc(res_fn, label_fn):
    res_scores = []
    with open(res_fn, "r") as res:
        num = int(res.readline())
        for i in range(num):
            res_scores.append(float(res.readline()))

    labels = []
    with open(label_fn, "r") as f:
        num = int(f.readline())
        for i in range(num):
            labels.append(float(f.readline()))

    # make sure same dimension
    valid_num = min(len(res_scores), len(labels))
    res_scores = res_scores[:valid_num]
    labels = labels[:valid_num]
    # compute roc
    fpr, tpr, thresholds = sklearn.metrics.roc_curve(labels, res_scores, 1)
    roc_auc = sklearn.metrics.auc(fpr, tpr)
    # plot
    plt.figure()
    plt.title("ROC curve (area = {0:0.2f})".format(roc_auc))
    plt.plot(fpr, tpr)
    plt.show()
Пример #29
0
def plot_2D_projections(title, output_file, cluster_assignments, projections):
    """
  Visualize SDR cluster projections
  """

    color_list = colors.cnames.keys()
    plt.figure()
    color_list = color_list
    color_names = []
    for i in range(len(cluster_assignments)):
        cluster_id = int(cluster_assignments[i])
        if cluster_id not in color_names:
            color_names.append(cluster_id)
        projection = projections[i]
        label = "Category %s" % cluster_id
        if len(color_list) > cluster_id:
            color = color_list[cluster_id]
        else:
            color = "black"
        plt.scatter(projection[0], projection[1], label=label, alpha=0.5, color=color, marker="o", edgecolor="black")

    # Add nicely formatted legend
    handles, labels = plt.gca().get_legend_handles_labels()
    by_label = OrderedDict(zip(labels, handles))
    plt.legend(by_label.values(), by_label.keys(), scatterpoints=1, loc=2)

    plt.title(title)
    plt.draw()
    plt.savefig(output_file)
    print("==> saved: %s" % output_file)
    return plt
Пример #30
0
def plot_depth_histogram(
    catalogue, bin_width, normalisation=False, bootstrap=None, filename=None, filetype="png", dpi=300
):
    """
    Creates a histogram of the depths in the catalogue
    :param catalogue:
        Earthquake catalogue as instance of :class:
        hmtk.seismicity.catalogue.Catalogue
    :param float bin_width:
        Width of the histogram for the depth bins
    :param bool normalisation:
        Normalise the histogram to give output as PMF (True) or count (False)
    :param int bootstrap:
        To sample depth uncertainty choose number of samples
    """
    plt.figure(figsize=DEFAULT_SIZE)
    # Create depth range
    if len(catalogue.data["depth"]) == 0:
        raise ValueError("No depths reported in catalogue!")
    depth_bins = np.arange(0.0, np.max(catalogue.data["depth"]) + bin_width, bin_width)
    depth_hist = catalogue.get_depth_distribution(depth_bins, normalisation, bootstrap)
    plt.bar(depth_bins[:-1], depth_hist, width=0.95 * bin_width, edgecolor="k")
    plt.xlabel("Depth (km)", fontsize="large")
    if normalisation:
        plt.ylabel("Probability Mass Function", fontsize="large")
    else:
        plt.ylabel("Count")
    plt.title("Depth Histogram", fontsize="large")

    _save_image(filename, filetype, dpi)
    plt.show()
    return