Пример #1
0
    def test_sliced_input(self):
        # cython code chokes on non C contiguous arrays
        xx = np.linspace(-1, 1, 100)

        x = xx[::5]
        y = xx[::5]

        make_interp_spline(x, y, k=1)
Пример #2
0
    def test_quadratic_deriv(self):
        der = [(1, 8.)]  # order, value: f'(x) = 8.

        # derivative at right-hand edge
        b = make_interp_spline(self.xx, self.yy, k=2, bc_type=(None, der))
        assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
        assert_allclose(b(self.xx[-1], 1), der[0][1], atol=1e-14, rtol=1e-14)

        # derivative at left-hand edge
        b = make_interp_spline(self.xx, self.yy, k=2, bc_type=(der, None))
        assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
        assert_allclose(b(self.xx[0], 1), der[0][1], atol=1e-14, rtol=1e-14)
Пример #3
0
    def test_cubic_deriv(self):
        k = 3

        # first derivatives at left & right edges:
        der_l, der_r = [(1, 3.)], [(1, 4.)]
        b = make_interp_spline(self.xx, self.yy, k, bc_type=(der_l, der_r))
        assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
        assert_allclose([b(self.xx[0], 1), b(self.xx[-1], 1)],
                        [der_l[0][1], der_r[0][1]], atol=1e-14, rtol=1e-14)

        # 'natural' cubic spline, zero out 2nd derivatives at the boundaries
        der_l, der_r = [(2, 0)], [(2, 0)]
        b = make_interp_spline(self.xx, self.yy, k, bc_type=(der_l, der_r))
        assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
Пример #4
0
    def test_shapes(self):
        np.random.seed(1234)
        k, n = 3, 22
        x = np.sort(np.random.random(size=n))
        y = np.random.random(size=(n, 5, 6, 7))

        b = make_interp_spline(x, y, k)
        assert_equal(b.c.shape, (n, 5, 6, 7))

        # now throw in some derivatives
        d_l = [(1, np.random.random((5, 6, 7)))]
        d_r = [(1, np.random.random((5, 6, 7)))]
        b = make_interp_spline(x, y, k, bc_type=(d_l, d_r))
        assert_equal(b.c.shape, (n + k - 1, 5, 6, 7))
Пример #5
0
    def test_complex(self):
        k = 3
        xx = self.xx
        yy = self.yy + 1.j*self.yy

        # first derivatives at left & right edges:
        der_l, der_r = [(1, 3.j)], [(1, 4.+2.j)]
        b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r))
        assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)
        assert_allclose([b(xx[0], 1), b(xx[-1], 1)],
                        [der_l[0][1], der_r[0][1]], atol=1e-14, rtol=1e-14)

        # also test zero and first order
        for k in (0, 1):
            b = make_interp_spline(xx, yy, k=k)
            assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)
Пример #6
0
    def test_int_xy(self):
        x = np.arange(10).astype(np.int_)
        y = np.arange(10).astype(np.int_)

        # cython chokes on "buffer type mismatch" (construction) or
        # "no matching signature found" (evaluation)
        for k in (0, 1, 2, 3):
            b = make_interp_spline(x, y, k=k)
            b(x)
Пример #7
0
    def test_multiple_rhs(self):
        yy = np.c_[np.sin(self.xx), np.cos(self.xx)]
        der_l = [(1, [1., 2.])]
        der_r = [(1, [3., 4.])]

        b = make_interp_spline(self.xx, yy, k=3, bc_type=(der_l, der_r))
        assert_allclose(b(self.xx), yy, atol=1e-14, rtol=1e-14)
        assert_allclose(b(self.xx[0], 1), der_l[0][1], atol=1e-14, rtol=1e-14)
        assert_allclose(b(self.xx[-1], 1), der_r[0][1], atol=1e-14, rtol=1e-14)
Пример #8
0
    def test_integrate_ppoly(self):
        # test .integrate method to be consistent with PPoly.integrate
        x = [0, 1, 2, 3, 4]
        b = make_interp_spline(x, x)
        b.extrapolate = 'periodic'
        p = PPoly.from_spline(b)

        for x0, x1 in [(-5, 0.5), (0.5, 5), (-4, 13)]:
            assert_allclose(b.integrate(x0, x1),
                            p.integrate(x0, x1))
Пример #9
0
    def test_full_matrix(self):
        np.random.seed(1234)
        k, n = 3, 7
        x = np.sort(np.random.random(size=n))
        y = np.random.random(size=n)
        t = _not_a_knot(x, k)

        b = make_interp_spline(x, y, k, t)
        cf = make_interp_full_matr(x, y, t, k)
        assert_allclose(b.c, cf, atol=1e-14, rtol=1e-14)
Пример #10
0
 def test_minimum_points_and_deriv(self):
     # interpolation of f(x) = x**3 between 0 and 1. f'(x) = 3 * xx**2 and 
     # f'(0) = 0, f'(1) = 3.
     k = 3
     x = [0., 1.]
     y = [0., 1.]
     b = make_interp_spline(x, y, k, bc_type=([(1, 0.)], [(1, 3.)]))
     
     xx = np.linspace(0., 1.)
     yy = xx**3
     assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)
Пример #11
0
    def setup_method(self):
        xx = np.linspace(0, 4.*np.pi, 41)
        yy = np.cos(xx)
        b = make_interp_spline(xx, yy)
        self.tck = (b.t, b.c, b.k)
        self.xx, self.yy, self.b = xx, yy, b

        self.xnew = np.linspace(0, 4.*np.pi, 21)

        c2 = np.c_[b.c, b.c, b.c]
        self.c2 = np.dstack((c2, c2))
        self.b2 = BSpline(b.t, self.c2, b.k)
