コード例 #1
0
    def plot_separation(self, i, snp, sep, data):
        '''Plot separation of IBD clique at sample i, SNP snp.'''
        parents = [
            self.ped.sample_id[self.ped.graph.predecessors(i)[a]]
            for a in im.constants.ALLELES
        ]
        print data
        print 'data[0]', data[0]
        print 'data[1]', data[1]
        (k00, k10, k01, k11), line = data[0:2]

        P.figure(1)
        P.clf()
        P.hold(True)
        # P.scatter([p], [q], color='k')
        P.scatter(k00, k10, color='r')
        P.scatter(k01, k11, color='b')
        if line is not None:
            a0, b0, a1, b1 = line
            t = linspace(0, max(k00))
            P.plot(t, polyval([a0, b0], t), 'r')
            t = linspace(0, max(k01))
            P.plot(t, polyval([a1, b1], t), 'b')
        P.title('Sample %d, SNP %d, inbreeding=%.4f, separation=%.2f' %
                (i, snp, self.params.kinship(parents[0], parents[1]), sep))
        P.show()
        P.savefig(os.environ['OBER'] + '/doc/poo/sep-chr%d-%d-%d.png' %
                  (self.chrom, i, snp))
コード例 #2
0
    def test_predict(self):
        # define some easy training data and predict predictive distribution
        circle1 = Ring(variance=1, radius=3)
        circle2 = Ring(variance=1, radius=10)
        
        n = 100
        X = circle1.sample(n / 2).samples
        X = vstack((X, circle2.sample(n / 2).samples))
        y = ones(n)
        y[:n / 2] = -1.0
        
#        plot(X[:n/2,0], X[:n/2,1], 'ro')
#        hold(True)
#        plot(X[n/2:,0], X[n/2:,1], 'bo')
#        hold(False)
#        show()

        covariance = SquaredExponentialCovariance(1, 1)
        likelihood = LogitLikelihood()
        gp = GaussianProcess(y, X, covariance, likelihood)

        # predict on mesh
        n_test = 20
        P = linspace(X[:, 0].min() - 1, X[:, 1].max() + 1, n_test)
        Q = linspace(X[:, 1].min() - 1, X[:, 1].max() + 1, n_test)
        X_test = asarray(list(itertools.product(P, Q)))
#        Y_test = exp(LaplaceApproximation(gp).predict(X_test).reshape(n_test, n_test))
        Y_train = exp(LaplaceApproximation(gp).predict(X))
        print Y_train
        
        print Y_train>0.5
        print y
コード例 #3
0
def main():
    # b = loadroot("ntuples300w5.root")
    # b.loadfile()
    # # b.getwidthdata(0.1)
    # print(b.gethist())
    bins = linspace(0, 1000, 20)
    plot_mass(300, bins)
    bins = linspace(0, 1000, 20)
    plot_mass(500, bins)
    bins = linspace(400, 1600, 20)
    plot_mass(1000, bins)
    bins = linspace(1000, 3000, 20)
    plot_mass(2000, bins)
コード例 #4
0
    def test_get_gaussian_2d(self):
        X = asarray([-1, 1])
        X = reshape(X, (len(X), 1))
        y = asarray([+1 if x >= 0 else -1 for x in X])
        covariance = SquaredExponentialCovariance(sigma=1, scale=1)
        likelihood = LogitLikelihood()
        gp = GaussianProcess(y, X, covariance, likelihood)
        laplace = LaplaceApproximation(gp, newton_start=asarray([3, 3]))
        
        f_mode, L, steps = laplace.find_mode_newton(return_full=True)
        gaussian = laplace.get_gaussian(f_mode, L)
        F = linspace(-10, 10, 20)
        D = zeros((len(F), len(F)))
        Q = array(D, copy=True)
        for i in range(len(F)):
            for j in range(len(F)):
                f = asarray([F[i], F[j]])
                D[i, j] = gp.log_posterior_unnormalised(f)
                Q[i, j] = gaussian.log_pdf(f.reshape(1, len(f)))
        
        subplot(1, 2, 1)
        pcolor(F, F, D)
        hold(True)
        plot(steps[:, 0], steps[:, 1])
        plot(f_mode[1], f_mode[0], 'mo', markersize=10)
        hold(False)
        colorbar()
        subplot(1, 2, 2)
        pcolor(F, F, Q)
        hold(True)
        plot(f_mode[1], f_mode[0], 'mo', markersize=10)
        hold(False)
        colorbar()
#        show()
        clf()
コード例 #5
0
ファイル: curve.py プロジェクト: martin1/thesis
def get_distance(x1, y1, x2, y2, points=10000, show_direction = False):
    
    y_max = 2000.0
    y_min = -200.0
    
    f1_inv = get_inverse_function(x1, y1)
    f2_inv = get_inverse_function(x2, y2)
    
    y = linspace(y_max, y_min, points)
    
    dist = list()
    dist_y = list()
    min_points = list()
    max_points = list()
    
    for y_n in y:
        if show_direction == False:
            d = abs(f1_inv(y_n) - f2_inv(y_n))
        elif show_direction == True:
            d = f1_inv(y_n) - f2_inv(y_n)
        dist.append(d)
    
    max_y = y[dist.index(max(dist))]
    min_y = y[dist.index(min(dist))]
    dist = [max(dist), min(dist), sum(dist)/float(len(dist))]
    min_points = [[f1_inv(min_y), min_y],[f2_inv(min_y), min_y]]
    max_points = [[f1_inv(max_y), max_y],[f2_inv(max_y), max_y]]
    
    return dist, min_points, max_points
コード例 #6
0
ファイル: cost.py プロジェクト: uoe-agents/IGP2
    def resample_trajectory(self, trajectory: ip.VelocityTrajectory, n: int, k: int = 3):

        zeros = [id for id in np.argwhere(trajectory.velocity <= trajectory.velocity_stop)]
        if zeros and len(zeros) < len(trajectory.velocity) - 1:
            path = np.delete(trajectory.path, zeros, axis=0)
            velocity = np.delete(trajectory.velocity, zeros)
            heading = np.delete(trajectory.heading, zeros)
            timesteps = np.delete(trajectory.timesteps, zeros)
        else:
            path = trajectory.path
            velocity = trajectory.velocity
            heading = trajectory.heading
            timesteps = trajectory.timesteps

        trajectory_nostop = ip.VelocityTrajectory(path, velocity, heading, timesteps)
        u = trajectory_nostop.pathlength
        u_new = linspace(0, u[-1], n)
        k = min(k, len(velocity) - 1)

        if k != 0:
            tck, _ = splprep([path[:, 0], path[:, 1], velocity, heading], u=u, k=k, s=0)
            tck[0] = self.fix_points(tck[0])
            path_new = np.empty((n, 2), float)
            path_new[:, 0], path_new[:, 1], velocity_new, heading_new = splev(u_new, tck)
            trajectory_resampled = ip.VelocityTrajectory(path_new, velocity_new, heading_new)
        else:
            trajectory_resampled = trajectory

        return trajectory_resampled
コード例 #7
0
def plot(hist0, hist1, gaus0, gaus1):
    xvals = linspace(0.0, 1.0, linspace_size)
    plt.figure()
    if hist0 is not None and hist1 is not None:
        if gaus0 is not None and gaus1 is not None:
            plt.subplot(1, 2, 1)
        plt.hist([
            hist1,
            hist0,
        ],
                 10,
                 normed=False,
                 histtype='bar',
                 stacked=False,
                 label=[u"pozitívne", u"negatívne"])
        plt.xlabel(u'Výstup klasifikátora')
        plt.ylabel(u'Počet')
        plt.legend(loc=0)
    if gaus0 is not None and gaus1 is not None:
        if hist0 is not None and hist1 is not None:
            plt.subplot(1, 2, 2)
        plt.hold(True)
        plt.plot(xvals, gaus1(xvals), label=u"pozitívne", linewidth=line_width)
        plt.plot(xvals, gaus0(xvals), label=u"negatívne", linewidth=line_width)
        plt.xlabel(u'Výstup klasifikátora')
        plt.ylabel(u'Hustota')
        plt.legend(loc=9)
