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()
    def solve(self, a=0, b=1, c=0, d=1, n=41, m=41, delta=10 ** -8, h=10 ** -10):
        self.n = n
        self.m = m
        self.hS = (b - a) / (n - 1)
        self.hX = (d - c) / (m - 1)
        self.h = h
        s = linspace(a, b, n)
        x = linspace(c, d, m)

        K = array(self.K(x, s))
        u = dot(K, self.z(s)) * self.hS

        # Начальное приближение
        z = random.random_sample((n,)) * -10
        alpha = 0.01

        z_min, alpha = self.chords_method(K, z, u, alpha, delta, h)
        print("z_min=", z_min, "alpha=", alpha)

        # Рисуем график
        plt.plot(s, self.z(s), s, z_min, "ro")
        plt.title(u"Минимизация функционала Тихонова", family="verdana")
        plt.xlabel("s")
        plt.ylabel("z(s)")
        plt.legend((r"$z_0$", r"$z_\eta^\alpha$"), loc=(0.85, 0.85))
        plt.grid()
        plt.text(-0.1, -0.1, u"Время выполнения: %.3f секунд" % (time.time() - time_l), family="verdana", size=8)
        plt.show()
Example #3
1
def singleBasis6():
    f = plt.figure()
    sb = f.add_subplot(111)
    sb.set_xticklabels([i for i in range(1, len(gridpoints) + 1)])
    # sb.set_yticklabels([])
    plt.axis([start, end, -1, 1])
    plt.xticks([(1 / 8.0) * g for g in gridpoints])

    # function
    # plt.plot(xval, yval, color="red")

    # basis fun
    ys_a = []
    for g in gridpoints:
        point = (1 / 8.0) * g
        alpha = fun(point)
        ys_a.append([alpha * hatfun(x, 3, g) for x in xval])

    # sum
    ys_sum = [0 for i in ys_a[0]]
    for ys_i in ys_a:
        for i in range(len(ys_i)):
            ys_sum[i] += ys_i[i]
    plt.plot(xval, ys_sum, color="blue", linewidth=2)

    plt.savefig(savedir + "singlebasis_6.png", bbox_inches="tight")
    plt.show()
Example #4
1
def show_step(marcher, number, steps, **kw):
    """Demonstrate simulation with graphical output"""
    # Set up harmonic driver.
    hm = HarmonicMotion(number)
    hm.marcher = marcher

    # Set up plotter.
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel("Location ($\\pi$)")
    ax.set_ylabel("Amplitude")
    # Title.
    titlefmt = "Step #%d/%d"
    text = ax.text(0.5, 1.05, "", transform=ax.transAxes, va="center", ha="center")
    # Content line.
    line, = ax.plot(hm.xgrid / np.pi, hm.soln)

    # Loop to the end and draw.
    it = 0
    while it < steps:
        hm.march()
        it += 1
    text.set_text(titlefmt % (it, steps))
    line.set_ydata(hm.soln)

    # Show it.
    plt.show()
Example #5
1
def test_ars_gaussian():
    """
    Test ARS on a Gaussian distribution
    """
    from scipy.stats import norm

    mu = 0
    sig = 1
    p = norm(mu, sig).pdf

    f = lambda x: -0.5 * x ** 2
    x_init = np.array([-2, -0.995, 0, 0.995, 2.0])
    v_init = f(x_init)

    N_samples = 10000
    smpls = np.zeros(N_samples)
    for s in np.arange(N_samples):
        ars = AdaptiveRejectionSampler(f, -np.inf, np.inf, x_init, v_init)
        smpls[s] = ars.sample()

    import matplotlib.pyplot as plt

    f = plt.figure()
    _, bins, _ = plt.hist(smpls, 20, normed=True, alpha=0.2)
    bincenters = 0.5 * (bins[1:] + bins[:-1])
    plt.plot(bincenters, p(bincenters), "r--", linewidth=1)
    plt.show()