Пример #12
0
 def test_quintic_derivs(self):
     k, n = 5, 7
     x = np.arange(n).astype(np.float_)
     y = np.sin(x)
     der_l = [(1, -12.), (2, 1)]
     der_r = [(1, 8.), (2, 3.)]
     b = make_interp_spline(x, y, k=k, bc_type=(der_l, der_r))
     assert_allclose(b(x), y, atol=1e-14, rtol=1e-14)
     assert_allclose([b(x[0], 1), b(x[0], 2)],
                     [val for (nu, val) in der_l])
     assert_allclose([b(x[-1], 1), b(x[-1], 2)],
                     [val for (nu, val) in der_r])
Пример #13
0
    def test_deriv_spec(self):
        # If one of the derivatives is omitted, the spline definition is 
        # incomplete.
        x = y = [1.0, 2, 3, 4, 5, 6]

        with assert_raises(ValueError):
            make_interp_spline(x, y, bc_type=([(1, 0.)], None))

        with assert_raises(ValueError):
            make_interp_spline(x, y, bc_type=(1, 0.))

        with assert_raises(ValueError):
            make_interp_spline(x, y, bc_type=[(1, 0.)])

        with assert_raises(ValueError):
            make_interp_spline(x, y, bc_type=42)

        # CubicSpline expects`bc_type=(left_pair, right_pair)`, while
        # here we expect `bc_type=(iterable, iterable)`.
        l, r = (1, 0.0), (1, 0.0)
        with assert_raises(ValueError):
            make_interp_spline(x, y, bc_type=(l, r))
Пример #14
0
    def test_cubic_deriv_unstable(self):
        # 1st and 2nd derivative at x[0], no derivative information at x[-1]
        # The problem is not that it fails [who would use this anyway],
        # the problem is that it fails *silently*, and I've no idea
        # how to detect this sort of instability.
        # In this particular case: it's OK for len(t) < 20, goes haywire
        # at larger `len(t)`.
        k = 3
        t = _augknt(self.xx, k)

        der_l = [(1, 3.), (2, 4.)]
        b = make_interp_spline(self.xx, self.yy, k, t, bc_type=(der_l, None))
        assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
Пример #15
0
    def test_deriv_spec(self):
        # If one of the derivatives is omitted, the spline definition is 
        # incomplete.
        x = y = [1.0, 2, 3, 4, 5, 6]

        with assert_raises(ValueError):
            make_interp_spline(x, y, bc_type=([(1, 0.)], None))

        with assert_raises(ValueError):
            make_interp_spline(x, y, bc_type=(1, 0.))

        with assert_raises(ValueError):
            make_interp_spline(x, y, bc_type=[(1, 0.)])

        with assert_raises(ValueError):
            make_interp_spline(x, y, bc_type=42)

        # CubicSpline expects`bc_type=(left_pair, right_pair)`, while
        # here we expect `bc_type=(iterable, iterable)`.
        l, r = (1, 0.0), (1, 0.0)
        with assert_raises(ValueError):
            make_interp_spline(x, y, bc_type=(l, r))
Пример #16
0
    def test_cubic_deriv_unstable(self):
        # 1st and 2nd derivative at x[0], no derivative information at x[-1]
        # The problem is not that it fails [who would use this anyway],
        # the problem is that it fails *silently*, and I've no idea
        # how to detect this sort of instability.
        # In this particular case: it's OK for len(t) < 20, goes haywire
        # at larger `len(t)`.
        k = 3
        t = _augknt(self.xx, k)

        der_l = [(1, 3.), (2, 4.)]
        b = make_interp_spline(self.xx, self.yy, k, t, bc_type=(der_l, None))
        assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
    def apply_torques(self, system, time: np.float = 0.0):

        # Check if RL algorithm changed the points we fit the spline at this time step
        # if points_array changed create a new spline. Using this approach we don't create a
        # spline every time step.
        # Make sure that first and last point y values are zero. Because we cannot generate a
        # torque at first and last nodes.
        # print('torque',self.max_rate_of_change_of_activation)

        if (
            not np.array_equal(self.points_cached[1, 1:-1], self.points_array(time))
            or self.initial_call_flag == 0
        ):
            self.initial_call_flag = 1

            # Apply filter to the activation signal, to prevent drastic changes in activation signal.
            self.filter_activation(
                self.points_cached[1, 1:-1],
                np.array((self.points_array(time))),
                self.max_rate_of_change_of_activation,
            )

            self.my_spline = make_interp_spline(
                self.points_cached[0], self.points_cached[1]
            )
            cumulative_lengths = np.cumsum(system.lengths)

            # Compute the muscle torque magnitude from the beta spline.
            self.torque_magnitude_cache = self.muscle_torque_scale * self.my_spline(
                cumulative_lengths
            )

        self.compute_muscle_torques(
            self.torque_magnitude_cache, self.direction, system.external_torques,
        )

        if self.counter % self.step_skip == 0:
            if self.torque_profile_recorder is not None:
                self.torque_profile_recorder["time"].append(time)

                self.torque_profile_recorder["torque_mag"].append(
                    self.torque_magnitude_cache.copy()
                )
                self.torque_profile_recorder["torque"].append(
                    system.external_torques.copy()
                )
                self.torque_profile_recorder["element_position"].append(
                    np.cumsum(system.lengths)
                )

        self.counter += 1