コード例 #8
0
def solveSystem (t, y):
    #    System: y = 1 - exp^(-t/T)   ^    t: time[s]    T: time constant[s]
    #    Isolate T:
    #    ln(1 - y) * T = -t           for    y < 1
    #    A[m x 1]:    ln(1 - y_i)     m equations
    #    b[m x 1]:    -t_i            i index
    
    #    Generate normal equations    A^T * A * x = A^T * b
    A = []
    b = []
    
    for i in range(len(t)):
        A.append(math.log(1 - y[i]))
        b.append([-t[i]])
    
    A = numpy.array(A)
    b = numpy.array(b)
    A_norm = numpy.dot(numpy.transpose(A), A)
    b_norm = numpy.dot(numpy.transpose(A), b)
    
    #    Solve
    T = b_norm / A_norm
    
    #    Setup output
    lMin = min(t)
    lMax = max(t)
    t = linspace(lMin, lMax, 10000)
    y = numpy.array([1 - math.exp(-i/T) for i in t])
    
    return T, t, y
コード例 #9
0
    def test_mode_newton_2d(self):
        X = asarray([-1, 1])
        X = reshape(X, (len(X), 1))
        y = asarray([+1 if x >= 0 else -1 for x in X])
        covariance = SquaredExponentialCovariance(sigma=1, scale=1)
        likelihood = LogitLikelihood()
        gp = GaussianProcess(y, X, covariance, likelihood)
        laplace = LaplaceApproximation(gp, newton_start=asarray([3, 3]))
        
        f_mode, _, steps = laplace.find_mode_newton(return_full=True)
        F = linspace(-10, 10, 20)
        D = zeros((len(F), len(F)))
        for i in range(len(F)):
            for j in range(len(F)):
                f = asarray([F[i], F[j]])
                D[i, j] = gp.log_posterior_unnormalised(f)
           
        idx = unravel_index(D.argmax(), D.shape)
        empirical_max = asarray([F[idx[0]], F[idx[1]]])
        
        pcolor(F, F, D)
        hold(True)
        plot(steps[:, 0], steps[:, 1])
        plot(f_mode[1], f_mode[0], 'mo', markersize=10)
        hold(False)
        colorbar()
        clf()
#        show()
           
        self.assertLessEqual(norm(empirical_max - f_mode), 1)
コード例 #10
0
    def test_indexing_with_arrays_of_indices(self):
        a = arange(12)
        i = array([1,1,3,8,5])
        numpy.testing.assert_array_equal(a[i], i)

        j = array([[3,4],
                   [9,7]])
        
        numpy.testing.assert_array_equal(a[j],array([[3,4],
                                                     [9,7]]))
        palette = array([[0,0,0],
                         [255,0,0],
                         [0,255,0],
                         [0,0,255],
                         [255,255,255]])
        image = array([[0,1,2,0],[0,3,4,0]])
        colour_image = palette[image]

        numpy.testing.assert_array_equal(colour_image, array([[[0,0,0],
                                                               [255,0,0],
                                                               [0,255,0],
                                                               [0,0,0]],
                                                             [[0,0,0],
                                                              [0,0,255],
                                                              [255,255,255],
                                                              [0,0,0]]]))
        
        a = arange(12).reshape(3,4)
        i = array([[0,1],
                   [1,2]])
        j = array([[2,1],
                   [3,3]])
        
        numpy.testing.assert_array_equal(a[i,j], array([[2,5],
                                                        [7,11]]))
        numpy.testing.assert_array_equal(a[i,2], array([[2,6],
                                                        [6,10]]))
        
        numpy.testing.assert_array_equal(a[i,:], array([[[0,1,2,3],
                                                         [4,5,6,7]],
                                                        [[4,5,6,7],
                                                         [8,9,10,11]]]))
        
        numpy.testing.assert_array_equal(a[:,j], array([[[2,1],
                                                         [3,3]],
                                                        [[6,5],
                                                         [7,7]],
                                                        [[10,9],
                                                         [11,11]]]))

        time = linspace(20,145,5)
        data = sin(arange(20).reshape(5,4))
        ind = data.argmax(axis=0)
        time_max = time[ind]
        data_max = data[ind, xrange(data.shape[1])]
        numpy.testing.assert_array_equal(data_max, data.max(axis=0))
コード例 #11
0
ファイル: Banana.py プロジェクト: karlnapf/kameleon-mcmc
 def get_proposal_points(self, n):
     """
     Returns n points which lie on a uniform grid on the "center" of the banana
     """
     if self.dimension == 2:
         (xmin, xmax), _ = self.get_plotting_bounds()
         x1 = linspace(xmin, xmax, n)
         x2 = self.bananicity * (x1 ** 2 - self.V)
         return array([x1, x2]).T
     else:
         return Distribution.get_proposal_points(self, n)
コード例 #12
0
ファイル: Banana.py プロジェクト: mgong2/kameleon-mcmc
 def get_proposal_points(self, n):
     """
     Returns n points which lie on a uniform grid on the "center" of the banana
     """
     if self.dimension == 2:
         (xmin, xmax), _ = self.get_plotting_bounds()
         x1 = linspace(xmin, xmax, n)
         x2 = self.bananicity * (x1**2 - self.V)
         return array([x1, x2]).T
     else:
         return Distribution.get_proposal_points(self, n)
コード例 #13
0
def bezier_approximation_interp(Xo, Yo):
    Xp = []
    Yp = []
    Xp.append(Xo[0])
    Yp.append(Yo[0])
    for i in range(1, len(Xo) - 2):
        Xp.append(Xo[i]), Yp.append(Yo[i])
        Xp.append((Xo[i] + Xo[i + 1]) / 2), Yp.append((Yo[i] + Yo[i + 1]) / 2)
    Xp.append(Xo[-2])
    Yp.append(Yo[-2])
    Xp.append(Xo[-1])
    Yp.append(Yo[-1])
    print(Xp)

    X = []
    Y = []
    for i in range(0, len(Xp) - 3, 2):
        distance = np.sqrt((Xp[i + 2] - Xp[i])**2 + (Yp[i + 2] - Yp[i])**2)
        distance = np.int(np.ceil(distance))
        mt = 1 * (distance - 1) / distance
        for t in linspace(0, mt, distance):
            x0, y0 = line(Xp[i], Xp[i + 1], Yp[i], Yp[i + 1], t)
            x1, y1 = line(Xp[i + 1], Xp[i + 2], Yp[i + 1], Yp[i + 2], t)
            x, y = line(x0, x1, y0, y1, t)
            X.append(x)
            Y.append(y)
    distance = np.sqrt((Xp[-1] - Xp[-3])**2 + (Yp[-1] - Yp[-3])**2)
    distance = np.int(np.ceil(distance))
    for t in linspace(0, 1, distance):
        x0, y0 = line(Xp[-3], Xp[-2], Yp[-3], Yp[-2], t)
        x1, y1 = line(Xp[-2], Xp[-1], Yp[-2], Yp[-1], t)
        x, y = line(x0, x1, y0, y1, t)
        X.append(x)
        Y.append(y)

    f = interp1d(X,
                 Y,
                 kind="cubic",
                 fill_value="extrapolate",
                 assume_sorted=True)
    return X, Y, f
コード例 #14
0
def plot3(hist, gaus, hist2):
    xvals = linspace(0.0, 1.0, linspace_size)

    plt.figure()
    plt.subplot(1, 3, 1)

    plt.bar(range(len(hist)), hist)

    plt.legend(loc=0)
    plt.subplot(1, 3, 2)
    plt.plot(xvals, gaus(xvals), label="anotated 1", linewidth=line_width)

    plt.subplot(1, 3, 3)
    plt.bar(range(len(hist2)), hist2)
