Exemplo n.º 1
0
def gt21_02(x):
    ''' ground truth for 2nd taylor of fexpr2_01. '''
    fexpr2_01 = make_prod(make_pwr('x', 1.0), make_e_expr(make_pwr('x', 1.0)))
    f0 = tof(fexpr2_01)
    f1 = tof(deriv(fexpr2_01))
    f2 = tof(deriv(deriv(fexpr2_01)))
    return f0(2.0) + f1(2.0) * (x - 2.0) + (f2(2.0) / 2) * (x - 2.0)**2
Exemplo n.º 2
0
def problem_2_deriv():
    fexpr = make_prod(make_pwr('t', 2.0), make_ln(make_pwr('t', 1.0)))
    print(fexpr)
    dv = deriv(fexpr)
    print(dv)
    second_dv = deriv(dv)
    tof_second = tof(second_dv)
    print(tof_second(1.0))
Exemplo n.º 3
0
def problem_1_deriv():  # still has problems

    # f(x) =(x+1)(2x+1)(3x+1) /(4x+1)^.5
    fex1 = make_plus(make_pwr('x', 1.0), const(1.0))
    fex2 = make_plus(make_prod(const(2.0), make_pwr('x', 1.0)), const(1.0))
    fex3 = make_plus(make_prod(const(3.0), make_pwr('x', 1.0)), const(1.0))
    fex4 = make_prod(fex1, fex2)

    fex5 = make_prod(fex4, fex3)

    fex6 = make_pwr_expr(
        make_plus(make_prod(const(4.0), make_pwr('x', 1.0)), const(1.0)), 0.5)
    fex = make_quot(fex5, fex6)
    print(fex)
    drv = deriv(fex)
    print('drv: ', drv)
    drvf = tof(drv)

    def gt_drvf(x):
        n = (60.0 * x**3) + (84 * x**2) + 34 * x + 4
        d = (4 * x + 1)**(3 / 2)
        return n / d

    for i in range(1, 10):
        print(drvf(i), gt_drvf(i))
        assert abs(gt_drvf(i) - drvf(i)) <= 0.001

    assert drv is not None
    print(drv)

    # zeros = find_poly_2_zeros(drv)
    # print(zeros)

    f1 = tof(fex)
    f2 = tof(deriv(fex))

    xvals = np.linspace(1, 5, 10000)
    yvals1 = np.array([f1(x) for x in xvals])
    yvals2 = np.array([f2(x) for x in xvals])
    fig1 = plt.figure(1)
    fig1.suptitle('Graph')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.ylim()
    plt.xlim()
    plt.grid()
    plt.plot(xvals, yvals1, label=fex.__str__(), c='r')
    plt.plot(xvals, yvals2, label=deriv(fex).__str__(), c='g')
    plt.legend(loc='best')
    plt.show()
Exemplo n.º 4
0
    def get_zeros(self, rms2, interp):
        n_elements = len(
            self.velocity
        ) * interp  #number of elements of the interpolated profile
        velocity_min = min(self.velocity)
        velocity_max = max(self.velocity)
        velocity_fino = (velocity_min + (velocity_max - velocity_min) *
                         numpy.arange(n_elements) / n_elements)
        ind = []

        perfil_fino = numpy.interp(velocity_fino, self.velocity,
                                   self.intensity)
        deriv1 = deriv.deriv(self.intensity)
        deriv2_nointerpol = deriv.deriv(self.velocity, deriv1)
        deriv2 = numpy.interp(velocity_fino, self.velocity, deriv2_nointerpol)
        self.cont = 0

        for i in range(n_elements - 1):
            signo = deriv2[i] * deriv2[i + 1]
            if signo < 0:

                if not ((self.cont == 0) and (deriv2[i] < deriv2[i + 1])):
                    #we keep the zero only if it goes from negative to positive, as otherwise it corresponds to a different, undetected peak
                    if ((((self.cont + 1) % 2) == 0) and (self.cont != 0)):
                        velant = self.zero[
                            -1]  #busca la velocidad del anterior cero
                        ind_antvel = numpy.where(
                            numpy.array(velocity_fino) == velant)[
                                0]  #busca el indice del perfil correspondiente
                        flux_max = max(
                            perfil_fino[ind_antvel:i]
                        )  #we estimate the intensity as the highest point between the zeros
                        if (max(perfil_fino[ind[self.cont - 1]:i]) >= rms2):

                            #we accept the peak if it is higher thatn twice the rms
                            self.zero.append(velocity_fino[i])
                            self.peak.append(flux_max)
                            ind.append(i)
                            self.cont = self.cont + 1
                        else:
                            #if not, we do not consider it and we must erase the previous zero
                            self.cont = self.cont - 1
                            self.zero.remove(self.zero[self.cont])
                            ind.remove(ind[self.cont])
                    else:
                        self.zero.append(velocity_fino[i])

                        ind.append(i)
                        self.cont = self.cont + 1
        return self.cont