Пример #18
0
def test_pid(P = 0.2, I= 0.0, D = 0.0, L = 100):
    """ test-PID 
        for i in range(1, END):
            pid.update(feedback) 
            output = pid.output 
            if pid.Setpoint > 0: 
                feedback += (output - (1/i))
            if i > 9:
                pid.Setpoint = 1 
            time.sleep(0.02 )
    L: end time 
    """

    pid = basic_pid.PID(P,I,D)
     
    pid.SetPoint = 0.0 
    pid.setSampleTime(0.01) 

    END = L 
    feedback = 0 
    feedback_list = [] 
    time_list = [] 
    setpoint_list = [] 
    for i in range(1, END):
        pid.update(feedback)
        output = pid.output
        if pid.SetPoint > 0:
            feedback += (output - 1/i) 
        if i > 9:
            pid.SetPoint = 1 
        time.sleep(0.02) 

        feedback_list.append(feedback) 
        setpoint_list.append(pid.SetPoint) 
        time_list.append(i) 

    time_sm = np.array(time_list) 
    time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300)
    helper = make_interp_spline(time_list,feedback_list)
    feedback_smooth = helper(time_smooth) 

    plt.plot(time_smooth, feedback_smooth) 
    plt.plot(time_list,setpoint_list) 
    plt.xlim((0,L))
    # plt.ylim((min(feedback_list),max(feedback_list)))
    plt.xlabel('time(s)')
    plt.ylabel('PID(PV)')
    plt.title('TEST PID')
    
    plt.grid(True) 
    plt.show() 
Пример #19
0
def create_graph(
        data,
        usercolor,
        title=None,
        dimensions=(6, 3),
        draw=False,
        background_color="#2f3136",
):
    plt.rcParams["figure.figsize"] = [dimensions[0], dimensions[1]]
    T = np.array(list(range(0, len(data))))
    xnew = np.linspace(T.min(), T.max(), 240)
    spl = make_interp_spline(T, data, k=3)
    power_smooth = spl(xnew)

    # remove under 0
    power = []
    for x in power_smooth:
        if x < 0:
            x = 0
        power.append(x)

    power_smooth = np.array(power)

    fig = plt.figure()
    fig.patch.set_facecolor(background_color)
    if title is not None:
        fig.suptitle(title, color="white")
    plt.autoscale(tight=True)
    plt.plot(xnew, power_smooth, color=usercolor)
    ax = plt.gca()
    loc = plticker.MultipleLocator(base=1.0)
    ax.xaxis.set_major_locator(loc)
    ax.set_facecolor(background_color)
    ax.set_xlabel("Hour (UTC)")
    # ax.set_ylabel('XP gain')

    ax.spines["bottom"].set_color("white")
    ax.spines["left"].set_color("white")
    ax.xaxis.label.set_color("white")
    ax.yaxis.label.set_color("white")
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)
    ax.tick_params(axis="x", colors="white")
    ax.tick_params(axis="y", colors="white")
    plt.fill_between(xnew, power_smooth, color=usercolor, alpha=0.2)
    if draw:
        plt.show()
    plt.savefig("downloads/graph.png",
                facecolor=background_color,
                bbox_inches="tight")
    plt.close()
Пример #20
0
def scatter(cost, term, titel):
    x = list(range(1, 10))
    plt.scatter(x, cost)
    plt.yscale('linear')
    xnew = np.linspace(min(x), max(x), 300)
    spl = make_interp_spline(x, cost, k=3)  #BSpline object
    power_smooth = spl(xnew)
    plt.plot(xnew, power_smooth, color='orange')
    plt.title('Distribution of cost per worker:searcher ants')
    plt.xlabel('Amount searchers (total=10)')
    plt.legend(labels=['Population ' + term])  #,'Population ' + term2])
    plt.ylabel('Cost')
    plt.savefig(titel)
    plt.clf()
Пример #21
0
 def cubic_interpolation(self, input_list, length, show_spline=False):
     # get scale info from output list.
     input_array = np.array(input_list)
     scale = int(length / (len(input_list) - 1))
     x = np.array([i * scale for i in range(len(input_list))])
     b_n = interpolate.make_interp_spline(x, input_array)
     output_list = []
     for ii in range(length):
         output_list.append(int(b_n(ii)))
     if(show_spline==True):
         plt.plot([i * scale for i in range(len(input_list))], input_list)
         plt.plot(range(len(output_list)), output_list)
         plt.show()
     return output_list
Пример #22
0
def _reavg(X0, Y0, X1, k, axis):
    """cumsum, interpolate, and diff.
    """

    Y0_cum = Y0.cumsum(axis=axis)
    if axis == -1: axis += Y0.ndim
    _Y0_cum = numpy.zeros(Y0.shape[:axis] + (1,) + Y0.shape[axis+1:])
    Y0_cum = numpy.concatenate((_Y0_cum, Y0_cum), axis=axis)

    Y1_cum = make_interp_spline(X0, Y0_cum, k=k, axis=axis)(X1)

    Y1 = numpy.diff(Y1_cum, axis=axis)

    return Y1