コード例 #15
0
ファイル: task_6.py プロジェクト: AlekseiVoron/Modeling
def calc_intervals_range(stream: list) -> dict:
    max_x = max(stream)
    intervals = {}
    for interval_end in linspace(0, max_x,
                                 21)[1:]:  # нулевой интервал следует выбросить
        intervals[interval_end] = []

    for x in stream:
        for interval in intervals:
            if x <= interval:
                intervals[interval].append(x)
                break

    return intervals
コード例 #16
0
ファイル: poo.py プロジェクト: orenlivne/ober
 def plot_separation(self, i, snp, sep, data):
     '''Plot separation of IBD clique at sample i, SNP snp.''' 
     parents = [self.ped.sample_id[self.ped.graph.predecessors(i)[a]] for a in im.constants.ALLELES]
     print data
     print 'data[0]', data[0]
     print 'data[1]', data[1]
     (k00, k10, k01, k11), line = data[0:2]
 
     P.figure(1)
     P.clf()
     P.hold(True)
     # P.scatter([p], [q], color='k')
     P.scatter(k00, k10, color='r')
     P.scatter(k01, k11, color='b')
     if line is not None:
         a0, b0, a1, b1 = line        
         t = linspace(0, max(k00))
         P.plot(t, polyval([a0, b0], t), 'r')
         t = linspace(0, max(k01))
         P.plot(t, polyval([a1, b1], t), 'b')
     P.title('Sample %d, SNP %d, inbreeding=%.4f, separation=%.2f' % (i, snp, self.params.kinship(parents[0], parents[1]), sep))
     P.show()
     P.savefig(os.environ['OBER'] + '/doc/poo/sep-chr%d-%d-%d.png' % (self.chrom, i, snp))
コード例 #17
0
ファイル: OnsetSmoothing.py プロジェクト: xrick/pypYIN
    def __init__(self, ONSET_SIGMA_IN_FRAMES):
        '''
        Constructor
        ONSET_SIGMA_IN_FRAMES: 
            the distance to onset, unit: number of frames, zero means at an onset frame
        '''

        minVal = norm.ppf(0.01)
        maxVal = norm.ppf(0.5)

        quantileVals = linspace(maxVal, minVal, ONSET_SIGMA_IN_FRAMES + 1)
        self.liks = numpy.zeros((ONSET_SIGMA_IN_FRAMES + 1, 1))

        for onsetDist in range(ONSET_SIGMA_IN_FRAMES + 1):
            self.liks[onsetDist] = norm.pdf(quantileVals[onsetDist])
コード例 #18
0
ファイル: plots.py プロジェクト: orenlivne/ober
def plot_fill_fraction(problem, color='b', zoom=None, ticks=None, label=None):
    '''Plot the filled fraction in each sample of a phased data set.'''
    data = problem.fill_fraction()
    # Sort by ascending fill %
    data = data[np.argsort(data[:, 1])]
    P.plot(range(1, data.shape[0] + 1), data[:, 1], color + '.-', label=label)
    min_y = data[0, 1] * 0.95
    if zoom:
        max_x = np.where(data[:, 1] > zoom)[0][0]
        P.xlim([0, max_x + 1])
    if ticks:
        yticks = linspace(min_y, 1.0, ticks)
        P.yticks(yticks, ['%.3f' % (t, ) for t in yticks])
    P.xlabel('Sample')
    P.ylabel('Filled Haplotype %')
    P.grid(True)
    return data
コード例 #19
0
ファイル: plots.py プロジェクト: orenlivne/ober
def plot_fill_fraction(problem, color='b', zoom=None, ticks=None, label=None):
    '''Plot the filled fraction in each sample of a phased data set.'''
    data = problem.fill_fraction()
    # Sort by ascending fill %
    data = data[np.argsort(data[:, 1])]
    P.plot(range(1, data.shape[0] + 1), data[:, 1], color + '.-', label=label)
    min_y = data[0, 1] * 0.95
    if zoom:
        max_x = np.where(data[:, 1] > zoom)[0][0]
        P.xlim([0, max_x + 1])
    if ticks:
        yticks = linspace(min_y, 1.0, ticks)
        P.yticks(yticks, ['%.3f' % (t,) for t in yticks])
    P.xlabel('Sample')
    P.ylabel('Filled Haplotype %')
    P.grid(True)
    return data
コード例 #20
0
def Polinomios(a, b):
    x = Symbol('x')
    ylen = b.size
    yprom = 0
    for i in range(ylen):
        yprom += b[i]

    yprom *= (1 / ylen)
    p1 = polyfit(a, b, 1)
    z1 = poly1d(p1)
    print("----------------------------------------")
    print("Polimonio 1: ")
    pprint(p1[0] * x + p1[1])
    Sr1 = 0
    St1 = 0
    for i in range(ylen):
        Sr1 += (b[i] - z1(a[i]))**2
        St1 += (b[i] - yprom)**2
    r1 = sqrt((St1 - Sr1) / St1)
    print("Coeficiente =", r1)

    p2 = polyfit(a, b, 2)
    z2 = poly1d(p2)
    print("Polimonio 2: ")
    pprint(p2[0] * x**2 + p2[1] * x + p2[2])
    Sr2 = 0
    St2 = 0
    for i in range(ylen):
        Sr2 += (b[i] - z2(a[i]))**2
        St2 += (b[i] - yprom)**2
    r2 = sqrt((St2 - Sr2) / St2)
    print("Coeficiente =", r2)
    xp = linspace(0, 2)
    _ = plt.plot(a, b, ".", xp, z1(xp), "-", xp, z2(xp), "--")
    plt.show()
    p3 = polyfit(a, b, 3)
    pprint(p3[0] * x**3 + p3[1] * x**2 + p3[2] * x + p3[3])
    p4 = polyfit(a, b, 4)
    pprint(p4[0] * x**4 + p4[1] * x**3 + p4[2] * x**2 + p4[3] * x + p4[4])
    p5 = polyfit(a, b, 5)
    pprint(p5[0] * x**5 + p5[1] * x**4 + p5[2] * x**3 + p5[3] * x**2 +
           p5[4] * x + p5[5])
    p6 = polyfit(a, b, 6)
    pprint(p6[0] * x**6 + p6[1] * x**5 + p6[2] * x**4 + p6[3] * x**3 +
           p6[4] * x**2 + p6[5] * x + p6[6])
コード例 #21
0
ファイル: util.py プロジェクト: bmerrison/morphforge
        def newFunctor(
                env,
                _voltage_interpolation_values=voltage_interpolation_values):

            old_chl = chl_functor(env)
            assert isinstance(
                old_chl, (StdChlAlphaBeta, StdChlAlphaBetaBeta
                          ))  # or issubclass(StdChlAlphaBetaBeta, old_chl)

            # New Name
            if new_name is not None:
                chl_name = new_name
            else:
                chl_name = old_chl.name + clone_name_suffix

            # Interpolation voltages:
            # voltage_interpolation_values=voltage_interpolation_values
            if _voltage_interpolation_values is None:
                _voltage_interpolation_values = linspace(-80, 60,
                                                         10) * unit('mV')

                # Copy the state variables
            new_state_vars = {}
            for state_var in old_chl.get_state_variables():
                alpha, beta = old_chl.get_alpha_beta_at_voltage(
                    statevar=state_var, V=_voltage_interpolation_values)
                inf, tau = InfTauCalculator.alpha_beta_to_inf_tau(alpha, beta)
                V = _voltage_interpolation_values.rescale('mV').magnitude
                inf = inf.rescale(pq.dimensionless).magnitude
                tau = tau.rescale('ms').magnitude
                new_state_vars[state_var] = InfTauInterpolation(V=V,
                                                                inf=inf,
                                                                tau=tau)

            chl = env.Channel(
                MM_InfTauInterpolatedChannel,
                name=chl_name,
                ion=old_chl.ion,
                equation=old_chl.eqn,
                conductance=old_chl.conductance,
                reversalpotential=old_chl.reversalpotential,
                statevars_new=new_state_vars,
            )
            return chl