Exemplo n.º 5
0
def find_infl_pnts(expr):
    drv = deriv(expr)
    drv_2 = deriv(drv)
    # print 'f`(x) = ', drv
    # print 'f``(x) = ', drv_2
    zeros = None
    try:
        zeros = find_poly_1_zeros(drv_2)
        # print '1st degree poly'
    except Exception:
        # print 'not a 1st degree poly'
        pass

    try:
        zeros = find_poly_2_zeros(drv_2)
        # print '2nd degree poly'
    except Exception:
        # print 'not a 2nd degree poly'
        pass

    if isinstance(zeros, const):
        zeros = [zeros]

    # print 'zeros:'
    # for z in zeros:
    #     print ':',z.get_val()

    f = tof(expr)
    f_dp = tof(drv_2)
    delta = 0.1
    points = []  #will store array of points and if they are max/min
    #zeros may be None if no inflection points
    if not zeros == None:
        for z in zeros:
            z_val = f(z.get_val())
            z_minus = f_dp(z.get_val() - delta)
            z_plus = f_dp(z.get_val() + delta)
            if z_minus < 0 and z_plus > 0:
                points.append(point2d(z, const(z_val)))
            if z_minus > 0 and z_plus < 0:
                points.append(point2d(z, const(z_val)))
    else:
        return None

    if points == []:
        return None
    else:
        # print points
        return points
Exemplo n.º 6
0
def find_infl_pnts(expr):

    deriv1 = deriv(expr)
    deriv2 = deriv(deriv1)

    zero = find_poly_1_zeros(deriv2)

    func = tof(expr)

    answers = abs(func(zero.get_val()) - 0.0)

    # add answers to iflection points
    inflpoints = [answers]

    return inflpoints
Exemplo n.º 7
0
def plot_spread_of_disease(p, t0, p0, t1, p1, tl, tu):
    assert isinstance(p, const) and isinstance(t0, const)
    assert isinstance(p0, const) and isinstance(t1, const)
    rt = spread_of_disease_model(p, t0, p0, t1, p1)
    rt_tof = tof(rt)
    derv_rt = deriv(rt)

    derv_tof = tof(derv_rt)

    xvals = np.linspace(tl.get_val(), tu.get_val(), 10000)
    yvals1 = np.array([rt_tof(x) for x in xvals])

    xvals2 = np.linspace(tl.get_val(), tu.get_val(), 10000)
    yvals2 = np.array([derv_tof(x) for x in xvals])

    fig1 = plt.figure(1)
    fig1.suptitle('Spread of Disease')
    plt.xlabel('t')
    plt.ylabel('sdf and dsdf')
    plt.ylim([0, 100000])
    plt.xlim([tl.get_val(), tu.get_val()])
    plt.grid()
    plt.plot(xvals, yvals1, label='sdf', c='r')
    plt.plot(xvals2, yvals2, label='dsdf', c='b')

    plt.legend(loc='best')
    plt.show()
Exemplo n.º 8
0
def plot_retention(lmbda, a, t0, t1):
    assert isinstance(lmbda, const)
    assert isinstance(a, const)
    assert isinstance(t0, const)
    assert isinstance(t1, const)
    rt = percent_retention_model(lmbda, a)
    rt_fn = tof(rt)
    derv_rt = deriv(rt)
    derv_tof = tof(derv_rt)

    xvals = np.linspace(t0.get_val(), t1.get_val(), 10000)
    yvals1 = np.array([rt_fn(x) for x in xvals])

    xvals2 = np.linspace(t0.get_val(), t1.get_val(), 10000)
    yvals2 = np.array([derv_tof(x) for x in xvals])

    fig1 = plt.figure(1)
    fig1.suptitle('Ebbinghaus Model of Forgetting')
    plt.xlabel('t')
    plt.ylabel('prf and dprf')
    plt.ylim([-20, 100])
    plt.xlim([t0.get_val(), t1.get_val()])
    plt.grid()
    plt.plot(xvals, yvals1, label='prf', c='r')
    plt.plot(xvals2, yvals2, label='dprf', c='b')

    plt.legend(loc='best')
    plt.show()