Example #6
1
def main(inputfile, format):
    """
	Kicks off the main method.

	Parameters
	----------
	inputfile : string
		System path to the file containing the data.
	format : string
		[raw | affinity | mahout] Designates the input format.

	Returns
	-------
	None
	"""
    data = np.loadtxt(inputfile, delimiter=",")
    if format == "raw":
        plot.plot(data[:, 0], data[:, 1], ".")
    elif format == "affinity":
        plot.imshow(data)
    else:
        # A little more involved.
        N = np.size(data, axis=0)
        dims = data[N - 1, 0]
        toplot = np.zeros((dims + 1, dims + 1))
        for t in range(0, N):
            i = data[t, 0]
            j = data[t, 1]
            val = data[t, 2]
            toplot[i, j] = val
        plot.imshow(toplot)
    plot.show()
def plot_fg(fg, data1, data2, bound):
    # obtain estimates
    e_mu1 = fg["mu1"].moments(0)
    e_mu2 = fg["mu2"].moments(0)
    e_d1 = normal_distribution_t(e_mu1, 100)
    e_d2 = normal_distribution_t(e_mu2, 100)
    if e_mu1 < e_mu2:
        d1 = fg["mu1"]
        d2 = fg["mu2"]
    else:
        d1 = fg["mu2"]
        d2 = fg["mu1"]
    # plot result
    plt.clf()
    ax1 = plt.subplot2grid((3, 2), (0, 0), colspan=2)
    ax2 = plt.subplot2grid((3, 2), (1, 0))
    ax3 = plt.subplot2grid((3, 2), (1, 1))
    ax4 = plt.subplot2grid((3, 2), (2, 0), colspan=2)
    plot_density(ax1, e_d1, [-0.5, 0.5], xlab="x", ylab="density")
    plot_density(ax1, e_d2, [-0.5, 0.5], xlab="x", ylab="density")
    plot_density(ax2, d1, [-0.2, 0.0], xlab=r"$\mu_1$", ylab="density")
    plot_density(ax3, d2, [0.0, 0.2], xlab=r"$\mu_2$", ylab="density")
    ax1.hist(data1, 50, normed=1)
    ax1.hist(data2, 50, normed=1)
    ax4.plot(bound)
    ax4.set_xlabel("iteration")
    ax4.set_ylabel("bound")
    plt.tight_layout()
    # plt.savefig("factor-graph-test-5.png")
    plt.show()
Example #8
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()
def main():
    plt.figure(1)
    plt.xlabel("circle(Time)")
    plt.ylabel("raw fluorescence")
    filename = sys.argv[1]
    filename2 = sys.argv[2]
    data = readfile(filename)
    parameters = readfile(filename2)
    row, col = data.shape
    # print max(data[row-4])
    newbigger = []
    for rownum in xrange(row):
        newbigger.append(data[rownum][col - 1])
    midnum = caculatemidnum(newbigger)
    data = data / midnum
    if row > 0:
        os.system("clear")
    for rownum in xrange(row):
        args = data[rownum]
        plt.figure(1)
        for i in xrange(col):
            plt.plot(i + 1, args[i], marker=".")
    x = np.linspace(0, 90, 100)
    for rownum in xrange(row):
        xopt4 = parameters[rownum]
        y = (
            xopt4[0]
            + xopt4[1] * x
            + xopt4[2] / ((1 + np.exp(-xopt4[3] * (x - xopt4[4]))) * (1 + np.exp(-xopt4[5] * (x - xopt4[6]))))
        )
        plt.figure(1)
        plt.plot(x, y)

    plt.show()
Example #10
0
def main():
    args = parse_arguments()
    dr = Drawing()
    multiplex = str(args.network) + "_multiplex"  # giving name to multiplex table
    nodelist = str(args.network) + "_node_list"  # giving name to node list table
    layerlist = str(args.network) + "_layer_list"  # giving name to layer list table
    # list of all layers
    list_of_layers = dr.list_of_layer(layerlist)
    # list of all nodes
    list_of_nodes = dr.list_of_node(nodelist)
    # graph object
    G = dr.G
    # same layer list is for the edges where each node is in the same layer
    same_layer = dr.same_layer
    # different layer list is for the edges where each node is in different layer
    different_layer = dr.different_layer
    # place the nodes
    dr.placing_nodes(list_of_nodes, list_of_layers, G)
    # place the edges
    dr.placing_edges(multiplex, G, same_layer, different_layer)

    pos = nx.get_node_attributes(G, "pos")

    # draw nodes
    nx.draw_networkx_nodes(G, pos, node_size=1000 / (len(list_of_nodes) * len(list_of_layers)), node_color="k")

    # draw the edges in the same layer
    nx.draw_networkx_edges(G, pos, edgelist=same_layer, width=0.5, edge_color="c")

    # draw the edges in different layers
    nx.draw_networkx_edges(G, pos, edgelist=different_layer, width=0.5, alpha=0.5, edge_color="0.20", style="dashed")

    plt.axis("off")
    plt.show()