コード例 #22
0
ファイル: task.py プロジェクト: studentArtemkin/CT_MM
def test0():
    N = 10
    dim = 1
    NofThreads = 5
    G = 6.67408 * numpy.power(10.0, -11)
    data = formData(N, dim)
    t = linspace(0, 10, 101)
    time0 = 0
    time1 = 0
    time2 = 0
    time3 = 0
    time4 = 0
    time5 = 0
    tmp_time = time.time()
    solution_test = test(data, N, dim, G, t)
    time0 = time.time() - tmp_time
    tmp_time = time.time()
    solution_Verlet = solve1(data, N, dim, G, t)
    time1 = time.time() - tmp_time
    tmp_time = time.time()
    solution_Verlet_threading = solve2(data, N, dim, NofThreads, G, t)
    time2 = time.time() - tmp_time
    tmp_time = time.time()
    solution_Verlet_multiproessing = solve3(data, N, dim, NofThreads, G, t)
    time3 = time.time() - tmp_time
    tmp_time = time.time()
    solution_Verlet_cython = Verlet1.solve4(data, N, dim, G, t)
    time4 = time.time() - tmp_time
    tmp_time = time.time()
    solution_Verlet_CUDA = solve5(data, N, dim, G, t)
    time5 = time.time() - tmp_time

    print('test: ' + str(solution_test) + '\n')
    print('Verlet: ' + str(solution_Verlet) + '\n')
    print('Verlet_threading: ' + str(solution_Verlet_threading) + '\n')
    print('Verlet_multiprocessing: ' + str(solution_Verlet_multiproessing) +
          '\n')
    print('Verlet_cython: ' + str(solution_Verlet_cython) + '\n')
    print('Verlet_CUDA: ' + str(solution_Verlet_CUDA) + '\n')

    print(
        str(time0) + ' ' + str(time1) + ' ' + str(time2) + ' ' + str(time3) +
        ' ' + str(time4) + ' ' + str(time5))
コード例 #23
0
    def sample_circle_data(n, noise_level=0.025, offset=0.05, seed_init=None):
        if seed_init is not None:
            seed(seed_init)

        # decision surface for sampled data
        thetas = linspace(0, pi / 2, n)
        X = sin(thetas) * (1 + randn(n) * noise_level)
        Y = cos(thetas) * (1 + randn(n) * noise_level)

        # randomly select labels and distinguish data
        labels = randint(0, 2, n) * 2 - 1
        idx_a = labels > 0
        idx_b = labels < 0
        X[idx_a] *= (1. + offset)
        Y[idx_a] *= (1. + offset)
        X[idx_b] *= (1. - offset)
        Y[idx_b] *= (1. - offset)

        return asarray(zip(X, Y)), labels
コード例 #24
0
ファイル: GPData.py プロジェクト: karlnapf/kameleon-mcmc
 def sample_circle_data(n, noise_level=0.025, offset=0.05, seed_init=None):
     if seed_init is not None:
         seed(seed_init)
     
     # decision surface for sampled data
     thetas = linspace(0, pi / 2, n)
     X = sin(thetas) * (1 + randn(n) * noise_level)
     Y = cos(thetas) * (1 + randn(n) * noise_level)
     
     # randomly select labels and distinguish data
     labels = randint(0, 2, n) * 2 - 1
     idx_a = labels > 0
     idx_b = labels < 0
     X[idx_a] *= (1. + offset)
     Y[idx_a] *= (1. + offset)
     X[idx_b] *= (1. - offset)
     Y[idx_b] *= (1. - offset)
     
     return asarray(zip(X, Y)), labels
コード例 #25
0
def plot1(hist, gaus):
    xvals = linspace(0.0, 1.0, linspace_size)

    plt.figure()
    plt.subplot(1, 2, 1)
    # plt.hist(
    #     [
    #         hist
    #     ],
    #     10,
    #     normed=False,
    #     histtype='bar',
    #     stacked=False,
    # )

    plt.bar(range(len(hist)), hist)

    plt.legend(loc=0)
    plt.subplot(1, 2, 2)
    plt.plot(xvals, gaus(xvals), label="anotated 1", linewidth=line_width)
コード例 #26
0
ファイル: curve.py プロジェクト: martin1/thesis
def get_avg_func(x, y, points=1000, mean='arithmetic'):
    
    y_max = 2000.0
    y_min = -200.0
    
    y_avg = linspace(y_max, y_min, points)
    x_avg = list()
    f = list()
    avg_dist = list()
    f_mean = get_mean_function(mean)
    
    #get inverse functions for all curves
    for i in range(0, len(x)):
            f.append(get_inverse_function(x[i], y[i]))
    
    
    for i in range(0, len(y_avg)):#for every point in the new average curve...
        x_avg.append(f_mean([f[j](y_avg[i]) for j in range(0, len(x))]))
    
    return lambda x: interp(x, x_avg, y_avg), x_avg
コード例 #27
0
def plot_rac(df: DataFrame, graph):
    """Plots the RAC curve for the given DataFrame.

    Args:
        df (DataFrame): DataFrame with risk values.
        graph: Object to plot the graph on.
    """
    # Set axes parameters
    graph.set_xlabel("Risk (%)", fontsize=10)
    graph.xaxis.set_major_formatter(PercentFormatter(xmax=1.00))
    graph.set_ylabel("RAC (%)", fontsize=10)
    graph.yaxis.set_major_formatter(PercentFormatter(xmax=1.00))
    # Equally-spaced points
    x = linspace(0, 1, 50)
    # Plot for each column in the dataframe
    for column in df.columns:
        y = [_risk_and_coverage(df[column], r) for r in x]
        graph.scatter(x, y, label=f"BK = {column}")
        graph.plot(x, y)
    graph.legend(fontsize=10)
コード例 #28
0
 def __init__(self, deviationInSec):
     '''
     #@param deviationInSec: how much vocal can deviate from refDur
     '''
     
       
     # normal distribution with 2 symmetric lobes
     self.numDurs = int(2* deviationInSec * NUMFRAMESPERSEC)
     if not self.numDurs % 2:
         self.numDurs += 1
         
     self.minVal = norm.ppf(0.01)
     self.maxVal= norm.ppf(0.99)
     
     quantileVals  = linspace(self.minVal, self.maxVal, self.numDurs )
     self.liks = numpy.zeros((self.numDurs,1)) 
     for d in range(0,self.numDurs):
         self.liks[d] = norm.pdf(quantileVals[d])
     
     self.liks = numpy.log(self.liks)
コード例 #29
0
 def create_interpolated_attr(self,
                              c_org,
                              selected_attrs=None,
                              max_val=5.0):
     """Generate target domain labels for debugging and testing: linearly sample attribute. Contains a list for each attr"""
     all_lists = []
     for i in range(len(selected_attrs)):
         c_trg_list = []  #[c_org]
         alphas = [
             -max_val, -((max_val - 1) / 2.0 + 1), -1, -0.5, 0, 0.5, 1,
             ((max_val - 1) / 2.0 + 1), max_val
         ]
         if max_val == 1:
             alphas = linspace(-1, 1, 9)  #[-1,-0.75,-0.5,0,0.5,1,]
         #alphas = np.linspace(-max_val, max_val, 10)
         for alpha in alphas:
             c_trg = c_org.clone()
             c_trg[:, i] = torch.full_like(c_trg[:, i], alpha)
             c_trg_list.append(c_trg)
         all_lists.append(c_trg_list)
     return all_lists