Пример #23
0
def animate(i):
    global U_prev, U_curr, F, surf, ax

    for j in range(i * draw_every, (i + 1) * draw_every):
        F = get_F(f, j * dt, points)
        # Calculate the left hand side
        B = get_rhs(dt, S, T, U_curr, U_prev, F)

        # move one step
        U_prev = U_curr.copy()
        U_curr = spsolve(A, B)

    # Update the plot
    # Remove elements
    surf.remove()
    # cb.remove()

    # # Get the new colormap levels
    # mid = 0 #(U_curr.min() + U_curr.max())/2
    # m = mid - max(abs(U_curr.min() - mid),abs(U_curr.max() - mid))
    # M = mid + max(abs(U_curr.min() - mid),abs(U_curr.max() - mid))
    # clev = np.linspace(m,M,49)

    # Get the values along the z-plane
    U = np.array([
        np.mean(U_curr[mesh.simplices[mesh.find_simplex([r, z])]]) for r in RR
    ])
    interp = interpolate.make_interp_spline(RR, U)
    U = interp(RR)

    Ff = lambda x, y: interp((x**2 + y**2)**0.5)
    Z = Ff(X, Y)

    # Plot the 3D version
    surf = ax.plot_surface(X,
                           Y,
                           Z,
                           rstride=1,
                           cstride=1,
                           cmap=cm.coolwarm,
                           norm=colors.CenteredNorm(),
                           edgecolor='none')
    # surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap=cm.coolwarm, edgecolor='none')
    # cb = fig.colorbar(surf)

    ax.set_title(r'Wave in $\phi$-slice t=%.2e' % (i * dt))

    progress1.update(i)

    return surf
def drawhourtrendgram(pivot_data, lblname):
    plt.figure(figsize=(5, 2.5))
    plt.subplots_adjust(0.11, 0.18, 0.98, 0.98, 0.2, 0.32)
    x = pivot_data.iloc[:, 0]
    x_new = np.linspace(x.min(), x.max(), 300)
    for i in range(len(lblname)):
        y = pivot_data.iloc[:, i + 1]
        y_smooth = make_interp_spline(x, y)(x_new)
        plt.plot(x_new, y_smooth, linewidth=1, label=lblname[i])
    plt.xlabel('Hour', fontdict=fontdict)
    plt.ylabel('Miles', fontdict=fontdict)
    plt.xticks(fontproperties='Times New Roman', size=10)
    plt.yticks(fontproperties='Times New Roman', size=10)
    plt.legend(prop=fontdict, loc='upper right')
Пример #25
0
def test_pid(P=0.2, I=0.1, D=0.0, M=10, L=100):

    pid = PID.PID(P, I, D, M)

    pid.point = 0.0
    pid.sample_time = 0.01

    END = L
    feedback = 0

    feedback_list = []
    time_list = []
    setpoint_list = []

    for i in range(1, END):
        output = pid.update(feedback)
        if not pid.point == 0:
            feedback += simulator.func3(
                output - (1 / i))  #+ random.uniform(-0.01, 0.01)
        #print feedback

        if i > 9:
            pid.point = 1

        time.sleep(0.02)

        feedback_list.append(feedback)
        setpoint_list.append(pid.point)
        time_list.append(i)

    time_sm = np.array(time_list)
    time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300)

    # feedback_smooth = spline(time_list, feedback_list, time_smooth)
    # Using make_interp_spline to create BSpline
    helper_x3 = make_interp_spline(time_list, feedback_list)
    feedback_smooth = helper_x3(time_smooth)

    plt.plot(time_smooth, feedback_smooth)
    plt.plot(time_list, setpoint_list)
    plt.xlim((0, L))
    plt.ylim((min(feedback_list) - 0.5, max(feedback_list) + 0.5))
    plt.xlabel('time (s)')
    plt.ylabel('PID (PV)')
    plt.title('TEST PID')

    plt.ylim((1 - 0.5, 1 + 0.5))

    plt.grid(True)
    plt.show()
Пример #26
0
def spline_it(data,n):
    splx = np.array([])
    for i in np.arange(n):
        t  = data[i][0]
        IA = data[i][1]
        U2 = data[i][2]

        U2new = np.linspace(U2[0],U2[-1],100)
        spl = make_interp_spline(U2,IA,k=5)

        pair = np.array([spl,U2new])
        splx = np.hstack((splx,pair))

    return splx;
Пример #27
0
def savechart(df, sunrise, sunset):
    myFmt = mdates.DateFormatter('%I %p')
    x_min = east.localize(
        datetime.combine(date.today(), time(sunrise.hour - 2, sunrise.minute)))
    x_max = east.localize(
        datetime.combine(date.today(), time(sunset.hour + 2, sunset.minute)))

    y_max = (df['Pred(Ft)'].max())
    y_min = (df['Pred(Ft)'].min())

    fig = plt.figure()  # an empty figure with no axes
    fig.suptitle(
        'No axes on this figure')  # Add a title so we know which it is

    fig, ax = plt.subplots(1, 1)

    ax.set_xlim([x_min, x_max])
    ax.set_ylim([y_min, y_max])

    x = df['Timestamp']
    y = df['Pred(Ft)']

    xnew = np.linspace(
        pd.Timestamp(x_min).value,
        pd.Timestamp(x_max).value,
        90)  #300 represents number of points to make between T.min and T.max
    xnew = pd.to_datetime(xnew)
    spl = make_interp_spline(x, y, k=3)  #BSpline object
    x_wave = spl(xnew)
    ax.plot(xnew, x_wave, markerfacecolor='dodgerblue', color='black')

    #set axis labels to time
    ax.xaxis.set_major_formatter(myFmt)
    ax.set_facecolor('ivory')
    ax.fill_between(xnew,
                    x_wave,
                    y2=y_min,
                    where=None,
                    interpolate=False,
                    facecolor='dodgerblue',
                    alpha=1,
                    zorder=10)
    ax.axvspan(x_min, sunrise, alpha=0.2, color='blue', zorder=15)
    ax.axvspan(x_max, sunset, alpha=0.2, color='blue', zorder=15)
    ax.set_title("Tide and Daylight Forecast: ")
    ax.set_yticklabels([])
    ax.set_yticks([])

    plt.savefig('tide_chart_new.png', bbox_inches='tight')
    return ()