Example #11
0
def main():
    np.random.seed(1)
    xtrain, ytrain, w_true = make_data_linreg_1d()
    model = LinregModel(w_true)
    plot_data_and_pred(xtrain, ytrain, model)
    plot_error_surface(xtrain, ytrain, model)
    plt.show()
    def test_EM1DFDfwd_VMD_ComplexCond(self):

        if self.prob.ispaired:
            self.prob.unpair()
        if self.survey.ispaired:
            self.survey.unpair()

        self.prob = EM1D.EM1D(self.mesh1D, mapping=self.modelComplex, **self.options)
        self.prob.chi = np.zeros(self.survey.nlay)
        self.prob.pair(self.survey)

        self.prob.CondType = "Complex"
        self.prob.survey.srcType = "VMD"
        self.prob.survey.offset = 10.0
        self.prob.survey.SetOffset()
        sig_half = 0.01
        m_1D = np.log(np.ones(self.prob.survey.nlay) * sig_half)
        Hz = self.prob.fields(m_1D)
        sigCole = EM1DAnal.ColeCole(self.survey.frequency, sig_half, self.eta, self.tau, self.c)
        Hzanal = EM1DAnal.Hzanal(sigCole, self.prob.survey.frequency, self.prob.survey.offset, "secondary")

        if self.showIt == True:

            plt.loglog(self.prob.survey.frequency, abs(Hz.real), "b")
            plt.loglog(self.prob.survey.frequency, abs(Hzanal.real), "b*")
            plt.loglog(self.prob.survey.frequency, abs(Hz.imag), "r")
            plt.loglog(self.prob.survey.frequency, abs(Hzanal.imag), "r*")
            plt.show()

        err = np.linalg.norm(Hz - Hzanal) / np.linalg.norm(Hzanal)
        self.assertTrue(err < 1e-5)
        print "EM1DFD-VMD for complex conductivity works"
Example #13
0
def plot_fft():
    xmin, xmax = -1.0, 1.0
    mesh, h = np.linspace(xmin, xmax, 500, retstep=True)
    sinf = Function1D.from_func(np.sin, mesh)
    cosf = Function1D.from_func(np.cos, mesh)
    eix = cosf + 1j * sinf

    fig = plt.figure()
    ax = fig.add_subplot(111)

    gauss = lambda x: np.exp(-x ** 2)
    func = Function1D.from_func(gauss, mesh)

    poly = lambda x: x + x ** 2 + 3
    func = Function1D.from_func(poly, mesh)

    # (0.1 + func).plot_ax(ax, name="func")
    func.plot_ax(ax, label="func")
    fft_func = func.fft()
    fft_func.plot_ax(ax, label="FFT(func)")
    same_func = fft_func.ifft(x0=xmin)
    print(same_func.h / func.h)
    same_func.plot_ax(ax, label="IFFT(FFT(func))")

    # sinf.fft().plot()
    # fft_eix = eix.fft()
    # fft_eix.plot()
    plt.legend()
    plt.show()
Example #14
0
def plot3d():
    """
    .. versionadded:: 1.1.0
    This demo depends on new features added to contourf3d.
    """
    from mpl_toolkits.mplot3d import axes3d
    import matplotlib.pyplot as plt
    from matplotlib import cm

    fig = plt.figure()
    ax = fig.gca(projection="3d")
    X, Y, Z = axes3d.get_test_data(0.05)
    ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
    cset = ax.contourf(X, Y, Z, zdir="z", offset=-100, cmap=cm.coolwarm)
    cset = ax.contourf(X, Y, Z, zdir="x", offset=-40, cmap=cm.coolwarm)
    cset = ax.contourf(X, Y, Z, zdir="y", offset=40, cmap=cm.coolwarm)

    ax.set_xlabel("X")
    # ax.set_xlim(-40, 40)
    ax.set_ylabel("Y")
    # ax.set_ylim(-40, 40)
    ax.set_zlabel("Z")
    # ax.set_zlim(-100, 100)

    plt.show()