Exemplo n.º 9
0
def plot_spread_of_news(p, k, tl, tu):
    assert isinstance(p, const) and isinstance(k, const)
    assert isinstance(tl, const) and isinstance(tu, const)
    nm = spread_of_news_model(p, k)
    nm_tof = tof(nm)
    deriv_nm = deriv(nm)
    deriv_nm_tof = tof(deriv_nm)

    xvals = np.linspace(tl.get_val(), tu.get_val(), 10000)
    yvals1 = np.array([nm_tof(x) for x in xvals])

    xvals2 = np.linspace(tl.get_val(), tu.get_val(), 10000)
    yvals2 = np.array([deriv_nm_tof(x) for x in xvals])

    fig1 = plt.figure(1)
    fig1.suptitle('Spread of News')
    plt.xlabel('t')
    plt.ylabel('snf and dsnf')
    plt.ylim([-2000, 52000])
    plt.xlim([tl.get_val(), tu.get_val()])
    plt.grid()
    plt.plot(xvals, yvals1, label='snf', c='r')
    plt.plot(xvals2, yvals2, label='dsnf', c='b')

    plt.legend(loc='best')
    plt.show()
Exemplo n.º 10
0
def plot_plant_growth(m, t0, h0, t1, h1, tl, tu):
    assert isinstance(m, const) and isinstance(t1, const)
    assert isinstance(t0, const) and isinstance(h0, const)
    assert isinstance(h1, const) and isinstance(tl, const)
    assert isinstance(tu, const)
    pg = plant_growth_model(m, t0, h0, t1, h1)
    pg_tof = tof(pg)
    derv_pg = deriv(pg)

    derv_tof = tof(derv_pg)

    xvals = np.linspace(tl.get_val() - t0.get_val(), tu.get_val(), 10000)
    yvals1 = np.array([pg_tof(x) for x in xvals])

    xvals2 = np.linspace(tl.get_val() - t0.get_val(), tu.get_val(), 10000)
    yvals2 = np.array([derv_tof(x) for x in xvals2])

    fig1 = plt.figure(1)
    fig1.suptitle('Plant Growth')
    plt.xlabel('t')
    plt.ylabel('pgf and dpgf')
    plt.ylim([-2, 58])
    plt.xlim([tl.get_val() - t0.get_val(), tu.get_val()])
    plt.grid()
    plt.plot(xvals, yvals1, label='pgf', c='r')
    plt.plot(xvals2, yvals2, label='dpgf', c='b')

    plt.legend(loc='best')
    plt.show()
Exemplo n.º 11
0
    def test_10(self):
        #(3x+2)^4
        print("****Unit Test 10********")
        fex0 = make_prod(make_const(3.0), make_pwr('x', 1.0))
        fex1 = make_plus(fex0, make_const(2.0))
        fex = make_pwr_expr(fex1, 4.0)
        print(fex)
        afex = antideriv(fex)
        assert not afex is None
        print(afex)
        afexf = tof(afex)
        err = 0.0001

        def gt(x):
            return (1.0 / 15) * ((3 * x + 2.0)**5)

        for i in range(1, 10):
            assert abs(afexf(i) - gt(i)) <= err
        fexf = tof(fex)
        assert not fexf is None
        fex2 = deriv(afex)
        assert not fex2 is None
        print(fex2)
        fex2f = tof(fex2)
        assert not fex2f is None
        for i in range(1, 1000):
            assert abs(fexf(i) - fex2f(i)) <= err
        print('Test 10:pass')