Пример #28
0
def hourtrendgram(pivot_data, lblname):
    f = plt.figure(figsize=(2.6, 2.5))
    ax = plt.axes()
    plt.subplots_adjust(0.1, 0.17, 0.98, 0.98, 0.2, 0.2)
    x = pivot_data.iloc[:, 0]
    x_new = np.linspace(x.min(), x.max(), 300)
    for i in range(len(lblname)):
        y = pivot_data.iloc[:, i + 1]
        y_smooth = make_interp_spline(x, y)(x_new)
        plt.plot(x_new, y_smooth, color='k', linestyle=dict_linestyle[i], linewidth=1, label=lblname[i])
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    seticksandlegend('Hour/h', 'Miles/km', loc='upper right', ncol=2, frameon=False)
    savefig2tif(f, '小时趋势变化图.tif')
Пример #29
0
def figure3():
    xs = [a for a, b in cum]
    ys = [b / totalP for a, b in cum]
    xs_new = np.linspace(min(xs), max(xs), 300)
    ys_smooth = spy.make_interp_spline(xs, ys)
    ys_new = ys_smooth(xs_new)
    f = plt.figure(figsize=(5, 5))
    plt.gca().spines['right'].set_visible(False)
    plt.gca().spines['top'].set_visible(False)

    plt.plot(xs_new, ys_new, 'k')
    f.savefig(pdffile3, bbox_inches='tight')
    print("Scribeva:", pdffile3)
    plt.show()
Пример #30
0
    def test_knots_not_data_sites(self):
        # Knots need not coincide with the data sites.
        # use a quadratic spline, knots are at data averages,
        # two additional constraints are zero 2nd derivs at edges
        k = 2
        t = np.r_[(self.xx[0],)*(k+1),
                  (self.xx[1:] + self.xx[:-1]) / 2.,
                  (self.xx[-1],)*(k+1)]
        b = make_interp_spline(self.xx, self.yy, k, t,
                               bc_type=([(2, 0)], [(2, 0)]))

        assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
        assert_allclose([b(self.xx[0], 2), b(self.xx[-1], 2)], [0., 0.],
                atol=1e-14)
 def test_periodic_axis(self):
     n = self.xx.shape[0]
     np.random.seed(1234)
     x = np.random.random_sample(n) * 2 * np.pi
     x = np.sort(x)
     x[0] = 0.
     x[-1] = 2 * np.pi
     y = np.zeros((2, n))
     y[0] = np.sin(x)
     y[1] = np.cos(x)
     b = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1)
     for i in range(n):
         assert_allclose(b(x[i]), y[:, i], atol=1e-14)
     assert_allclose(b(x[0]), b(x[-1]), atol=1e-14)
Пример #32
0
Файл: ln.py Проект: sevilj/ln
def plot():
    x = ln(forward, backward)[0]
    y = ln(forward, backward)[1]
    plt.scatter(x, y, s=30)
    z = sorted(x.flatten())
    x_new = np.linspace(min(z), max(z), 15)
    a_BSpline = make_interp_spline(z, y, k=len(x) - 1)
    y_new = a_BSpline(x_new)
    plt.grid(True)
    plt.title("Water consumption")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.plot(x, y)
    plt.show()
Пример #33
0
    def test_knots_not_data_sites(self):
        # Knots need not coincide with the data sites.
        # use a quadratic spline, knots are at data averages,
        # two additional constraints are zero 2nd derivatives at edges
        k = 2
        t = np.r_[(self.xx[0],)*(k+1),
                  (self.xx[1:] + self.xx[:-1]) / 2.,
                  (self.xx[-1],)*(k+1)]
        b = make_interp_spline(self.xx, self.yy, k, t,
                               bc_type=([(2, 0)], [(2, 0)]))

        assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
        assert_allclose([b(self.xx[0], 2), b(self.xx[-1], 2)], [0., 0.],
                atol=1e-14)
Пример #34
0
def plot_confidence_interval(*args,
                             label=None,
                             q_inf=0.1,
                             q_sup=0.9,
                             alpha=.3,
                             smoothing=None,
                             dots=False):
    y_data = np.asarray(args[-1])
    if len(args) == 1:
        # We only have the data. We create x-axis values.
        x_data = np.arange(y_data.shape[0])
    else:
        x_data = np.asarray(args[0])

    avg = np.mean(y_data, axis=0)
    q10 = np.quantile(y_data, q_inf, axis=0)
    q90 = np.quantile(y_data, q_sup, axis=0)

    if smoothing is not None:
        x_plot = np.linspace(x_data.min(), x_data.max(),
                             x_data.shape[0] * smoothing)
        avg_plot = make_interp_spline(x_data, avg, k=2)(x_plot)
        q10_plot = make_interp_spline(x_data, q10, k=2)(x_plot)
        q90_plot = make_interp_spline(x_data, q90, k=2)(x_plot)
    else:
        x_plot = x_data
        avg_plot = avg
        q10_plot = q10
        q90_plot = q90

    line = plt.plot(x_plot, avg_plot, label=label)
    color = line[0].get_c()

    if dots:
        plt.scatter(x_data, avg, c=color)

    plt.fill_between(x_plot, q90_plot, q10_plot, color=color, alpha=alpha)