def plotROC(predStrengths, classLabels):
    import matplotlib.pyplot as plt

    cur = (1.0, 1.0)  # cursor
    ySum = 0.0  # variable to calculate AUC
    numPosClas = sum(array(classLabels) == 1.0)
    yStep = 1 / float(numPosClas)
    xStep = 1 / float(len(classLabels) - numPosClas)
    sortedIndicies = predStrengths.argsort()  # get sorted index, it's reverse
    fig = plt.figure()
    fig.clf()
    ax = plt.subplot(111)
    # loop through all the values, drawing a line segment at each point
    for index in sortedIndicies.tolist()[0]:
        if classLabels[index] == 1.0:
            delX = 0
            delY = yStep
        else:
            delX = xStep
            delY = 0
            ySum += cur[1]
        # draw line from cur to (cur[0]-delX,cur[1]-delY)
        ax.plot([cur[0], cur[0] - delX], [cur[1], cur[1] - delY], c="b")
        cur = (cur[0] - delX, cur[1] - delY)
    ax.plot([0, 1], [0, 1], "b--")
    plt.xlabel("False positive rate")
    plt.ylabel("True positive rate")
    plt.title("ROC curve for AdaBoost horse colic detection system")
    ax.axis([0, 1, 0, 1])
    plt.show()
    print "the Area Under the Curve is: ", ySum * xStep
Example #16
0
def LouvainModularity(G, colours, node_size=80):

    graphs = list(nx.connected_component_subgraphs(G))
    graphs.sort(key=lambda x: len(x.nodes()), reverse=True)
    G = graphs[0]

    # first compute the best partition
    partition = community.best_partition(G)

    # drawing
    size = float(len(set(partition.values())))
    pos = nx.spring_layout(G)
    count = 0.0
    nx.draw_networkx_edges(G, pos, edge_color="#aaaaaa", alpha=0.8)
    sub_graphs_louvain = []

    k = 0
    for com in set(partition.values()):
        count = count + 1.0
        list_nodes = [nodes for nodes in partition.keys() if partition[nodes] == com]

        nx.draw_networkx_nodes(G, pos, list_nodes, linewidths=0, node_size=node_size, node_color=colours[k])
        # place partition in subgraphs
        sub_graphs_louvain.append(G.subgraph(list_nodes))
        k += 1
        if k >= len(colours):
            k = 0

    plt.axis("off")
    plt.savefig("grap_communties_louvain.png")
    plt.show()

    print "modularity: %s" % computeModularity(G, sub_graphs_louvain)
    print "%s communities" % len(sub_graphs_louvain)
    return sub_graphs_louvain
Example #17
0
File: test1.py Project: hxhwan/test
def main():
    print "Hello PyCharm"
    a = 1
    b = [1, 2, 3]

    plt.plot(b)
    plt.show()
def convolve_template():
    from plot_Profile_evolution import all_obs
    import numpy as np

    date_list, observations = all_obs()
    x = np.arange(512 - 25 - 50, 512 + 45 + 51)

    delay = []
    for n in observations:
        best_mu = 0
        best_corr = 0

        for mu in np.linspace(512 - 25, 512 + 45, 701):
            template = np.exp(-(x - 512) ** 2 / (2.0 * 6.2 ** 2)) + 0.09 * np.exp(-(x - mu) ** 2 / (2.0 * 8.0 ** 2))
            template /= template.max()
            corr = np.correlate(n, template, mode="valid").max()

            if corr > best_corr:
                best_corr = corr
                best_mu = mu

        delay.append(best_mu - 512)

    plt.plot(date_list, delay, "ko")
    plt.show()