Exemplo n.º 12
0
def plot_plant_growth(m, t1, x1, t2, x2, tl, tu):
    assert isinstance(m, const) and isinstance(t1, const)
    assert isinstance(x1, const) and isinstance(t2, const)
    assert isinstance(x2, const) and isinstance(tl, const)
    assert isinstance(tu, const)

    expr = plant_growth_model(m, t1, x1, t2, x2)
    growth = tof(expr)
    growth_deriv = tof(deriv(expr))

    min = tl.get_val()
    max = tu.get_val()

    xvals = np.linspace(min, max, 10000)
    yvals1 = np.array([growth(x) for x in xvals])
    yvals2 = np.array([growth_deriv(x) for x in xvals])

    fig1 = plt.figure(1)
    fig1.suptitle("Plant Growth")
    plt.xlabel('t')
    plt.ylabel('pgf and dgdf')
    ymax = max(np.max(yvals1), np.max(yvals2))
    ymin = min(np.min(yvals1), np.min(yvals2))
    plt.ylim([ymin, ymax])
    plt.xlim([min, max])
    plt.grid()
    plt.plot(xvals, yvals1, label='pgf', c='r')
    plt.plot(xvals, yvals2, label='dgdf', c='b')
    plt.legend(loc='best')
    plt.show()
Exemplo n.º 13
0
    def test_08(self):
        #(5x-7)^-2  => -1/5 * (5x-7)^-1
        print("****Unit Test 08********")
        fex1 = make_plus(make_prod(make_const(5.0), make_pwr('x', 1.0)),
                         make_const(-7.0))
        fex = make_pwr_expr(fex1, -2.0)
        print(fex)
        afex = antideriv(fex)
        assert not afex is None
        print("antideriv: ", afex)
        afexf = tof(afex)
        err = 0.0001

        def gt(x):
            return (-1.0 / 5.0) * ((5 * x - 7.0)**-1)

        for i in range(1, 100):
            assert abs(afexf(i) - gt(i)) <= err
        fexf = tof(fex)
        assert not fexf is None
        fex2 = deriv(afex)
        assert not fex2 is None
        print("deriv fex2: ", fex2)
        fex2f = tof(fex2)
        assert not fex2f is None
        for i in range(1, 100):
            print(fexf(i), " ", fex2f(i))
            assert abs(fexf(i) - fex2f(i)) <= err
        print('Test 08:pass')
Exemplo n.º 14
0
    def test_assign_03_prob_01_ut_06(self):
        print('\n***** Assign 03: Problem 01: Unit Test 06 *****')
        e1 = make_prod(make_const(2.0), make_pwr('x', 4.0))
        e2 = make_prod(make_const(-1.0), make_pwr('x', 1.0))
        e3 = make_plus(e1, e2)
        e4 = make_plus(e3, make_const(1.0))

        e5 = make_prod(make_const(-1.0), make_pwr('x', 5.0))
        e6 = make_prod(make_const(0.0), make_pwr('x', 4.0))
        e7 = make_plus(e5, e6)
        e8 = make_prod(make_const(0.0), make_pwr('x', 3.0))
        e9 = make_plus(e7, e8)
        e10 = make_prod(make_const(0.0), make_pwr('x', 2.0))
        e11 = make_plus(e9, e10)
        e12 = make_prod(make_const(0.0), make_pwr('x', 1.0))
        e13 = make_plus(e11, e12)
        e14 = make_plus(e13, make_const(1.0))

        e15 = make_prod(e4, e14)
        print('-- function expression is:\n')
        print(e15)
        drv = deriv(e15)
        assert not drv is None
        print('\n-- derivative is:\n')
        print(drv)
        e15f = tof(drv)
        assert not e15f is None
        gt = lambda x: -18.0 * (x**8) + 6.0 * (x**5) - 5.0 * (x**4) + 8.0 * (
            x**3) - 1.0
        err = 0.00001
        print('\n--comparison with ground truth:\n')
        for i in range(10):
            #print(e15f(i), gt(i))
            assert abs(e15f(i) - gt(i)) <= err
        print('Assign 03: Problem 01: Unit Test 06: pass')
Exemplo n.º 15
0
def problem_3_tangent():
    fex = make_e_expr(make_pwr('x', 1.0))
    print("f(x)= ", fex)
    drv = deriv(fex)
    print("f'(x)= ", drv)
    drvf = tof(drv)
    print("f'(-1)= ", drvf(-1))