Пример #35
0
def test_pid(P=0.2, I=0.0, D=0.0, L=100):
    pid = PID(P, I, D)

    pid.SetPoint = 0.0
    pid.setSampleTime(0.01)

    END = L
    feedback = 0

    feedback_list = []
    time_list = []
    setpoint_list = []

    for i in range(1, END):
        pid.update(feedback)
        output = pid.output
        # print(output)
        if pid.SetPoint > 0:
            feedback += output  # (output - (1/i))控制系统的函数
        if 9 <= i <= 40:
            pid.SetPoint = 1
        elif i > 40:
            pid.SetPoint = 0.5

        time.sleep(0.01)

        feedback_list.append(feedback)
        setpoint_list.append(pid.SetPoint)
        time_list.append(i)

    time_sm = np.array(time_list)
    time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300)
    feedback_smooth = make_interp_spline(time_list, feedback_list)(time_smooth)

    plt.figure(figsize=(8, 8 * 0.618))

    plt.plot(time_smooth, feedback_smooth)
    plt.plot(time_list, setpoint_list)

    plt.xlabel("Time(s)")
    plt.ylabel("PID(PV)")
    plt.title("TEST-PID Kp={} Ki={} Kd={}".format(P, I, D))

    plt.grid(True)
    plt.savefig("PID-Kp={},Ki={},Kd={}.jpg".format(P, I, D))
    plt.savefig("PID-Kp={},Ki={},Kd={}.pdf".format(P, I, D))
    plt.close()

    return 0
Пример #36
0
def plot_func(plot_name, func):
    """
    It plots a single variable function.
    """
    
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    

    # Eliminate upper and right axes
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    
    x = [-2, -1.5, -1, 0, 1, 1.5, 2]
    y = [func(i) for i in x]
    
    # Creating smooth curve
    xnew = np.linspace(min(x), max(x), 300)
    spl = make_interp_spline(x, y, k=3)
    smooth_y = spl(xnew)
    
    plt.plot(xnew, smooth_y, color='black')
    
    # Plot constraint
    #plt.axvline(2, color='k', linestyle='dashed')
    
    # plot min point
    #plt.plot([0], [0], marker='o', color='k')
    
    # range of x and y axis
    x_range = ax.get_xlim()
    y_range = ax.get_ylim()

    plt.xticks(np.arange(int(x_range[0]), int(x_range[1]) + 1, step=1))
    plt.yticks(np.arange(0, int(y_range[1]) + 1, step=1))
    
    # axis major lines
    ax.xaxis.grid(which='major', linestyle='--')
    ax.yaxis.grid(which='major', linestyle='--')
    
    plt.ylabel(r'$f(x)$')
    plt.xlabel(r'$x$')
    
    # Set margin to zero to make y-axis connected to x-axis
    #plt.margins(0)
    plt.tight_layout() # To fix axis labels not shown completely in the fig
    plt.show()

    fig.savefig(join('./figs/', plot_name + '.png'), format='png', dpi=500)
Пример #37
0
def getRSSIGraphs():
    for x in range(11):
        if x % 2 == 0:
            # RSSI Values for Boxes + No Boxes
            noBoxRSSI = getRSSI('NoBoxData/noBox' + str(x) + '.csv')
            boxRSSI = getRSSI('BoxData/box' + str(x) + '.csv')
            # Scan values for Boxes + No Boxes
            noBoxScans = getIteration('NoBoxData/noBox' + str(x) + '.csv')
            boxScans = getIteration('BoxData/box' + str(x) + '.csv')
            # Range Limit
            plt.ylim(min(noBoxRSSI) - 20, max(noBoxRSSI) + 20)
            # Get first 50 scans
            plt.xlim(0, 51)
            # X scale
            plt.xticks(np.arange(0, 51, 2.0))
            # Axes Labels
            plt.xlabel('Scan Number')
            plt.ylabel('RSSI Value (dBm)')
            # Title
            plt.title(str(x) + " Meters RSSI Values")
            # Smoothen Graph
            xNoBoxNew = np.linspace(min(noBoxScans), max(noBoxScans), 600)
            xBoxNew = np.linspace(min(boxScans), max(boxScans), 600)
            spl = make_interp_spline(noBoxScans, noBoxRSSI, k=3)
            spl2 = make_interp_spline(boxScans, boxRSSI, k=3)
            newNoBox = spl(xNoBoxNew)
            newBox = spl2(xBoxNew)

            # Plot Graph
            plt.plot(xNoBoxNew, newNoBox, "-b", label="No BoxData")
            plt.plot(xBoxNew, newBox, "-r", label="Boxed")
            # Legend
            plt.legend(loc="upper right")
            # Save + close plot
            plt.savefig('RSSIGraphs/' + str(x) + "Meters")
            plt.close()
Пример #38
0
    def __init__(self):
        self.f = open('./media/test2.txt').read()
        self.f = open('./media/test2.txt').read()
        self.data = self.f[self.f.find('    -'):self.f.find('\n\n\n')].split('\n')[3:]
        self.all_data = []
        for line in self.data:
            if 'threshold' not in line:
                line = line.strip()
                self.all_data.append(list(map(float, re.split(r'\s+', line)[0:2])))
            else:
                break
        with open('./media/all_data.csv', 'wb') as f:
            np.savetxt(f, self.all_data, fmt='%.2e %.2f', delimiter=',')
        self.read_data = np.genfromtxt('./media/all_data.csv')
        x = list(x for x in range(self.read_data.shape[0]))
        y1 = [np.log10(x) for x in self.read_data[:, 0]]
        y2 = self.read_data[:, 1]
        self.xnew = np.linspace(min(x), max(x), 30)

        spl1 = make_interp_spline(x, y1, k=3)
        spl2 = make_interp_spline(x, y2, k=3)

        self.y1_new = spl1(self.xnew)
        self.y2_new = spl2(self.xnew)