Example #19
0
def compare_networks(default_class, tested_class, data, **kwargs):
    epochs = kwargs.pop("epochs", 100)
    is_comparison_plot = kwargs.pop("is_comparison_plot", False)

    # Compute result for default network (which must be slower)
    network = default_class(**kwargs)

    default_connections = copy.deepcopy(network.connection)
    network.train(*data, epochs=epochs)

    network_default_error = network.last_error_in()
    errors1 = network.normalized_errors_in()

    # Compute result for test network (which must be faster)
    kwargs["connection"] = default_connections
    network = tested_class(**kwargs)

    network.train(*data, epochs=epochs)
    network_tested_error = network.last_error_in()
    errors2 = network.normalized_errors_in()

    if is_comparison_plot:
        error_range = np.arange(max(len(errors1), len(errors2)))
        plt.plot(error_range[: len(errors1)], errors1)
        plt.plot(error_range[: len(errors2)], errors2)
        plt.show()

    return network_default_error, network_tested_error
 def drawLetter(self, list):
     plt.axes()
     for i in range(len(list)):
         print(i)
         if i != (len(list) - 1):
             print(
                 "x are: ",
                 str((list[i])[0]),
                 " ",
                 str((list[i + 1])[0]),
                 " y are: ",
                 str((list[i])[1]),
                 " ",
                 str((list[i + 1])[1]),
             )
             print("drawing line between points ", str(list[i]), " ", str(list[i + 1]))
             dotted_line = plt.Line2D(
                 ((list[i])[0], (list[i + 1])[0]),
                 ((list[i])[0], (list[i + 1])[1]),
                 lw=5.0,
                 ls="-.",
                 marker=".",
                 markersize=50,
                 markerfacecolor="r",
                 markeredgecolor="r",
                 alpha=0.5,
             )
             plt.gca().add_line(dotted_line)
             # plt.scatter(x, y)
     plt.axis("scaled")
     plt.show()
Example #21
0
def hist(PSSMS, window=0.25):
    F = plt.figure()
    # ax1 = F.add_subplot(1,2,1)
    ax2 = F.add_subplot(1, 1, 1)

    # ax1.hist([P.pv[1]  for P in PSSMS ],bins=35, edgecolor="white", color="green")
    colors = ["red" if p.pv[1] < 0.001 and p.pv2[1] < 0.001 else "blue" for p in PSSMS]
    EXS = [p.null[0] for p in PSSMS]
    OBS = [p.MD_score for p in PSSMS]
    VARS = [math.log(1.0 / p.null[1], 10) for p in PSSMS]
    FCS = [p.MD_score - (p.null[0]) for p in PSSMS]

    ax2.scatter(
        [VARS[i] for i in range(len(colors)) if colors[i] == "blue"],
        [FCS[i] for i in range(len(colors)) if colors[i] == "blue"],
        color="blue",
        alpha=0.5,
    )
    ax2.scatter(
        [VARS[i] for i in range(len(colors)) if colors[i] == "red"],
        [FCS[i] for i in range(len(colors)) if colors[i] == "red"],
        color="red",
        alpha=1.0,
        label=r"$p_{s} < 0.001$" + "\n" r"$p_{ns}<0.001$",
    )
    ax2.grid()
    ax2.set_ylim(-max(FCS) - 0.1, max(FCS) + 0.1)
    ax2.set_ylabel(r"$MD_{obs} - E[MD_{null}]$", fontsize=20)
    ax2.set_xlabel(r"$1/Var(MD_{null})$", fontsize=20)
    ax2.legend(loc="best")
    plt.show()
Example #22
0
def show_emoji(name):
    img = name[1:-1]  # :ship: -> ship
    url = "http://www.emoji-cheat-sheet.com/graphics/emojis/{}.png".format(img)
    fo = urlopen(url)
    img = plt.imread(fo)
    plt.imshow(img)
    plt.show()