Exemplo n.º 16
0
    def test_assign_03_prob_01_ut_05(self):
        print('\n***** Assign 03: Problem 01: Unit Test 05 *****')
        e1 = make_plus(make_pwr('x', 1.0), make_const(1.0))

        e2 = make_pwr('x', 3.0)
        e3 = make_prod(make_const(0.0), make_pwr('x', 2.0))
        e4 = make_plus(e2, e3)
        e5 = make_prod(make_const(5.0), make_pwr('x', 1.0))
        e6 = make_plus(e4, e5)
        e7 = make_plus(e6, make_const(2.0))

        e8 = make_prod(e1, e7)
        # 1) print the expression we just constructed
        print('-- function expression is:\n')
        print(e8)
        # 2) differentiate and make sure that it not None
        drv = deriv(e8)
        assert not drv is None
        print('\n-- derivative is:\n')
        print(e8)
        # 3) convert drv into a function
        e8f = tof(drv)
        assert not e8f is None
        # steps 2) and 3) can be combined into tof(deriv(e6)).
        # 4) construct the ground truth function
        gt = lambda x: 4.0 * (x**3) + 3 * (x**2) + 10.0 * x + 7.0
        # 5) compare the ground gruth with what we got in
        # step 3) on an appropriate number range.
        print('\n--comparison with ground truth:\n')
        err = 0.00001
        for i in range(15):
            #print(e8f(i), gt(i))
            assert abs(e8f(i) - gt(i)) <= err
        print('Assign 03: Problem 01: Unit Test 05: pass')
Exemplo n.º 17
0
def loc_xtrm_1st_drv_test(expr):

    #step 1 take derivative
    myderiv = deriv(expr)

    #step2 solve for x
    zeros = find_poly_2_zeros(myderiv)

    # for c in zeros:
    #     print c

    pf = tof(expr)

    extremas = []

    for c in zeros:
        yval = abs(pf(c.get_val()) - 0.0)

        if (pf(c.get_val()) - 1 > 0 & pf(c.get_val()) + 1 < 0):
            extremas.append("min", point2d(c.get_val(), yval))

        else:
            extremas.append("max", point2d(c.get_val(), yval))

    return extremas
Exemplo n.º 18
0
def maximize_revenue(
        dmnd_eq,
        constraint=lambda x: x >= 0):  #only works on linear demand eqs
    rev = incrementPolyPwrs(dmnd_eq, 1)
    rev_drv = deriv(rev)
    # print 'eq:',dmnd_eq
    # print 'rev',rev
    # print 'rev deriv',rev_drv
    rev_drv_f = tof(rev_drv)
    dmnd_f = tof(dmnd_eq)
    rev_f = tof(rev)
    # print 'f(20)',dmnd_f(20)
    # print 'R(20)',rev_f(20)
    # print 'R`(20)',rev_drv_f(20)
    xtrm = loc_xtrm_2nd_drv_test(rev)
    for val in xtrm:
        # print val[0]
        # print val[1]
        x = val[1].get_x().get_val()
        y = val[1].get_y().get_val()

        if (val[0] == 'max' and constraint(x)):
            num_units = const(x)
            revenue = const(y)
            price = const(dmnd_f(x))

    return (num_units, revenue, price)
Exemplo n.º 19
0
def plot_spread_of_news(p, k, tl, tu):
    assert isinstance(p, const) and isinstance(k, const)
    assert isinstance(tl, const) and isinstance(tu, const)

    expr = spread_of_news_model(p, k)
    news = tof(expr)

    expr_deriv = deriv(expr)
    news_deriv = tof(expr_deriv)

    min = tl.get_val()
    max = tu.get_val()

    xvals = np.linspace(min, max, 10000)
    yvals1 = np.array([news(x) for x in xvals])
    yvals2 = np.array([news_deriv(x) for x in xvals])

    fig1 = plt.figure(1)
    fig1.suptitle("Spread of News")
    plt.xlabel('t')
    plt.ylabel('snf and dsnf')
    ymax = max(np.max(yvals1), np.max(yvals2))
    ymin = min(np.min(yvals1), np.min(yvals2))
    plt.ylim([ymin, ymax])
    plt.xlim([min, max])
    plt.grid()
    plt.plot(xvals, yvals1, label='snf', c='r')
    plt.plot(xvals, yvals2, label='dnsf', c='b')
    plt.legend(loc='best')
    plt.show()

    if __name__ == '__main__':
        print("test 1: ")
        fex = percent_retention_model(make_const(1.0), make_const(1.0))