コード例 #30
0
ファイル: DurationPdf.py プロジェクト: EQ4/HMMDuration
 def __init__(self, deviationInSec):
     '''
     #@param deviationInSec: how much vocal can deviate from refDur
     deviationInSec = 0.07
     '''
     
       
     # normal distribution with 2 symmetric lobes
     self.numDurs = int(2* deviationInSec * NUMFRAMESPERSEC)
     if not self.numDurs % 2:
         self.numDurs += 1
         
     self.minVal = norm.ppf(0.01)
     self.maxVal= norm.ppf(0.99)
     
     quantileVals  = linspace(self.minVal, self.maxVal, self.numDurs )
     self.liks = numpy.zeros((self.numDurs,1)) 
     for d in range(0,self.numDurs):
         self.liks[d] = norm.pdf(quantileVals[d])
     
     self.liks = numpy.log(self.liks)
コード例 #31
0
 def train(self, data, target):
     """
     Uses KDE to estimate the best classification threshold (delta).
     :param data: shapelet transformed dataset
     :type data: np.array, shape = (len(dataset),)
     :param target: list of 0 (event has NOT occurred during in this time series) or 1 if it has
     :type target: np.array, shape = (len(dataset),)
     :return: information gain, delta, f_c(delta)
     :rtype: tuple(float, float, float)
     """
     nin_class = data[target == 0]
     np_c = len(nin_class) / (len(target) + .0)
     in_class = data[target == 1]
     p_c = len(in_class) / (len(target) + .0)
     density = int(self.resolution * (max(data) - min(data)))
     dist_space = linspace(min(data), max(data), density)
     f_c = gaussian_kde(in_class)(dist_space)
     nf_c = gaussian_kde(nin_class)(dist_space)
     P_c = p_c * f_c / (np_c * nf_c + p_c * f_c)
     P_c[P_c > self.p] = -P_c[P_c > self.p]
     delta_candidates = argrelmax(P_c, order=3)[0]
     bsf_information_gain = 0
     bsf_delta = 0
     bsf_f_c_delta = 0
     for i in delta_candidates:
         i = [i]
         delta = dist_space[i][0]
         d1 = target[data < delta]
         d2 = target[data >= delta]
         igain = information_gain(target, d1, d2)
         f_c_delta = nf_c[i][0]
         if igain > bsf_information_gain:
             bsf_information_gain = igain
             bsf_delta = delta
             bsf_f_c_delta = f_c_delta
         elif igain == bsf_information_gain and f_c_delta < bsf_f_c_delta:
             bsf_information_gain = igain
             bsf_delta = delta
             bsf_f_c_delta = f_c_delta
     return bsf_information_gain, bsf_delta, bsf_f_c_delta
コード例 #32
0
 def updateSignals(self, moneyManager, marketManager, estimateParameter, rates):
     # get current value for market
     V_tilde_M = marketManager.getFeedInfo('AE', 'QTE_CNT1')
     S_tilde_M = self.marketManager.getFeedInfo('AE', 'WTD_AVE1')
     
     # get current value for execution        
     V_tilde_E = moneyManager.getStatistics()
     S_tilde_E = moneyManager.getExecQty()
     
     # get estimate parameters        # market VWAP
     Exp_S_hat_M = estimateParameter['Exp_S_hat_M']        
     Var_S_hat_M = estimateParameter['Var_S_hat_M']
     
     # market volume
     Exp_V_hat_M_E = estimateParameter['Exp_V_hat_M_E']
     Var_V_hat_M_E = estimateParameter['Var_V_hat_M_E']
     
     # slippage
     exp_slippage = estimateParameter['exp_slippage']
     var_slippage = estimateParameter['var_slippage']
     
     # compute the mean and variance of slippage
     self.additional_params['ref_rate'] = rates['ref_rate']
     range_of_rates = linspace(rates['min_rate'], rates['max_rate'], rates['step_rate'])
     value_fct = []
     for r in range_of_rates:
         mean_P = self.mean_P(r, V_tilde_E, V_tilde_M, S_tilde_E, S_tilde_M, Exp_S_hat_M, Exp_V_hat_M_E, exp_slippage)
         mean_Q = self.mean_Q(r, V_tilde_M, Exp_V_hat_M_E)
         cov_P_Q = self.cov_P_Q(r)
         var_P = self.var_P(r, V_tilde_E, V_tilde_M, Var_S_hat_M, Var_V_hat_M_E, var_slippage)
         var_Q = self.var_Q(r, Var_V_hat_M_E)
         
         mean_s = self.meanSlippage(mean_P, mean_Q, cov_P_Q, var_Q)                
         var_s = self.varSlippage(mean_P, mean_Q, cov_P_Q, var_P, var_Q)
     
         value_fct = obj_function(mean_s, var_s, vec_r);
             [val_max idx_max] = max(value_fct);
             min_r = V_tilde_E/(V_tilde_M + Exp_V_hat_M_E);
             
             optimal_r(i_cp,i_cdv) = max(vec_r(idx_max), min_r);
コード例 #33
0
ファイル: util.py プロジェクト: bmerrison/morphforge
        def newFunctor(env, _voltage_interpolation_values=voltage_interpolation_values):



            old_chl = chl_functor(env)
            assert isinstance(old_chl, (StdChlAlphaBeta,
                              StdChlAlphaBetaBeta))  # or issubclass(StdChlAlphaBetaBeta, old_chl)

            # New Name
            if new_name is not None:
                chl_name = new_name
            else:
                chl_name = old_chl.name + clone_name_suffix

            # Interpolation voltages:
            # voltage_interpolation_values=voltage_interpolation_values
            if _voltage_interpolation_values is None:
                _voltage_interpolation_values = linspace(-80, 60, 10) * unit('mV')

                        # Copy the state variables
            new_state_vars = {}
            for state_var in old_chl.get_state_variables():
                alpha, beta = old_chl.get_alpha_beta_at_voltage(statevar=state_var, V=_voltage_interpolation_values)
                inf, tau = InfTauCalculator.alpha_beta_to_inf_tau(alpha, beta)
                V = _voltage_interpolation_values.rescale('mV').magnitude
                inf = inf.rescale(pq.dimensionless).magnitude
                tau = tau.rescale('ms').magnitude
                new_state_vars[state_var] = InfTauInterpolation(V=V, inf=inf, tau=tau)


            chl = env.Channel(
                MM_InfTauInterpolatedChannel,
                name=chl_name,
                ion=old_chl.ion,
                equation=old_chl.eqn,
                conductance=old_chl.conductance,
                reversalpotential=old_chl.reversalpotential,
                statevars_new=new_state_vars,
               )
            return chl