Example #23
0
    def zplane(self, title="", fontsize=18):
        """ Display filter in the complex plane

        Parameters
        ----------

        """
        rb = self.z
        ra = self.p

        t = np.arange(0, 2 * np.pi + 0.1, 0.1)
        plt.plot(np.cos(t), np.sin(t), "k")

        plt.plot(np.real(ra), np.imag(ra), "x", color="r")
        plt.plot(np.real(rb), np.imag(rb), "o", color="b")
        M1 = -10000
        M2 = -10000
        if len(ra) > 0:
            M1 = np.max([np.abs(np.real(ra)), np.abs(np.imag(ra))])
        if len(rb) > 0:
            M2 = np.max([np.abs(np.real(rb)), np.abs(np.imag(rb))])
        M = 1.6 * max(1.2, M1, M2)
        plt.axis([-M, M, -0.7 * M, 0.7 * M])
        plt.title(title, fontsize=fontsize)
        plt.show()
def findBestRegularization(s, x_sub, y_sub):
    regs = np.linspace(0, 10, 20)
    reg_acc_cv = []
    reg_acc_train = []
    max_acc = 0
    best_reg = 0

    for r in regs:
        th1, th2 = Train.trainSciPy2(s, x_sub, y_sub, r)

        acc_cv = accuracy_score(y_cv, [SimpleNN2.predictClass(s, th1, th2, w) for w in x_cv])
        acc_train = accuracy_score(y_sub, [SimpleNN2.predictClass(s, th1, th2, w) for w in x_sub])
        reg_acc_cv.append(acc_cv)
        reg_acc_train.append(acc_train)

        if max_acc < acc_cv:
            max_acc = acc_cv
            best_reg = r

        print(
            "Validating regularization parameter [{0}]; Train accuracy: [{1}] CV accuracy: [{2}]".format(
                r, acc_train, acc_cv
            )
        )

    print("Best reg param: {0} with accuracy on CV dataset: {1}".format(best_reg, max_acc))

    plt.plot(regs, reg_acc_cv)
    plt.plot(regs, reg_acc_train)
    plt.show()

    return best_reg
def main():
    avg = 0.0
    samples = 0
    values = []

    # Get alpha
    alpha = float(input("IIR alpha (0..1.0): "))

    # Check alpha bounds
    if alpha > 1.0:
        print("Setting alpha to 1.0")
        alpha = 1.0
    if alpha < 0:
        print("Setting alpha to 0.0")
        alpha = 0.0

    # Run the filter until we arrive at 99.9% of newval
    values.append(0.0)
    while avg < 1.0 * 0.999:
        samples += 1
        avg = iirAddValue(avg, alpha, 1.0)
        # Plot value in percent
        values.append(avg / 0.01)
        print("%d: %g" % (samples, avg))

    # Display the results
    plt.title("IIR Response Over Time (Alpha = %g)" % (alpha))
    plt.ylim(0, 110)
    plt.xlabel("Samples")
    plt.ylabel("IIR Output (%)")
    plt.plot(values)
    plt.grid(True)
    plt.show()

    pass
Example #26
0
def run_test(name, re, max_iters, i):
    print "Testing Re = %s" % re

    basepath = os.path.join("results", name, "re%s" % re)
    if not os.path.exists(basepath):
        os.makedirs(basepath)

    ctrl = LBSimulationController(TestLDCSim, default_config={"re": re, "max_iters": max_iters})
    ctrl.run(ignore_cmdline=True)
    horiz = np.loadtxt("ldc_golden/vx2d", skiprows=4)
    vert = np.loadtxt("ldc_golden/vy2d", skiprows=4)

    plt.plot(horiz[:, 0] * 2 - 1, horiz[:, i], ".", label="Paper")
    plt.plot(vert[:, i], 2 * (vert[:, 0] - 0.5), ".", label="Paper")
    save_output(basepath, max_iters)
    plt.legend(loc="lower right")
    plt.gca().yaxis.grid(True)
    plt.gca().xaxis.grid(True)
    plt.gca().xaxis.grid(True, which="minor")
    plt.gca().yaxis.grid(True, which="minor")

    plt.title("2D Lid Driven Cavity, Re = %s" % re)
    print os.path.join(basepath, "results.pdf")
    plt.savefig(os.path.join(basepath, "results.pdf"), format="pdf")

    plt.clf()
    plt.cla()
    plt.show()