Exemplo n.º 20
0
def plot_spread_of_disease(p, t0, p0, t1, p1, tl, tu):
    assert isinstance(p, const) and isinstance(t0, const)
    assert isinstance(p0, const) and isinstance(t1, const)

    expr = spread_of_disease_model(p, t0, p0, t1, p1)

    disease = tof(expr)
    disease_derive = tof(deriv(expr))

    min = tl.get_val()
    max = tu.get_val()

    xvals = np.linspace(min, max, 10000)
    yvals1 = np.array([disease(x) for x in xvals])
    yvals2 = np.array([disease_derive(x) for x in xvals])

    fig1 = plt.figure(1)
    fig1.suptitle("Spread of Disease")
    plt.xlabel('t')
    plt.ylabel('sdf and dsdf')
    ymax = max(np.max(yvals1), np.max(yvals2))
    ymin = min(np.min(yvals1), np.min(yvals2))
    plt.ylim([ymin, ymax])
    plt.xlim([min, max])
    plt.grid()
    plt.plot(xvals, yvals1, label='sdf', c='r')
    plt.plot(xvals, yvals2, label='dsdf', c='b')
    plt.legend(loc='best')
    plt.show()
Exemplo n.º 21
0
    def test_09(self):
        #3*(x+2)^-1 => 3*ln|x+2|
        print("****Unit Test 09********")
        fex0 = make_plus(make_pwr('x', 1.0), make_const(2.0))
        fex1 = make_pwr_expr(fex0, -1.0)
        fex = make_prod(make_const(3.0), fex1)
        print(fex)
        afex = antideriv(fex)
        print("antideriv: ", afex)
        err = 0.0001
        afexf = tof(afex)

        def gt(x):
            return 3.0 * math.log(abs(2.0 + x), math.e)

        for i in range(1, 101):
            assert abs(afexf(i) - gt(i)) <= err
        assert not afex is None
        print(afex)
        fexf = tof(fex)
        assert not fexf is None
        fex2 = deriv(afex)
        assert not fex2 is None
        print(fex2)
        fex2f = tof(fex2)
        assert not fex2f is None
        for i in range(1, 1000):
            assert abs(fexf(i) - fex2f(i)) <= err
        print('Test 09:pass')
Exemplo n.º 22
0
    def test_03(self):
        #(x+11)/(x-3) ^3
        print('\n***** Test 03 ***********')
        q = make_quot(make_plus(make_pwr('x', 1.0), make_const(11.0)),
                      make_plus(make_pwr('x', 1.0), make_const(-3.0)))
        pex = make_pwr_expr(q, 3.0)
        print('-- function expression is:\n')
        print(pex)
        pexdrv = deriv(pex)
        assert not pexdrv is None
        print('\n - - derivative is:\n')
        print(pexdrv)
        pexdrvf = tof(pexdrv)
        assert not pexdrvf is None
        gt = lambda x: -42.0 * (((x + 11.0)**2) / ((x - 3.0)**4))
        err = 0.00001
        print('\n - -comparison with ground truth:\n')
        for i in range(10):
            if i != 3.0:
                print(pexdrvf(i), gt(i))
                #print("gt: ",gt(0))
                assert abs(pexdrvf(i) - gt(i)) <= err

    #print("pexdrvf(0): ",pexdrvf(0),"gt(i): ", gt(0))
        print('Test 03:pass')
Exemplo n.º 23
0
    def test_assign_03_prob_01_ut_04(self):
        print('\n***** Assign 03: Problem 01: Unit Test 04 *****')
        e1 = make_pwr('x', 2.0)
        e2 = make_plus(e1, make_prod(make_const(0.0), make_pwr('x', 1.0)))
        e3 = make_plus(e2, make_const(-1.0))
        e4 = make_pwr_expr(e3, 4.0)

        e5 = make_pwr('x', 2.0)
        e6 = make_plus(e5, make_prod(make_const(0.0), make_pwr('x', 1.0)))
        e7 = make_plus(e6, make_const(1.0))
        e8 = make_pwr_expr(e7, 5.0)

        e9 = make_prod(e4, e8)

        print(e9)
        e9f = tof(deriv(e9))
        assert not e9f is None
        err = 0.000001

        def drvf(x):
            return 2 * x * ((x**2 - 1.0)**3) * (
                (x**2 + 1.0)**4) * (9 * x**2 - 1.0)

        for i in range(10):
            #print(e9f(i), drvf(i))
            assert abs(e9f(i) - drvf(i)) <= err
        print('Assign 03: Problem 01: Unit Test 04: pass')