コード例 #34
0
ファイル: dataVerwerk.py プロジェクト: metrorail/skripsie
def dagDict(treine):
    dagtreine = {}
    
    # maak 'n dag se rooster vol van die basisuurpatroon en stoor dit in 'n CSV-formaat...
    nieBUPure = int(nieBUPseries.values()[0]/(60.0-nieBUPseries.values()[0]))    
    for cp in linspace(0,24-nieBUPure*2,24.0/nieBUPure-1):  # vir nieBUPure=3 (45 min periode): [0,3,6,9,12,15,18]
        # Stap deur die treine wat volgens treinnommer gesorteer is (begin dus by 0101 en eindig by 9999)
        for trein in sorted(treine):
            # Verwerk eers die treine wat nie volgens die BUP bedryf word nie
            if(nieBUPseries.has_key(trein[0:2])):
                
                # Die huidige trein moenie eindig met 01 nie en ook nie met 02 nie
                if(trein[2:4] != '01' and trein[2:4] != '02'):
                    vorigeTreinInSerieNo = '{:0>4}'.format(str(int(trein)-2))  
                    if(treine[trein]['tyd'][0] > treine[vorigeTreinInSerieNo]['tyd'][0]):
                        # val nog in selfe uur, hoef niks te doen nie.
                        treine[trein]['cp'] = treine[vorigeTreinInSerieNo]['cp']
                        tye = np.array(treine[trein]['tyd'])+treine[trein]['cp']/24.0
                       
                    else:
                        treine[trein]['cp'] = treine[vorigeTreinInSerieNo]['cp'] +1 
                        tye = np.array(treine[trein]['tyd'])+(treine[trein]['cp'])/24.0
                else:
                    treine[trein]['cp'] = cp/3*3
                    tye = np.array(treine[trein]['tyd'])+treine[trein]['cp']/24.0
                uniekeTreinno = '{:0>4}'.format(str(int(trein)+int(cp)/3*2*(nieBUPure+1)))
                dagtreine[uniekeTreinno] = {'stasieKode':treine[trein]['stasieKode'], 'tyd':tye.tolist(), 'kmPunt':treine[trein]['kmPunt'], 'trajek':treine[trein]['trajek']}                    
                
            # Verwerk dan die treine wat wel volgens die BUP werk
            elif(BUPseries.has_key(trein[0:2])): 
                for cpa in [cp, cp+1, cp+2]:
                    tye = np.array(treine[trein]['tyd'])+cpa/24.0
                    uniekeTreinno = '{:0>4}'.format(str(int(trein)+int(cpa)*2*(60/BUPseries[trein[0:2]])))
                    dagtreine[uniekeTreinno] = {'stasieKode':treine[trein]['stasieKode'], 'tyd':tye.tolist(), 'kmPunt':treine[trein]['kmPunt'], 'trajek':treine[trein]['trajek']}
            else:
                print 'FOUT: Treinserie ', trein, ' kom in die CPLEX-afvoer voor, maar die periode is nie bekend nie! \nGaan die leers BUPseries.csv en nieBUPseries.csv na.'
    with open("dagrooster.txt",'wb') as outfile:
        json.dump(dagtreine, outfile)
コード例 #35
0
def main():
    massset = set()
    for each in os.listdir("ntuples"):
        if ".root" in each:
            massset.add(int(each.split("w")[0]))
    i = 0
    processes = []
    for each_mass in sorted(massset):
        if each_mass < 300:
            continue
        maxv = int(each_mass * 2.5)
        if maxv > 3000:
            maxv = 3000
        i += 1
        # plot_mass_modified(each_mass, linspace(0, int(maxv), 25))
        t = multiprocessing.Process(target=plot_mass_modified,
                                    args=(each_mass,
                                          linspace(0, int(maxv), 25)))
        processes.append(t)
        t.start()
        if (i + 1) % 8 == 0:
            for each in processes:
                each.join()
            processes = []
    for each in processes:
        each.join()

    paras = {}
    allfiles = os.listdir("pickle")
    for each in allfiles:
        mass = int(each.replace("fitvalues", "").replace(".pickle", ""))
        with open("pickle/" + each, 'rb') as f:
            pvalues = pickle.load(f)
            paras[mass] = pvalues
    with open('fitvalues.pickle', 'wb') as f:
        pickle.dump(paras, f)
コード例 #36
0
def _create_entity_connection_matrix(
    df_coordinates: pd.DataFrame,
    starts: List[Coordinate],
    ends: List[Coordinate],
    aquifer_starts: List[Coordinate],
    aquifer_ends: List[Coordinate],
    max_distance_fraction: float,
    max_distance: float,
    concave_hull_list: Optional[List[np.ndarray]] = None,
    n_non_reservoir_evaluation: Optional[int] = 10,
) -> pd.DataFrame:
    """
    Converts the the coordinates given for starts and ends to the desired DataFrame format for simulation input.

    Args:
        df_coordinates: original DataFrame version of coordinates
        starts: List of coordinates for all the starting entities
        ends: List of coordinates of all the end entities
        aquifer_starts: List of coordinates for all aquifer starts
        aquifer_ends: List of coordinates of all aquifer ends
        max_distance_fraction: Fraction of longest connection distance to be removed
        max_distance: Maximum distance between nodes, removed otherwise
        concave_hull_list: List of boundingboxes per layer, i.e., numpy array with x, y, z min/max
            boundingboxes for each grid block
        n_non_reservoir_evaluation: Number of equally spaced points along a connection to check fornon-reservoir.

    Returns:
        Connection coordinate DataFrame on Flow desired format.

    """
    print("Creating entity connection DataFrame...", end="")
    columns = [
        "xstart",
        "ystart",
        "zstart",
        "xend",
        "yend",
        "zend",
        "start_entity",
        "end_entity",
    ]
    df_out = pd.DataFrame(columns=columns)

    for start, end in zip(starts, ends):
        str_start_entity = __get_entity_str(df_coordinates, start)
        str_end_entity = __get_entity_str(df_coordinates, end)

        if concave_hull_list is not None:
            tube_coordinates = linspace(
                start=start,
                stop=end,
                num=n_non_reservoir_evaluation,  # type: ignore
                endpoint=False,
                dtype=float,
                axis=1,
            ).T

            if not any((all(check_in_hull(concave_hull, tube_coordinates))
                        for concave_hull in concave_hull_list)):
                continue

        df_out = df_out.append(
            {
                "xstart": start[0],
                "ystart": start[1],
                "zstart": start[2],
                "xend": end[0],
                "yend": end[1],
                "zend": end[2],
                "start_entity": str_start_entity,
                "end_entity": str_end_entity,
            },
            ignore_index=True,
        )

    for start, end in zip(aquifer_starts, aquifer_ends):
        str_start_entity = __get_entity_str(df_coordinates, start)

        df_out = df_out.append(
            {
                "xstart": start[0],
                "ystart": start[1],
                "zstart": start[2],
                "xend": end[0],
                "yend": end[1],
                "zend": end[2],
                "start_entity": str_start_entity,
                "end_entity": "aquifer",
            },
            ignore_index=True,
        )

    df_out = _remove_long_connections(df_out, max_distance_fraction,
                                      max_distance)

    print("done.")
    return df_out
コード例 #37
0
i,j,k,l,=0,0,0,0        
        
print(i)

x= [2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015]
y = [485709,486722,475887,469311,453618,447977,436867,426885,392470,370021,351340,335504,306387,273781,238761]

p1= np.polyfit(x,y,1)
p2= np.polyfit(x,y,2)
p3= np.polyfit(x,y,3)
from scipy.interpolate import *



import matplotlib.pyplot as plt
xp = linspace(2000,2020,100)

fig,ax = plt.subplots()

plt.plot(xp,polyval(p1,xp),'r-')
plt.plot(xp,polyval(p2,xp),'m:')
plt.plot(xp,polyval(p3,xp),'b--')
ax.set_title("Prediction of Crime Data in Chicago")
ax.set_ylabel('Count')
ax.set_xlabel('Year')
plt.plot(x,y,'o')

#yfit = p1[0] * x + p1[1]
#yresid = y - yfit
#SSresid = sum(pow(yresid,2))
#SStotal = len(y) * np.var(y)
コード例 #38
0
ファイル: log_plot.py プロジェクト: TEAM-HRA/hra_suite
'''
Created on Nov 26, 2013

@author: jurek
'''

import matplotlib.pyplot as plt
import numpy as np
from numpy.core.function_base import linspace

x = linspace(10, 100, 90)
plt.plot(x, np.log(x))
plt.show()
コード例 #39
0
ファイル: log_plot.py プロジェクト: TEAM-HRA/hra_suite
'''
Created on Nov 26, 2013

@author: jurek
'''

import matplotlib.pyplot as plt
import numpy as np
from numpy.core.function_base import linspace


x = linspace(10, 100, 90)
plt.plot(x, np.log(x))
plt.show()
コード例 #40
0
#    Calculate speed (load and terrain)
#    30% is a guessstimate
loss = 0.3  #    Equals 30% loss
speed_load = speed * (1.0 - loss)
print ""
print " At 30% loss due to load, friction and terrain: " + str(speed_load) + "m/s"

#    Plot down sampled data and slice
print ""
print " Plotting ..."