Example #27
0
    def draw(self, color="k", deg=True, marker="None"):
        # set angle unit
        if deg:
            conversion_ratio = 180 / np.pi
            unit = 180
        else:
            conversion_ratio = 1
            unit = np.pi

        # generate (phi, theta) points from cliffs (phi, theta_R, theta_L)
        phi_list = []
        theta_list = []

        # phi_list.append(-unit)
        # theta_list.append(self.cliffs[0].theta_L * conversion_ratio)

        for cliff in self.cliffs:
            phi_list.append(cliff.phi * conversion_ratio)
            theta_list.append(cliff.theta_L * conversion_ratio)
            phi_list.append(cliff.phi * conversion_ratio)
            theta_list.append(cliff.theta_R * conversion_ratio)

        # phi_list.append(unit)
        # theta_list.append(self.cliffs[-1].theta_R * conversion_ratio)

        plt.plot(phi_list, theta_list, color=color, marker=marker)
        # plt.gca().set_aspect('equal', adjustable='box')
        plt.gcf().set_size_inches(10, 2.5)
        plt.axis((-unit, unit, 0, unit / 2))
        plt.show()
def hys_test():
    file = "/Users/mike/Google Drive/__code/RockPyV3/test_data/FeNi100-A-b-048-M001-140428-002.hys"
    files = [
        "test_data/FeNi100-A-b-048-M001-140428-002.hys",
        "test_data/FeNi100-A-c-105-M001-140428-001.hys",
        "test_data/FeNi100-A-d-140-M001-140428-001.hys",
        "test_data/FeNi100-A-d-200-M001-140428-001.hys",
        "test_data/FeNi100-A-d-322-M001-140428-001.hys",
    ]
    # file = ['/Users/mike/Google Drive/__PHD/__Projects/003 FeNi/04 data/FeNi10-B/VSM/FeNi10-B-a-054-GC-140623.hys']
    stats_all = []
    # for file in files:
    aux = []
    S = sample.Sample(name="FeNi100-A-d-322-M001")
    H1 = S.add_measurement(mtype="hys", mfile=file, machine="vsm")
    # test, stats = H1.approach_sat(branch='up_field', step=0.001, check=True)
    # aux.append(stats)
    # plt.plot(test[:, 0], test[:, 1])
    # test, stats = H1.approach_sat(branch='down_field', step=0.001, check=False)
    # plt.plot(H1.uf_interp[:,0],H1.uf_interp[:,1], label='interp1')
    # plt.plot(H1.up_field[:,0],H1.up_field[:,1], '+', label='data')
    # plt.plot(H1.df_interp[:,0],H1.df_interp[:,1])

    data = H1.up_field
    for i in np.arange(1.5, 2, 0.1):
        plt.plot(data[:, 0] ** -i, data[:, 1], label=str(i))

    """ approach to saturation test """
    # test, stats = H1.approach_sat(branch='up_field', step=0.01, check=True, corrected=False)
    # test, stats = H1.approach_sat(branch='down_field', step=0.01, check=True, corrected=False)
    # plt.plot(test[:, 0], test[:, 1])
    plt.legend(loc="best")
    plt.xlim([0, 6000])
    plt.show()
Example #29
0
    def _run_fired(self):

        """

		"""
        for i in range(len(self.parameters)):

            # Sets a Poisson Distribution
            if self.parameters[i].dist == "Poisson":
                self.prior_dict[self.parameters[i].name] = 0

                # Sets a Normal Distribution
            if self.parameters[i].dist == "Uniform":
                self.prior_dict[self.parameters[i].name] = (self.parameters[i].min, self.parameters[i].max)

                # Sets a Normal Distribution
            if self.parameters[i].dist == "Normal":
                self.prior_dict[self.parameters[i].name] = self.parameters[i].sig

        print "dictionary created"
        print self.prior_dict

        x, y, w = Data.tracefitmodel.data
        model = Data.tracefitmodel.getMCMC(x, y, priors=self.prior_dict, datamodel=None)

        model.sample(self.iter, burn=self.burn_in)

        Matplot.plot(model)
        plt.show()
        model.stats()

        return self.status
Example #30
0
def showCorners(img, corner_list):
    symbols = ["ro", "bo", "yo"]
    for i, corners in enumerate(corner_list):
        plt.plot(corners[:, 0], corners[:, 1], symbols[i])

    plt.imshow(img, cmap="gray", interpolation="bicubic")
    plt.show()