Exemplo n.º 24
0
def find_infl_pnts(expr):
    #find the second derivative
    second_drv = deriv(deriv(expr))
    degree = findDegree(second_drv)
    expr_tof = tof(expr)
    inflection_points = []
    if degree == 2:
        zeros = find_poly_2_zeros(second_drv)
        for x in zeros:
            y = expr_tof(x.get_val())
            inflection_points.append(make_point2d(x.get_val() , y))
    else:
        x = find_poly_1_zeros(second_drv)
        y = expr_tof(x.get_val())
        inflection_points.append(make_point2d(x.get_val(), y))

    return inflection_points
Exemplo n.º 25
0
def max_profit(cost_fun, rev_fun):

    profit = plus(cost_fun, prod(rev_fun,-1))
    profit_deriv = deriv(profit)

    zeroes = find_poly_2_zeros(profit_deriv)

    return max(zeroes)
Exemplo n.º 26
0
def newton_raphson(poly_fexpr, g, n):
    tof_expr = tof(poly_fexpr)
    deriv_expr = tof(deriv(poly_fexpr))

    for i in range(n.get_val()):
        x = g.get_val() - (tof_expr(g.get_val()) / deriv_expr(g.get_val()))
        g = const(x)

    return g
Exemplo n.º 27
0
def demand_elasticity(demand_eq, price):
    assert isinstance(price, const)
    # E(p) = (-p*f`(p))/f(p)
    f = tof(demand_eq)
    drv = deriv(demand_eq)
    fprime = tof(drv)
    p = price.get_val()

    return const((-p * fprime(p)) / f(p))
Exemplo n.º 28
0
def getCarleman(f, size):
    #Gets the carlemanmatrix of a function
    result = []
    for m in range(0, size):
        result.append([])
        for n in range(0, size):
            result[m].append(
                deriv.deriv(lambda x: pow(f(x), m), 0, n) / fac(n))
    return np.matrix(result)
Exemplo n.º 29
0
def graph_drv(fexpr, xlim, ylim):
    f1 = tof(fexpr)
    f2 = tof(deriv(fexpr))

    xvals = np.linspace(-2, 2, 10000)
    yvals1 = np.array([f1(x) for x in xvals])
    yvals2 = np.array([f2(x) for x in xvals])
    fig1 = plt.figure(1)
    fig1.suptitle('Graph')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.ylim()
    plt.xlim()
    plt.grid()
    plt.plot(xvals, yvals1, label=fexpr.__str__(), c='r')
    plt.plot(xvals, yvals2, label=deriv(fexpr).__str__(), c='g')
    plt.legend(loc='best')
    plt.show()
Exemplo n.º 30
0
def demand_elasticity(demand_eq, price):
    assert isinstance(price, const)
    fx_drv = tof(deriv(demand_eq))
    fx = tof(demand_eq)

    p = price.get_val()

    n = (-1.0 * p) * fx_drv(p)
    d = fx(p)
    return n / d
Exemplo n.º 31
0
  def get_zeros(self,rms2,interp):
    n_elements=len(self.velocity)*interp#number of elements of the interpolated profile
    velocity_min=min(self.velocity)
    velocity_max=max(self.velocity)
    velocity_fino=(velocity_min+(velocity_max-velocity_min)*numpy.arange(n_elements)/n_elements)
    ind=[]
  
    perfil_fino=numpy.interp(velocity_fino,self.velocity,self.intensity)
    deriv1=deriv.deriv(self.intensity)
    deriv2_nointerpol=deriv.deriv(self.velocity,deriv1)
    deriv2=numpy.interp(velocity_fino,self.velocity,deriv2_nointerpol)
    self.cont=0

    for i in range(n_elements-1):
      signo=deriv2[i]*deriv2[i+1]
      if signo < 0:
	
	if not((self.cont== 0) and (deriv2[i] < deriv2[i+1])):
	  #we keep the zero only if it goes from negative to positive, as otherwise it corresponds to a different, undetected peak
	  if ((((self.cont+1)%2) == 0) and (self.cont != 0)):
	    velant=self.zero[-1]#busca la velocidad del anterior cero
	    ind_antvel=numpy.where(numpy.array(velocity_fino)==velant)[0]#busca el indice del perfil correspondiente
	    flux_max=max(perfil_fino[ind_antvel:i])#we estimate the intensity as the highest point between the zeros
	    if (max(perfil_fino[ind[self.cont-1]:i]) >= rms2):
	      
	    #we accept the peak if it is higher thatn twice the rms
	      self.zero.append(velocity_fino[i])
	      self.peak.append(flux_max)
	      ind.append(i)
	      self.cont=self.cont+1 
	    else:
	      #if not, we do not consider it and we must erase the previous zero
	      self.cont=self.cont-1
	      self.zero.remove(self.zero[self.cont])
	      ind.remove(ind[self.cont])
	  else:      
	    self.zero.append(velocity_fino[i])
	    
	    ind.append(i)
	    self.cont=self.cont+1 
    return self.cont