Пример #39
0
def plotHoughTransform(data, t, smooth=True):
    _, ax = plt.subplots()
    for datum in data:
        x, y, *th = datum
        if smooth:
            new_t = linspace(t[0], t[-1], 100)
            a_spline = interpolate.make_interp_spline(t, th)
            new_th = a_spline(new_t)
            plt.plot(new_t, new_th, label="(" + str(x) + "," + str(y) + ")")
        else:
            plt.plot(t, th, label="(" + str(x) + "," + str(y) + ")")

    ax.set(xlabel="theta", ylabel="r value", title="HOUGH LINE CURVE")
    plt.legend(bbox_to_anchor=(1, 1), loc='upper left', borderaxespad=0.)
    plt.show()
Пример #40
0
def plot_quadratic(plot_name):
    """
    It plots a quadratic function
    """
    
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    
    #  move left y-axis to center
    ax.spines['left'].set_position('center')
    #ax.spines['bottom'].set_position('center')
    
    # Eliminate upper and right axes
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    
    x = [-3, -2, -1, 0, 1, 2, 3]
    y = [i**2 for i in x]
    
    # Creating smooth curve
    xnew = np.linspace(min(x), max(x), 300)
    spl = make_interp_spline(x, y, k=3)
    smooth_y = spl(xnew)
    
    plt.plot(xnew, smooth_y, color='black')
    
    # Plot constraint
    #plt.axvline(2, color='k', linestyle='dashed')
    
    # plot min point
    #plt.plot([0], [0], marker='o', color='k')
    
    # range of x and y axis
    x_range = ax.get_xlim()
    y_range = ax.get_ylim()

    plt.xticks(np.arange(int(x_range[0]), int(x_range[1]) + 1, step=1))
    plt.yticks(np.arange(int(y_range[0]) + 1, int(y_range[1]) + 1, step=1))
    
    # axis major lines
    ax.xaxis.grid(which='major', linestyle='--')
    ax.yaxis.grid(which='major', linestyle='--')
    
    # Set margin to zero to make y-axis connected to x-axis
    plt.margins(0)
    plt.show()

    fig.savefig(join('./figs/', plot_name + '.png'), format='png', dpi=500)
Пример #41
0
def paint4(list1, list2, title, filename):
    length = len(list1)
    length2 = len(list2)
    x = np.arange(0, length, 1)
    x2 = np.arange(0, length2, 1)
    # x2 *= int(max(length, length2) / length2)
    x2 *= 10

    y1 = list1
    y2 = list2
    x_new = np.linspace(x.min(), x.max(), 300)
    # x2_new = np.linspace(x2.min(), x2.max(), 300)
    y_smooth1 = make_interp_spline(x, y1)(x_new)
    # y_smooth2 = make_interp_spline(x2, y2)(x2_new)

    plt.title(title, fontsize='14')
    plt.xlabel("Time (h)", fontsize='14')
    plt.ylabel("Rate (numbers/min)", fontsize='14')

    plt.plot(x_new,
             y_smooth1,
             c='burlywood',
             label='Instantaneous rate',
             linewidth='2')
    plt.plot(x2,
             y2,
             c='green',
             label='Average rate',
             linewidth='2',
             marker="o",
             markersize=3)

    plt.xticks([
        0,
        int(length / 8),
        int(length / 4),
        int(3 * length / 8),
        int(2 * length / 4),
        int(5 * length / 8),
        int(3 * length / 4),
        int(7 * length / 8), length
    ], ["0:00", '', "6:00", '', "12:00", '', "18:00", '', "0:00"])
    plt.grid(axis='y')  # 添加网格
    # sns.despine()
    plt.tick_params(labelsize=12)  # 刻度字体大小13
    plt.legend(fontsize="13")
    plt.savefig(filename)
    plt.show()
Пример #42
0
def fit_plot(dataTrain, dataTest, K):
  # get w
  w, p_train, p_test, err_train, err_test = train_w(dataTrain, dataTest, K)

  # plot graph
  plt.scatter(dataTrain[0],dataTrain[1],20)
  x_new = np.linspace(np.amin(dataTrain[0]), np.amax(dataTrain[0]),1000)
  a_BSpline = interpolate.make_interp_spline(dataTrain[0,dataTrain[0,:].argsort()],p_train[dataTrain[0,:].argsort()])
  y_new = a_BSpline(x_new)
  plt.plot(x_new,y_new,color="red")
  plt.ylim(np.amin(dataTrain[1])-5, np.amax(dataTrain[1])+5)
  plt.show()



  return w, err_train, err_test
Пример #43
0
    def test_minimum_points_and_deriv(self):
        # interpolation of f(x) = x**3 between 0 and 1. f'(x) = 3 * xx**2 and
        # f'(0) = 0, f'(1) = 3.
        k = 3
        x = [0., 1.]
        y = [0., 1.]
        b = make_interp_spline(x, y, k, bc_type=([(1, 0.)], [(1, 3.)]))

        xx = np.linspace(0., 1.)
        yy = xx**3
        assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)

        # If one of the derivatives is omitted, the spline definition is
        # incomplete:
        assert_raises(ValueError, make_interp_spline, x, y, k,
                      **dict(bc_type=([(1, 0.)], None)))