plot.figure()
plot.title("Full waveform (down sampled from 8kHz to 1kHz)")
plot.xlabel("Time [min]")
plot.ylabel("Amplitude")
n = linspace(0, len(wData) - 1, len(wData))[::8]
plot.plot((n / wRate) / 60, wDataDownSampled)

plot.figure()
plot.title("Time slice of full waveform")
plot.xlabel("Time [s]")
plot.ylabel("Amplitude")
n = linspace(32000, 71999, len(wDataSlice))
plot.plot(n / wRate, wDataSlice)

#    Generate normal distribution with parameters speed and uncertainty
plot.figure()
plot.title("Normal distribution of speed with no load applied")
plot.xlabel("Speed [m/s]")
plot.ylabel("Probability density")
x = linspace(speed - 4 * uncertainty, speed + 4 * uncertainty, 1000)
コード例 #41
0
 def test_linespace_method(self):
     a = linspace(0,2,9) # array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ,  1.25,  1.5 ,  1.75,  2.  ])
     x = linspace(0, 2*pi, 100)
     f = sin(x)
     self.assertEqual(len(a), 9)
コード例 #42
0
ファイル: plot_fill_stage.py プロジェクト: orenlivne/ober
@author: Oren Livne <*****@*****.**>
============================================================
'''
import impute as im, matplotlib.pyplot as P, numpy as np, os
from numpy.core.function_base import linspace

P.figure(1)
P.clf()
P.hold(True)

p = im.hutt('hutt.phased.npz')
d5 = im.plots.plot_fill_fraction(p, color='b', label='Stage 5')

p = im.hutt('hutt.stage6.npz')
d = im.plots.plot_fill_fraction(p, color='r', label='Stage 6')

zoom = 0.96
ticks = 10
min_y = 0.95 * min(d[:, 1][0], d5[:, 1][0])
max_x = np.where(d[:, 1] > zoom)[0][0]
P.xlim([0, max_x + 1])
P.ylim([min_y, 1.0])
yticks = linspace(min_y, 1.0, ticks)
P.yticks(yticks, ['%.3f' % (t,) for t in yticks])

P.title('Hutterites Phasing Coverage, Chromosome 22')
P.legend(loc='lower right', prop={'size': 12})
P.show()

P.savefig(os.environ['OBER'] + '/doc/phasing/fill.png')
コード例 #43
0
ファイル: test01.py プロジェクト: Tony1886/python_workplace
# coding=gbk
# coding£ºutf-8
'''

 @Created on 2018Äê1ÔÂ26ÈÕ ÏÂÎç2:43:08
 @author: Administrator
'''
from myFunc import mfft, mifft
from math import *
from numpy import *
# import numpy as np
from matplotlib import *
import matplotlib.pyplot as plt
from numpy.dual import fft
from numpy.fft.helper import fftshift
from numpy.core.function_base import linspace

x = linspace(-pi, pi, 100)
print(type(x))
print(shape(x))
y = random.random(size=(1, 10))
print(type(y))
print(type(shape(y)))
print(type(shape(y)))
f = sin(x)
F = fftshift(fft(f))
#F = mfft(f)
plt.subplot(121)
plt.plot(abs(F))
plt.show()
コード例 #44
0
ファイル: Test01.py プロジェクト: Tony1886/python_workplace
# y1=sin(x)
# y2=cos(x)
# plt.plot(x,y1,'b.',x,y2,'r-')
# plt.show()

# import sys,random
# def compute(n):
#     i=0;s=0
#     while i<=n:
#         s+=random.random()
#         i+=1
#     return s/n
# n=500000
# print('average of %d random number is %g'%(n,compute(n)))

x = linspace(-10, 10, 1000)
y = x
[X, Y] = meshgrid(x, y)
w = 2
Gauss = exp(-(X**2 + Y**2) / pow(w, 2))
# plt.subplot(121)
# plt.imshow(Gauss)
# plt.subplot(122)
D = 2
y1 = exp(-x**2 / D**2)
plt.plot(x, y1)
# y2=zeros((1,1000))
# y2[where(abs(x)<=D)]=1
# plt.plot(x,y2,'r')
plt.show()
コード例 #45
0
 def test_upcasting_from_float_complex(self):
     b = linspace(0, pi, 3)
     c = exp(b*1j)
     self.assertEqual(c.dtype.name, 'complex128')
コード例 #46
0
 def test_upcasting_from_int_float(self):
     a = ones(3,dtype='int32')
     b = linspace(0, pi, 3)
     c = a+b
     self.assertEqual(type(c), type(b))
コード例 #47
0
#!/usr/bin/env python
'''
============================================================
Plot our HMM IBD posterior probabilities for model cases. 