Exemplo n.º 32
0
def lk(im1, im2, i, j, window_size):
    fx, fy, ft = deriv.deriv(im1, im2)
    halfWindow = np.floor(window_size / 2)
    curFx = fx[i - halfWindow - 1 : i + halfWindow, j - halfWindow - 1 : j + halfWindow]
    curFy = fy[i - halfWindow - 1 : i + halfWindow, j - halfWindow - 1 : j + halfWindow]
    curFt = ft[i - halfWindow - 1 : i + halfWindow, j - halfWindow - 1 : j + halfWindow]
    curFx = curFx.T
    curFy = curFy.T
    curFt = curFt.T

    curFx = curFx.flatten(order="F")
    curFy = curFy.flatten(order="F")
    curFt = -curFt.flatten(order="F")

    A = np.vstack((curFx, curFy)).T
    U = np.dot(np.dot(lin.pinv(np.dot(A.T, A)), A.T), curFt)
    return U[0], U[1]
Exemplo n.º 33
0
Arquivo: lk.py Projeto: chyojn/kod
def lk(g, im1, im2, i_s, j_s, window_size):
    fx, fy, ft = deriv.deriv(im1, im2, g)
    halfWindow = np.floor(window_size/2)
    res = []
    for i,j in itertools.izip(i_s,j_s):
        curFx = fx[i-halfWindow-1:i+halfWindow, 
                   j-halfWindow-1:j+halfWindow]
        curFy = fy[i-halfWindow-1:i+halfWindow, 
                   j-halfWindow-1:j+halfWindow]
        curFt = ft[i-halfWindow-1:i+halfWindow, 
                   j-halfWindow-1:j+halfWindow]
        curFx = curFx.T
        curFy = curFy.T
        curFt = curFt.T

        curFx = curFx.flatten(order='F') 
        curFy = curFy.flatten(order='F') 
        curFt = -curFt.flatten(order='F') 

        A = np.vstack((curFx, curFy)).T
        U = np.dot(np.dot(lin.pinv(np.dot(A.T,A)),A.T),curFt)
        res.append((i,j,U[0],U[1]))
    return res
Exemplo n.º 34
0
def lk(im1, im2, window_size) :
    u = np.zeros(im1.shape)
    v = np.zeros(im2.shape)

    fx, fy, ft = deriv.deriv(im1, im2)
    halfWindow = np.floor(window_size/2)
    for i in range(int(halfWindow+1),int(fx.shape[0]-halfWindow)):
        for j in range(int(halfWindow+1),int(fx.shape[1]-halfWindow)):
            curFx = fx[i-halfWindow-1:i+halfWindow, 
                       j-halfWindow-1:j+halfWindow]
            curFy = fy[i-halfWindow-1:i+halfWindow, 
                       j-halfWindow-1:j+halfWindow]
            curFt = ft[i-halfWindow-1:i+halfWindow, 
                       j-halfWindow-1:j+halfWindow]
        
            curFx = curFx.flatten() 
            curFy = curFy.flatten() 
            curFt = -curFt.flatten() 
            
            A = np.vstack((curFx, curFy)).T
            U = np.dot(np.dot(lin.pinv(np.dot(A.T,A)),A.T),curFt)
            u[i,j] = U[0]
            v[i,j] = U[1]
    return (u,v)