Пример #44
0
    def __init__(self):
        self.nmass = 3 # number of mass eigen states
        self.nnu = const.nnu_standard
        self.mass = np.zeros(self.nmass)

        self.lammax = 1e3 # max of am/T
        self.lammin = 1e-3 # min of am/T
        
        nlam = 1000
        lnlam = np.linspace(np.log(self.lammin),np.log(self.lammax),nlam)
        lnrho = np.zeros(nlam)
        for i in range(nlam):
            lam = np.exp(lnlam[i])
            lnrho[i] = integrate.quad(lambda x:x**2*np.sqrt(x**2+lam**2)/(np.exp(x)+1),0,100)[0]
        lnrho = np.log(lnrho[:]*const.nu_energy) # ratio of massive to massless
        self.spl_lnrho = interpolate.make_interp_spline(lnlam,lnrho)
Пример #45
0
def oscillatorPlot(A,T):
    p=np.array(T)
    q=np.array(A)/2
    plt.title('Oscillator-plot : Amplitude vs Time')
    x=np.linspace(p.min(),p.max(),100)
    a_BSpline=ie.make_interp_spline(p,q)
    y=a_BSpline(x)

    plt.plot(x,y,label="Generated Graph")
    plt.plot(p,q,marker='o',label="Actual Graph")
    plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
    plt.grid(True,which='both')
    plt.axhline(y=0, color='k')
    plt.xlabel('Time in ms')
    plt.ylabel('Amplitude in volts')
    plt.show()
Пример #46
0
 def test_minimum_points_and_deriv(self):
     # interpolation of f(x) = x**3 between 0 and 1. f'(x) = 3 * xx**2 and 
     # f'(0) = 0, f'(1) = 3.
     k = 3
     x = [0., 1.]
     y = [0., 1.]
     b = make_interp_spline(x, y, k, bc_type=([(1, 0.)], [(1, 3.)]))
     
     xx = np.linspace(0., 1.)
     yy = xx**3
     assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)
     
     # If one of the derivatives is omitted, the spline definition is 
     # incomplete:
     assert_raises(ValueError, make_interp_spline, x, y, k, 
             **dict(bc_type=([(1, 0.)], None)))
Пример #47
0
 def test_linear(self):
     b = make_interp_spline(self.xx, self.yy, k=1)
     assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
Пример #48
0
 def test_list_input(self, k):
     # regression test for gh-8714: TypeError for x, y being lists and k=2
     x = list(range(10))
     y = [a**2 for a in x]
     make_interp_spline(x, y, k=k)
Пример #49
0
    def test_string_aliases(self):
        yy = np.sin(self.xx)

        # a single string is duplicated
        b1 = make_interp_spline(self.xx, yy, k=3, bc_type='natural')
        b2 = make_interp_spline(self.xx, yy, k=3, bc_type=([(2, 0)], [(2, 0)]))
        assert_allclose(b1.c, b2.c, atol=1e-15)

        # two strings are handled
        b1 = make_interp_spline(self.xx, yy, k=3,
                                bc_type=('natural', 'clamped'))
        b2 = make_interp_spline(self.xx, yy, k=3,
                                bc_type=([(2, 0)], [(1, 0)]))
        assert_allclose(b1.c, b2.c, atol=1e-15)

        # one-sided BCs are OK
        b1 = make_interp_spline(self.xx, yy, k=2, bc_type=(None, 'clamped'))
        b2 = make_interp_spline(self.xx, yy, k=2, bc_type=(None, [(1, 0.0)]))
        assert_allclose(b1.c, b2.c, atol=1e-15)

        # 'not-a-knot' is equivalent to None
        b1 = make_interp_spline(self.xx, yy, k=3, bc_type='not-a-knot')
        b2 = make_interp_spline(self.xx, yy, k=3, bc_type=None)
        assert_allclose(b1.c, b2.c, atol=1e-15)

        # unknown strings do not pass
        with assert_raises(ValueError):
            make_interp_spline(self.xx, yy, k=3, bc_type='typo')

        # string aliases are handled for 2D values
        yy = np.c_[np.sin(self.xx), np.cos(self.xx)]
        der_l = [(1, [0., 0.])]
        der_r = [(2, [0., 0.])]
        b2 = make_interp_spline(self.xx, yy, k=3, bc_type=(der_l, der_r))
        b1 = make_interp_spline(self.xx, yy, k=3,
                                bc_type=('clamped', 'natural'))
        assert_allclose(b1.c, b2.c, atol=1e-15)

        # ... and for n-D values:
        np.random.seed(1234)
        k, n = 3, 22
        x = np.sort(np.random.random(size=n))
        y = np.random.random(size=(n, 5, 6, 7))

        # now throw in some derivatives
        d_l = [(1, np.zeros((5, 6, 7)))]
        d_r = [(1, np.zeros((5, 6, 7)))]
        b1 = make_interp_spline(x, y, k, bc_type=(d_l, d_r))
        b2 = make_interp_spline(x, y, k, bc_type='clamped')
        assert_allclose(b1.c, b2.c, atol=1e-15)
Пример #50
0
    def test_int_xy(self):
        x = np.arange(10).astype(np.int_)
        y = np.arange(10).astype(np.int_)

        # cython chokes on "buffer type mismatch"
        make_interp_spline(x, y, k=1)
Пример #51
0
 def test_non_int_order(self):
     with assert_raises(TypeError):
         make_interp_spline(self.xx, self.yy, k=2.5)
Пример #52
0
 def spl_interp(x, y, axis):
     return make_interp_spline(x, y, axis=axis)
Пример #53
0
 def test_order_0(self):
     b = make_interp_spline(self.xx, self.yy, k=0)
     assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
Пример #54
0
 def test_not_a_knot(self):
     for k in [3, 5]:
         b = make_interp_spline(self.xx, self.yy, k)
         assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
Пример #55
0
 def bspl_antideriv(x, y, axis=0):
     return make_interp_spline(x, y, axis=axis).antiderivative()