Created on December 19, 2012
@author: Oren Livne <*****@*****.**>
============================================================
'''

import matplotlib.pyplot as P, os, numpy as np
from numpy.core.function_base import linspace
from impute.dev import ibd_single

N = 50
p = linspace(0, 1, N) + 1e-15
q = 1 - p
colors = ['b', 'g', 'r', 'm', 'k']


def plot_shared_allele_inflation(f):
    '''Plot the phased-phased IBD posterior probability change when we use shared allele frequencies.'''
    P.clf()
    for f in [0.1, 0.5, 0.9]:
        OR = f / (1 - f)
        ibd1 = 1 / (1 + p / OR)
        ibd2 = 1 / (1 + (p**2 + q**2) / OR)
        P.plot(p, ibd1 / ibd2, label='$f=%.1f,\, OR=%.1f$' % (f, OR))
    P.grid(True)
    P.xlim([0, 1])
    P.ylim([0, 2])
コード例 #48
0
ファイル: results_file.py プロジェクト: spacether/pycalculix
    def nplot(self, field, fname='', display=True, levels=21, gradient=False,
              gmult=1.0, max_val=None, min_val=None, title=''):
        """Plots nodal results.

        Args:
            field (str): results item to plot, examples: 'ux', 'ey', 'Seqv'
            fname (str): prefix of png file name, if writing an image
            display (bool): True = interactively show the plot
            levels (int): number of levels to use in the colorbar
            gradient (bool): True = results plotted with gradient
                False = results plotted with filled areas
            gmult (int): geometric multiplier on displacement of nodes
                displayed_node_loc = model_node_loc + gmult*node_displacement
            max_val (float or None): max value in the colorbar

                - None: max from selected data used
                - float: use the passed float
            min_val (float): min value in the colorbar

                - None: min from selected data used
                - float: use the passed float
            title (str): third line in the plot title
        """
        # store the selected nodes and elements
        sel = {}
        sel['nodes'] = self.__problem.fea.view.nodes
        sel['elements'] = self.__problem.fea.view.elements
        sel['faces'] = self.__problem.fea.view.faces

        # sort nodes low to high so index is correct
        # we have index to id below so showing subsets works
        sel['nodes'] = list(sel['nodes'])
        sel['nodes'] = sorted(sel['nodes'], key=lambda k: k.id)

        # store results at nodes
        axials = []
        radials = []
        zvals = []
        id_to_ind = {}
        for node in sel['nodes']:
            id_to_ind[node.id] = len(axials)
            axi = node.y + gmult*self.__results[self.__time]['node'][node.id]['uy']
            rad = node.x + gmult*self.__results[self.__time]['node'][node.id]['ux']
            axials.append(axi)
            radials.append(rad)
            zvals.append(self.__results[self.__time]['node'][node.id][field])

        # make a list of triangles, given by indices, looping anticlockwise
        triangles = []
        mylist = []
        if len(sel['elements']) > 0:
            mylist = sel['elements']
        elif len(sel['faces']) > 0:
            mylist = sel['faces']
        for element in mylist:
            tris = element.get_tris() # list of triangle nodes
            for tri in tris:
                for ind, nid in enumerate(tri):
                    tri[ind] = id_to_ind[nid]     # convert id to index
            triangles += tris

        # check to see if selected nodes and elements are
        # in the parent model's nodes and elements
        fig = plt.figure()
        ax_ = fig.add_subplot(111)

        # need to set tick list here
        vmin = min(zvals)
        vmax = max(zvals)
        stop_plot = False
        if max_val != None and min_val == None:
            if max_val < vmin:
                stop_plot = True
                print('Error:')
                print(' Only max was passed but it is < the data min!')
                print(' Pass a max_val that is > the data min of %f' % vmin)
            else:
                vmax = max_val
        elif min_val != None and max_val == None:
            if min_val > vmax:
                stop_plot = True
                print('Error:')
                print(' Only min was passed but it is > the data max!')
                print(' Pass a min_val that is < the data max of %f' % vmax)
            else:
                vmin = min_val
        elif max_val != None and min_val != None:
            if max_val < min_val:
                stop_plot = True
                print('Error:')
                print(' Min and max passed, but min > max!')
                print(' Pass a min_val that is < max_val')
            else:
                vmax = max_val
                vmin = min_val
        # exit if stop plot flag is on
        if stop_plot:
            return None

        tick_list = [vmin]
        if vmax != vmin:
            # we have a range of values we're plotting
            tick_list = linspace(vmin, vmax, levels+1)

        # plot using a gradient(shaded) or levels
        # code required for the colorbar, needs to go before plotting for colormap
        cnorm = colors.Normalize(vmin=vmin, vmax=vmax)
        cmap = colors.ListedColormap(['b', 'b']) # default to plot one val
        if vmax != vmin:
            # we have a range of values we're plotting
            if gradient:
                cmap = plt.get_cmap(CMAP)
            else:
                cmap = plt.get_cmap('jet', levels)
        cmap.set_under('0.3', 0.8)
        cmap.set_over('0.7', 0.8)
        if gradient or len(tick_list) == 1:
            # This one is shaded
            plt.tripcolor(axials, radials, triangles, zvals, shading='gouraud',
                          cmap=cmap, norm=cnorm)
        else:
            # this one is not shaded
            plt.tricontourf(axials, radials, triangles, zvals, levels=tick_list,
                            cmap=cmap, norm=cnorm, extend='both')

        scalarmap = cmx.ScalarMappable(norm=cnorm, cmap=cmap)
        scalarmap.set_array([])
        cbar = plt.colorbar(scalarmap, orientation='vertical', ticks=tick_list)

        scibool = False
        if field[0] == 'e':
            # strain plotting, use scientific numbering
            scibool = True
        met_max = self.__metric_num(max(zvals), sci=scibool)
        met_min = self.__metric_num(min(zvals), sci=scibool)
        label = 'Max: %s\nMin: %s' % (met_max, met_min)
        tick_list = [self.__metric_num(tick, sci=scibool) for tick in tick_list]
        cbar.ax.set_yticklabels(tick_list)
        cbar.ax.set_xlabel(label, labelpad=10, x=0, ha='left')
        cbar.ax.xaxis.set_label_position('top')

        # set the horizontal and vertical axes
        base_classes.plot_set_bounds(plt, axials, radials)

        # set units
        alist = self.__problem.fea.get_units(field, 'dist', 'time')
        [f_unit, d_unit, t_unit] = alist

        # set plot axes
        plot_title = ('Node %s%s\nTime=%f%s' %
                      (field, f_unit, self.__time, t_unit))
        if title != '':
            plot_title += '\n%s' % title
        plt.title(plot_title)
        plt.xlabel('axial, y'+d_unit)
        plt.ylabel('radial, x'+d_unit)
        ax_.set_aspect('equal')
        if gmult != 1:
            ax_.xaxis.set_ticklabels([])
            ax_.yaxis.set_ticklabels([])
        base_classes.plot_finish(plt, fname, display)
コード例 #49
0
ファイル: task.py プロジェクト: studentArtemkin/CT_MM
def measure_time():
    #N
    dim = 1
    NofThreads = 5
    G = 6.67408 * numpy.power(10.0, -11)
    t = linspace(0, 10, 101)
    time1 = [0, 0, 0]
    time2 = [0, 0, 0]
    time3 = [0, 0, 0]
    time4 = [0, 0, 0]
    time5 = [0, 0, 0]
    myRange = [100, 200, 400]
    for i, N in enumerate(myRange):
        data = formData(N, dim)
        for j in range(3):
            tmp_time = time.time()
            solve1(data, N, dim, G, t)
            time1[i] += time.time() - tmp_time
        for j in range(3):
            tmp_time = time.time()
            solve2(data, N, dim, NofThreads, G, t)
            time2[i] += time.time() - tmp_time
        for j in range(3):
            tmp_time = time.time()
            solve3(data, N, dim, NofThreads, G, t)
            time3[i] += time.time() - tmp_time
        for j in range(3):
            tmp_time = time.time()
            Verlet1.solve4(data, N, dim, G, t)
            time4[i] += time.time() - tmp_time
        for j in range(3):
            tmp_time = time.time()
            solve5(data, N, dim, G, t)
            time5[i] += time.time() - tmp_time
    for i in range(3):
        time1[i] /= 3
        time2[i] /= 3
        time3[i] /= 3
        time4[i] /= 3
        time5[i] /= 3
    plt.subplot(1, 3, 1)
    plt.plot(myRange, time1, label="default")
    plt.plot(myRange, time2, label="threading")
    plt.plot(myRange, time3, label="multiprocessing")
    plt.plot(myRange, time4, label="cython")
    plt.plot(myRange, time5, label="CUDA")
    plt.legend()
    plt.subplot(1, 3, 2)
    for i in range(3):
        time2[i] = time1[i] / time2[i]
        time3[i] = time1[i] / time3[i]
        time4[i] = time1[i] / time4[i]
        time5[i] = time1[i] / time5[i]
    plt.plot(myRange, time2, label="threading")
    plt.plot(myRange, time3, label="multiprocessing")
    plt.plot(myRange, time4, label="cython")
    plt.plot(myRange, time5, label="CUDA")
    plt.legend()
    plt.subplot(1, 3, 3)
    plt.plot(myRange, time2, label="threading")
    plt.plot(myRange, time3, label="multiprocessing")
    plt.plot(myRange, time4, label="cython")
    plt.legend()
    plt.show()
コード例 #50
0
# python program to create an array with 5 equal points using linespace() method

'''
Function Name    :  Create Array With 5 Equal Points Using linespace(). 
Function Date    :  28 Aug 2020
Function Author  :  Prasad Dangare
Input            :  Integer
Output           :  Float
'''

from numpy import*
from numpy.core.function_base import linspace

# divide 0 to 10 into 5 parts and take those points in the array

a = linspace(0, 10, 5)
print('a = ', a)
コード例 #51
0
ファイル: plot_ibd_posterior.py プロジェクト: orenlivne/ober
#!/usr/bin/env python
"""
============================================================
Plot our HMM IBD posterior probabilities for model cases. 

Created on December 19, 2012
@author: Oren Livne <*****@*****.**>
============================================================
"""

import matplotlib.pyplot as P, os, numpy as np
from numpy.core.function_base import linspace
from impute.dev import ibd_single

N = 50
p = linspace(0, 1, N) + 1e-15
q = 1 - p
colors = ["b", "g", "r", "m", "k"]


def plot_shared_allele_inflation(f):
    """Plot the phased-phased IBD posterior probability change when we use shared allele frequencies."""
    P.clf()
    for f in [0.1, 0.5, 0.9]:
        OR = f / (1 - f)
        ibd1 = 1 / (1 + p / OR)
        ibd2 = 1 / (1 + (p ** 2 + q ** 2) / OR)
        P.plot(p, ibd1 / ibd2, label="$f=%.1f,\, OR=%.1f$" % (f, OR))
    P.grid(True)
    P.xlim([0, 1])
    P.ylim([0, 2])