예제 #1
0
def rytov_two_layer_numerical(width_layer_1, width_layer_2, frequency,
                              ref_index_1, ref_index_2, x0):
    a = width_layer_1
    b = width_layer_2
    f = frequency
    eps_1 = ref_index_1**2
    eps_2 = ref_index_2**2

    k = 2 * np.pi * f / (3 * 10**8)

    r = Rational(1, 2)

    # parallel (first return value) (p-pol.)
    eps_te = nsolve(
        k * (eps_2 - eps)**r * tan(k * (eps_2 - eps)**r * b * r) + k *
        (eps_1 - eps)**r * tan(k * (eps_1 - eps)**r * a * r), eps, x0[0])

    # perpendicular (second return value) (s-pol.)
    eps_tm = nsolve(
        (1 / eps_2) * k * (eps_2 - eps)**r * tan(k *
                                                 (eps_2 - eps)**r * b * r) +
        (1 / eps_1) * k * (eps_1 - eps)**r * tan(k * (eps_1 - eps)**r * a * r),
        eps, x0[1])

    return [eps_te**0.5, eps_tm**0.5]
예제 #2
0
def test_nsolve():
    # onedimensional
    from sympy import Symbol, sin, pi
    x = Symbol('x')
    assert nsolve(sin(x), 2) - pi.evalf() < 1e-16
    assert nsolve(Eq(2 * x, 2), x, -10) == nsolve(2 * x - 2, -10)
    # multidimensional
    x1 = Symbol('x1')
    x2 = Symbol('x2')
    f1 = 3 * x1**2 - 2 * x2**2 - 1
    f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
    f = Matrix((f1, f2)).T
    F = lambdify((x1, x2), f.T, modules='mpmath')
    for x0 in [(-1, 1), (1, -2), (4, 4), (-4, -4)]:
        x = nsolve(f, (x1, x2), x0, tol=1.e-8)
        assert mnorm(F(*x), 1) <= 1.e-10
    # The Chinese mathematician Zhu Shijie was the very first to solve this
    # nonlinear system 700 years ago (z was added to make it 3-dimensional)
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    f1 = -x + 2 * y
    f2 = (x**2 + x * (y**2 - 2) - 4 * y) / (x + 4)
    f3 = sqrt(x**2 + y**2) * z
    f = Matrix((f1, f2, f3)).T
    F = lambdify((x, y, z), f.T, modules='mpmath')

    def getroot(x0):
        root = nsolve((f1, f2, f3), (x, y, z), x0)
        assert mnorm(F(*root), 1) <= 1.e-8
        return root

    assert map(round, getroot((1, 1, 1))) == [2.0, 1.0, 0.0]
예제 #3
0
def cctGenSetDminDmax(Q_in, Ekin0_in, minTol_in, Z_in, deltaDmin_in,
                      deltaDmax_in, xsaddle_in, dsaddle_in, xcontact_in,
                      dcontact_in):
    # Calculate limits
    Eav = Q_in - np.sum(Ekin0_in) - minTol_in

    # Solve Dmin
    Dsym = Symbol('Dsym')
    Dmin = np.float(nsolve(Dsym - (Z_in[0]*Z_in[1]/xsaddle_in + \
                                   Z_in[0]*Z_in[2]/dsaddle_in + \
                                   Z_in[1]*Z_in[2] \
                                   )*1.43996518/(Eav), Dsym, 18.0)) + \
           deltaDmin_in + minTol_in

    Dmax = Dmin + deltaDmax_in

    # What is minimum D when TP and LF are touching
    A = ((Eav) / 1.43996518 - Z_in[0] * Z_in[2] / dcontact_in) / Z_in[1]
    D_tpl_contact = np.float(nsolve(Dsym**2*A - \
                                    Dsym*(A*dcontact_in + Z_in[0] +
                                          Z_in[2]) + \
                                    Z_in[2]*dcontact_in, Dsym, 26.0))
    # What is minimum D when TP and HF are touching
    A = ((Eav) / 1.43996518 - Z_in[0] * Z_in[1] / xcontact_in) / Z_in[2]
    D_tph_contact = np.float(nsolve(Dsym**2*A - \
                                    Dsym*(A*xcontact_in + Z_in[0] +
                                          Z_in[1]) + \
                                    Z_in[1]*xcontact_in, Dsym, 30.0))
    del A
    del Dsym
    del Eav
    return Dmin, Dmax, D_tpl_contact, D_tph_contact
예제 #4
0
파일: test_numeric.py 프로젝트: cran/rSymPy
def test_nsolve():
    # onedimensional
    from sympy import Symbol, sin, pi
    x = Symbol('x')
    assert nsolve(sin(x), 2) - pi.evalf() < 1e-16
    assert nsolve(Eq(2*x, 2), x, -10) == nsolve(2*x - 2, -10)
    # multidimensional
    x1 = Symbol('x1')
    x2 = Symbol('x2')
    f1 = 3 * x1**2 - 2 * x2**2 - 1
    f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
    f = Matrix((f1, f2)).T
    F = lambdify((x1, x2), f.T, modules='mpmath')
    for x0 in [(-1, 1), (1, -2), (4, 4), (-4, -4)]:
        x = nsolve(f, (x1, x2), x0, tol=1.e-8)
        assert mnorm(F(*x),1) <= 1.e-10
    # The Chinese mathematician Zhu Shijie was the very first to solve this
    # nonlinear system 700 years ago (z was added to make it 3-dimensional)
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    f1 = -x + 2*y
    f2 = (x**2 + x*(y**2 - 2) - 4*y)  /  (x + 4)
    f3 = sqrt(x**2 + y**2)*z
    f = Matrix((f1, f2, f3)).T
    F = lambdify((x,  y,  z), f.T, modules='mpmath')
    def getroot(x0):
        root = nsolve((f1,  f2,  f3), (x,  y,  z), x0)
        assert mnorm(F(*root),1) <= 1.e-8
        return root
    assert map(round,  getroot((1,  1,  1))) == [2.0,  1.0,  0.0]
예제 #5
0
def test_nsolve_complex():
    x, y = symbols('x y')

    assert nsolve(x**2 + 2, 1j) == sqrt(2.)*I
    assert nsolve(x**2 + 2, I) == sqrt(2.)*I

    assert nsolve([x**2 + 2, y**2 + 2], [x, y], [I, I]) == Matrix([sqrt(2.)*I, sqrt(2.)*I])
    assert nsolve([x**2 + 2, y**2 + 2], [x, y], [I, I]) == Matrix([sqrt(2.)*I, sqrt(2.)*I])
예제 #6
0
def test_nsolve_complex():
    x, y = symbols('x y')

    assert nsolve(x**2 + 2, 1j) == sqrt(2.)*I
    assert nsolve(x**2 + 2, I) == sqrt(2.)*I

    assert nsolve([x**2 + 2, y**2 + 2], [x, y], [I, I]) == Matrix([sqrt(2.)*I, sqrt(2.)*I])
    assert nsolve([x**2 + 2, y**2 + 2], [x, y], [I, I]) == Matrix([sqrt(2.)*I, sqrt(2.)*I])
예제 #7
0
def test_nsolve_dict_kwarg():
    x, y = symbols('x y')
    # one variable
    assert nsolve(x**2 - 2, 1, dict = True) == \
        [{x: sqrt(2.)}]
    # one variable with complex solution
    assert nsolve(x**2 + 2, I, dict = True) == \
        [{x: sqrt(2.)*I}]
    # two variables
    assert nsolve([x**2 + y**2 - 5, x**2 - y**2 + 1], [x, y], [1, 1], dict = True) == \
        [{x: sqrt(2.), y: sqrt(3.)}]
예제 #8
0
def test_nsolve_dict_kwarg():
    x, y = symbols('x y')
    # one variable
    assert nsolve(x**2 - 2, 1, dict = True) == \
        [{x: sqrt(2.)}]
    # one variable with complex solution
    assert nsolve(x**2 + 2, I, dict = True) == \
        [{x: sqrt(2.)*I}]
    # two variables
    assert nsolve([x**2 + y**2 - 5, x**2 - y**2 + 1], [x, y], [1, 1], dict = True) == \
        [{x: sqrt(2.), y: sqrt(3.)}]
예제 #9
0
def test_nsolve_precision():
    x, y = symbols('x y')
    sol = nsolve(x**2 - pi, x, 3, prec=128)
    assert abs(sqrt(pi).evalf(128) - sol) < 1e-128
    assert isinstance(sol, Float)

    sols = nsolve((y**2 - x, x**2 - pi), (x, y), (3, 3), prec=128)
    assert isinstance(sols, Matrix)
    assert sols.shape == (2, 1)
    assert abs(sqrt(pi).evalf(128) - sols[0]) < 1e-128
    assert abs(sqrt(sqrt(pi)).evalf(128) - sols[1]) < 1e-128
    assert all(isinstance(i, Float) for i in sols)
	def age_dist(self, age=1.0):

		# Half-lives from Dunham et al. (2014) and age distribution from C2D (Evans et al. 2009) and Sadavoy et al. 2014
		# Note: Not correct half-lives: would need to be recalculated under the assumption of consecutive decay which is why
		# the calculated age distribution does not match the input criteria

		### Relative population fractions observed in Perseus where t = 1 Myr
		age_frac = numpy.asarray([0.068, 0.211, 0.102, 0.545, 0.075])
		age_0 = 1.0

		lmbda_obs = numpy.zeros(5)
		lmbda = numpy.zeros(5)
		for i in range(0,len(age_frac)): lmbda_obs[i] = log(age_frac[i])/(-age_0)

		# Get values of lambda corresponding to observed age distribution
		# Note that the initial guesses are specific to the Class distribution in Perseus at 1 Myr
		x = Symbol('x')
		lmbda[0] = nsolve(exp(-x * age_0) - age_frac[0], x, [lmbda_obs[0]])
		lmbda[1] = nsolve(lmbda[0]/(x-lmbda[0]) * (exp(-lmbda[0]*age_0) - exp(-x*age_0)) - age_frac[1], x, [lmbda_obs[1]])
		lmbda[2] = nsolve(lmbda[0]*lmbda[1] * (exp(-lmbda[0]*age_0)/(lmbda[1]-lmbda[0])/(x-lmbda[0]) + 
			exp(-lmbda[1]*age_0)/(lmbda[0]-lmbda[1])/(x-lmbda[1]) + 
			exp(-x*age_0)/(lmbda[0]-x)/(lmbda[1]-x))-age_frac[2], x, [6.0])
		lmbda[3] = nsolve(lmbda[0]*lmbda[1]*lmbda[2] * (exp(-lmbda[0]*age_0)/(lmbda[1]-lmbda[0])/(lmbda[2]-lmbda[0])/(x-lmbda[0]) +
			exp(-lmbda[1]*age_0)/(lmbda[0]-lmbda[1])/(lmbda[2]-lmbda[1])/(x-lmbda[1]) + 
			exp(-lmbda[2]*age_0)/(lmbda[0]-lmbda[2])/(lmbda[1]-lmbda[2])/(x-lmbda[2]) + 
			exp(-x*age_0)/(lmbda[0]-x)/(lmbda[1]-x)/(lmbda[2]-x)) - age_frac[3], x, [0.3])
		lmbda[4] = nsolve(lmbda[0]*lmbda[1]*lmbda[2]*lmbda[3] * (exp(-lmbda[0]*age_0)/(lmbda[1]-lmbda[0])/(lmbda[2]-lmbda[0])/(lmbda[3]-lmbda[0])/(x-lmbda[0]) +
			exp(-lmbda[1]*age_0)/(lmbda[0]-lmbda[1])/(lmbda[2]-lmbda[1])/(lmbda[3]-lmbda[1])/(x-lmbda[1]) + 
			exp(-lmbda[2]*age_0)/(lmbda[0]-lmbda[2])/(lmbda[1]-lmbda[2])/(lmbda[3]-lmbda[2])/(x-lmbda[2]) + 
			exp(-lmbda[3]*age_0)/(lmbda[0]-lmbda[3])/(lmbda[1]-lmbda[3])/(lmbda[2]-lmbda[3])/(x-lmbda[3]) + 
			exp(-x*age_0)/(lmbda[0]-x)/(lmbda[1]-x)/(lmbda[2]-x)/(lmbda[3]-x)) - age_frac[4], x, [-0.1])

		# Calculate new fractional populations, setting Class III equal to any leftovers
		self.frac = numpy.zeros(5)
		self.frac[0] = exp(-lmbda[0]*age)
		self.frac[1] = lmbda[0]/(lmbda[1]-lmbda[0]) * (exp(-lmbda[0]*age) - exp(-lmbda[1]*age))
		self.frac[2] = lmbda[0]*lmbda[1] * (exp(-lmbda[0]*age)/(lmbda[1]-lmbda[0])/(lmbda[2]-lmbda[0]) + 
			exp(-lmbda[1]*age)/(lmbda[0]-lmbda[1])/(lmbda[2]-lmbda[1]) + 
			exp(-lmbda[2]*age)/(lmbda[0]-lmbda[2])/(lmbda[1]-lmbda[2]))
		self.frac[3] = lmbda[0]*lmbda[1]*lmbda[2] * (exp(-lmbda[0]*age)/(lmbda[1]-lmbda[0])/(lmbda[2]-lmbda[0])/(lmbda[3]-lmbda[0]) +
			exp(-lmbda[1]*age)/(lmbda[0]-lmbda[1])/(lmbda[2]-lmbda[1])/(lmbda[3]-lmbda[1]) + 
			exp(-lmbda[2]*age)/(lmbda[0]-lmbda[2])/(lmbda[1]-lmbda[2])/(lmbda[3]-lmbda[2]) + 
			exp(-lmbda[3]*age)/(lmbda[0]-lmbda[3])/(lmbda[1]-lmbda[3])/(lmbda[2]-lmbda[3]))
		# self.frac[4] = lmbda[0]*lmbda[1]*lmbda[2]*lmbda[3] * (exp(-lmbda[0]*age)/(lmbda[1]-lmbda[0])/(lmbda[2]-lmbda[0])/(lmbda[3]-lmbda[0])/(lmbda[4]-lmbda[0]) +
		#	exp(-lmbda[1]*age)/(lmbda[0]-lmbda[1])/(lmbda[2]-lmbda[1])/(lmbda[3]-lmbda[1])/(lmbda[4]-lmbda[1]) + 
		#	exp(-lmbda[2]*age)/(lmbda[0]-lmbda[2])/(lmbda[1]-lmbda[2])/(lmbda[3]-lmbda[2])/(lmbda[4]-lmbda[2]) + 
		#	exp(-lmbda[3]*age)/(lmbda[0]-lmbda[3])/(lmbda[1]-lmbda[3])/(lmbda[2]-lmbda[3])/(lmbda[4]-lmbda[3]) + 
		#	exp(-lmbda[4]*age)/(lmbda[0]-lmbda[4])/(lmbda[1]-lmbda[4])/(lmbda[2]-lmbda[4])/(lmbda[3]-lmbda[4]))

		# Assume that everything ends up as Class III; no main sequence. An ok assumption when the interest is on Class 0/I sources
		self.frac[4] = 1. - sum(self.frac[:4])

		return self.frac
예제 #11
0
def test_nsolve_precision():
    x, y = symbols('x y')
    sol = nsolve(x**2 - pi, x, 3, prec=128)
    assert abs(sqrt(pi).evalf(128) - sol) < 1e-128
    assert isinstance(sol, Float)

    sols = nsolve((y**2 - x, x**2 - pi), (x, y), (3, 3), prec=128)
    assert isinstance(sols, Matrix)
    assert sols.shape == (2, 1)
    assert abs(sqrt(pi).evalf(128) - sols[0]) < 1e-128
    assert abs(sqrt(sqrt(pi)).evalf(128) - sols[1]) < 1e-128
    assert all(isinstance(i, Float) for i in sols)
예제 #12
0
def test_nsolve_fail():
    x = symbols('x')
    # Sometimes it is better to use the numerator (issue 4829)
    # but sometimes it is not (issue 11768) so leave this to
    # the discretion of the user
    ans = nsolve(x**2/(1 - x)/(1 - 2*x)**2 - 100, x, 0)
    assert ans > 0.46 and ans < 0.47
예제 #13
0
def test_nsolve_fail():
    x = symbols('x')
    # Sometimes it is better to use the numerator (issue 4829)
    # but sometimes it is not (issue 11768) so leave this to
    # the discretion of the user
    ans = nsolve(x**2 / (1 - x) / (1 - 2 * x)**2 - 100, x, 0)
    assert ans > 0.46 and ans < 0.47
예제 #14
0
def rytov_two_layer_numerical(l1, l2, eps1, eps2, frequency, x0):
    k = 2 * pi * frequency / c

    r = Rational(1, 2)

    # parallel (first return value) (p-pol.)
    eps_p = nsolve(
        k * (eps2 - eps)**r * tan(k * (eps2 - eps)**r * l2 * r) + k *
        (eps1 - eps)**r * tan(k * (eps1 - eps)**r * l1 * r), eps, x0[0])

    # perpendicular (second return value) (s-pol.)
    eps_s = nsolve(
        (1 / eps2) * k * (eps2 - eps)**r * tan(k * (eps2 - eps)**r * l2 * r) +
        (1 / eps1) * k * (eps1 - eps)**r * tan(k * (eps1 - eps)**r * l1 * r),
        eps, x0[1])

    return [eps_s**0.5, eps_p**0.5]
예제 #15
0
def test_increased_dps():
    # Issue 8564
    import mpmath
    mpmath.mp.dps = 128
    x = Symbol('x')
    e1 = x**2 - pi
    q = nsolve(e1, x, 3.0)

    assert abs(sqrt(pi).evalf(128) - q) < 1e-128
예제 #16
0
def test_increased_dps():
    # Issue 8564
    import mpmath
    mpmath.mp.dps = 128
    x = Symbol('x')
    e1 = x**2 - pi
    q = nsolve(e1, x, 3.0)

    assert abs(sqrt(pi).evalf(128) - q) < 1e-128
예제 #17
0
def solvey(D_in, x_in, E_in, Z_in, c_in, sol_guess):
    ke2 = 1.43996518
    yval = Symbol('yval')
    try:
        ySolution = nsolve(sp.sqrt((D_in-x_in)**2+yval**2)**5*Z_in[1]*(10.0*(x_in**2+yval**2)**2+c_in[1]**2*(2*x_in**2-yval**2)) + \
                           sp.sqrt(x_in**2+yval**2)**5*Z_in[2]*(10.0*((D_in-x_in)**2+yval**2)**2+c_in[2]**2*(2*(D_in-x_in)**2-yval**2)) + \
                          -10.0*(sp.sqrt(x_in**2+yval**2)*sp.sqrt((D_in-x_in)**2+yval**2))**5* \
                                (E_in/ke2 - (Z_in[1]*Z_in[2])*(1.0/D_in+(c_in[1]**2+c_in[2]**2)/(5.0*D_in**3)))/Z_in[0],
                           yval, sol_guess)
    except ValueError:
        ySolution = 0.0
    return np.float(ySolution)
예제 #18
0
def test_nsolve():
    # onedimensional
    x = Symbol('x')
    assert nsolve(sin(x), 2) - pi.evalf() < 1e-15
    assert nsolve(Eq(2 * x, 2), x, -10) == nsolve(2 * x - 2, -10)
    # Testing checks on number of inputs
    raises(TypeError, lambda: nsolve(Eq(2 * x, 2)))
    raises(TypeError, lambda: nsolve(Eq(2 * x, 2), x, 1, 2))
    # issue 4829
    assert nsolve(x**2 / (1 - x) / (1 - 2 * x)**2 - 100, x, 0)  # doesn't fail
    # multidimensional
    x1 = Symbol('x1')
    x2 = Symbol('x2')
    f1 = 3 * x1**2 - 2 * x2**2 - 1
    f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
    f = Matrix((f1, f2)).T
    F = lambdify((x1, x2), f.T, modules='mpmath')
    for x0 in [(-1, 1), (1, -2), (4, 4), (-4, -4)]:
        x = nsolve(f, (x1, x2), x0, tol=1.e-8)
        assert mnorm(F(*x), 1) <= 1.e-10
    # The Chinese mathematician Zhu Shijie was the very first to solve this
    # nonlinear system 700 years ago (z was added to make it 3-dimensional)
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    f1 = -x + 2 * y
    f2 = (x**2 + x * (y**2 - 2) - 4 * y) / (x + 4)
    f3 = sqrt(x**2 + y**2) * z
    f = Matrix((f1, f2, f3)).T
    F = lambdify((x, y, z), f.T, modules='mpmath')

    def getroot(x0):
        root = nsolve(f, (x, y, z), x0)
        assert mnorm(F(*root), 1) <= 1.e-8
        return root

    assert list(map(round, getroot((1, 1, 1)))) == [2.0, 1.0, 0.0]
    assert nsolve([Eq(f1), Eq(f2), Eq(f3)], [x, y, z],
                  (1, 1, 1))  # just see that it works
    a = Symbol('a')
    assert abs(
        nsolve(1 / (0.001 + a)**3 - 6 /
               (0.9 - a)**3, a, 0.3) - mpf('0.31883011387318591')) < 1e-15
예제 #19
0
def eqn(ztp, zh, zl, rh, rtp, rl, x, y):
    ke = 1.439964
    Q = 185.891
    a = (Q / ke)**2
    b = (ztp * zh)**2
    c = (ztp * zl)**2
    d = (zh * zl)**2
    A = rh + rtp - x * (2 * rtp + rh + rl)

    dmin = Symbol('dmin')
    return nsolve(
        ztp * zh / ((dmin * x + A)**2 + y**2)**(0.5) + ztp * zl /
        ((dmin * (1 - x) - A)**2 + y**2)**(0.5) + zh * zl / dmin - Q / ke,
        dmin, 18)
예제 #20
0
def test_nsolve():
    # onedimensional
    x = Symbol('x')
    assert nsolve(sin(x), 2) - pi.evalf() < 1e-15
    assert nsolve(Eq(2*x, 2), x, -10) == nsolve(2*x - 2, -10)
    # Testing checks on number of inputs
    raises(TypeError, lambda: nsolve(Eq(2*x, 2)))
    raises(TypeError, lambda: nsolve(Eq(2*x, 2), x, 1, 2))
    # issue 4829
    assert nsolve(x**2/(1 - x)/(1 - 2*x)**2 - 100, x, 0)  # doesn't fail
    # multidimensional
    x1 = Symbol('x1')
    x2 = Symbol('x2')
    f1 = 3 * x1**2 - 2 * x2**2 - 1
    f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
    f = Matrix((f1, f2)).T
    F = lambdify((x1, x2), f.T, modules='mpmath')
    for x0 in [(-1, 1), (1, -2), (4, 4), (-4, -4)]:
        x = nsolve(f, (x1, x2), x0, tol=1.e-8)
        assert mnorm(F(*x), 1) <= 1.e-10
    # The Chinese mathematician Zhu Shijie was the very first to solve this
    # nonlinear system 700 years ago (z was added to make it 3-dimensional)
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    f1 = -x + 2*y
    f2 = (x**2 + x*(y**2 - 2) - 4*y) / (x + 4)
    f3 = sqrt(x**2 + y**2)*z
    f = Matrix((f1, f2, f3)).T
    F = lambdify((x, y, z), f.T, modules='mpmath')

    def getroot(x0):
        root = nsolve(f, (x, y, z), x0)
        assert mnorm(F(*root), 1) <= 1.e-8
        return root
    assert list(map(round, getroot((1, 1, 1)))) == [2.0, 1.0, 0.0]
    assert nsolve([Eq(
        f1), Eq(f2), Eq(f3)], [x, y, z], (1, 1, 1))  # just see that it works
    a = Symbol('a')
    assert nsolve(1/(0.001 + a)**3 - 6/(0.9 - a)**3, a, 0.3).ae(
        mpf('0.31883011387318591'))
예제 #21
0
def getDnPrice(closes, rsis, dAvgUps, dAvgDns, len_rsi, len_bb, para_bb,
               bb_flag):
    # if close < close[-1]
    x = Symbol('x')
    dUp = 0
    dDn = closes[-1] - x
    dAvgUp = dAvgUps[-1] * (len_rsi - 1) / len_rsi
    dAvgDn = (dAvgDns[-1] * (len_rsi - 1) + dDn) / len_rsi
    rsi = dAvgUp / (dAvgUp + dAvgDn) * 100
    mean = (np.sum(rsis[-len_bb + 1:]) + rsi) / len_bb
    sum2 = 0
    for i in range(-len_bb + 1, 0):
        sum2 += (rsis[i] - mean)**2
    sum2 += (rsi - mean)**2
    std_dev = sqrt(sum2 / len_bb)
    if bb_flag == 'up':
        bb = mean + para_bb * std_dev
    elif bb_flag == 'low':
        bb = mean - para_bb * std_dev
    return nsolve(rsi - bb, x, closes[-1])
예제 #22
0
def solveDwhenTPonAxis(xr_in, E_in, Z_in, ec_in, sol_guess):
    """
    Get D for given x, Energy, particle Z and particle radii, when ternary
    particle is on axis.
    
    :type xr_in: float
    :param xr_in: relative x displacement of ternary particle between heavy and
                 light fission fragment.
    
    :type y_in: float
    :param y_in: y displacement between ternary particle and fission axis.
    
    :type E_in: float
    :param E_in: Energy in MeV.
    
    :type Z_in: list of ints
    :param Z_in: Particle proton numbers [Z1, Z2, Z3].

    :type sol_guess: float
    :param sol_guess: Initial guess for solution.
    
    :rtype: float
    :returns: D for current equation.
    """

    ke2 = 1.43996518

    Dval = Symbol('Dval')
    return np.float(nsolve(Dval**5*(Z_in[0]*Z_in[1]*(1.0-xr_in)**2+\
                                    Z_in[0]*Z_in[2]*(1.0-xr_in)**3/xr_in+\
                                    Z_in[1]*Z_in[2]*(1.0-xr_in)**3)+\
                           Dval**3*(Z_in[0]*Z_in[1]*ec_in[1]**2/5.0+\
                                    Z_in[0]*Z_in[2]*ec_in[2]**2/5.0*\
                                                    (1.0-xr_in)**3+\
                                    Z_in[1]*Z_in[2]*(ec_in[1]**2+
                                                     ec_in[2]**2)/5.0*\
                                                    (1.0-xr_in)**3)+\
                           -Dval**6*(E_in/ke2)*(1-xr_in)**3,
                           Dval, sol_guess))
    def solvey(self, D_in, x_in, E_in, Z_in, sol_guess):
        """
        Get y for given D, x, Energy, particle Z and particle radii.
        
        :type D_in: float
        :param D_in: Distance between heavy and light fission fragment.
        
        :type x_in: float
        :param x_in: x displacement between ternary particle and heavy fragment.
        
        :type E_in: float
        :param E_in: Energy in MeV.
        
        :type Z_in: list of ints
        :param Z_in: Particle proton numbers [Z1, Z2, Z3].

        :type sol_guess: float
        :param sol_guess: Initial guess for solution.
        
        :rtype: float
        :returns: y for current equation.
        """
        #sp.mpmath.mp.dps = 3
        yval = Symbol('yval')
        #A = E_in/self.ke2 - Z_in[1]*Z_in[2]/D_in
        #b = Z_in[0]*Z_in[1]
        #c = Z_in[0]*Z_in[2]
        #B = (x_in**2+yval**2)**(0.5)
        #C = ((D_in-x_in)**2+yval**2)**(0.5)

        #return np.float(nsolve(b*C+c*B - A*B*C, yval, sol_guess))
        try:
            ySolution = nsolve(Z_in[0]*Z_in[1]*sp.sqrt((D_in-x_in)**2 + yval**2) + \
                               Z_in[0]*Z_in[2]*sp.sqrt(x_in**2 + yval**2) - \
                               (E_in/self.ke2 - Z_in[1]*Z_in[2]/D_in)*sp.sqrt(x_in**2+yval**2)*sp.sqrt((D_in-x_in)**2+yval**2),
                               yval, sol_guess)
        except ValueError:
            ySolution = 0.0
        return np.float(ySolution)
예제 #24
0
def model2(data, n, price1, price2):
    sample = float(data.shape[0])
    shares = np.histogram(data[:, 1], bins=np.arange(1.0, n + 2.0))[0] / sample
    x = Symbol("x")
    y = Symbol("y")
    eq1 = shares[1] * price1 - (price1 * x) / (1 + x + y)
    eq2 = shares[2] * price2 - (price2 * y) / (1 + x + y)
    sl = nsolve(
        (eq1, eq2),
        (x, y),
        (0.5, 0.5),
        set=True,
        rational=True,
        manual=True,
        implicit=True,
        simplify=True,
        numerical=True,
    )
    # print('prices: 0\t' + str(price1) + '\t' + str(price2))
    # print('shares: ' + str(shares[0]) + '\t' + str(shares[1])  + '\t' + str(shares[2]))
    # print('d = ' + str(sl[0]) + '\t' + str(sl[1]))
    V = np.array([0, sl[0], sl[1]])
    return V
    def solveD(self, xr_in, y_in, E_in, Z_in, rad_in, sol_guess):
        """
        Get D for given x, y, Energy, particle Z and particle radii.
        
        :type xr_in: float
        :param xr_in: relative x displacement of ternary particle between heavy and
                     light fission fragment.
        
        :type y_in: float
        :param y_in: y displacement between ternary particle and fission axis.
        
        :type E_in: float
        :param E_in: Energy in MeV.
        
        :type Z_in: list of ints
        :param Z_in: Particle proton numbers [Z1, Z2, Z3].
        
        :type rad_in: list of ints
        :param rad_in: Particle radii [rad1, rad2, rad3].

        :type sol_guess: float
        :param sol_guess: Initial guess for solution.
        
        :rtype: float
        :returns: D for current equation.
        """

        a = (Z_in[0] * Z_in[1])
        b = (Z_in[0] * Z_in[2])
        c = (Z_in[1] * Z_in[2])
        A = rad_in[0] + rad_in[1] - xr_in * (2 * rad_in[0] + rad_in[1] +
                                             rad_in[2])

        Dval = Symbol('Dval')
        return np.float(nsolve(a/((Dval*xr_in+A)**2+y_in**2)**(0.5) + \
                               b/((Dval*(1-xr_in)-A)**2+y_in**2)**(0.5) + \
                               c/Dval-E_in/self.ke2, Dval, sol_guess))
    def solvey(self, D_in, x_in, E_in, Z_in, sol_guess):
        """
        Get y for given D, x, Energy, particle Z and particle radii.
        
        :type D_in: float
        :param D_in: Distance between heavy and light fission fragment.
        
        :type x_in: float
        :param x_in: x displacement between ternary particle and heavy fragment.
        
        :type E_in: float
        :param E_in: Energy in MeV.
        
        :type Z_in: list of ints
        :param Z_in: Particle proton numbers [Z1, Z2, Z3].

        :type sol_guess: float
        :param sol_guess: Initial guess for solution.
        
        :rtype: float
        :returns: y for current equation.
        """

        #self.ke2 = 1.43996518
        #self.ec = [0, 6.2474511063728828, 5.5901699437494727]

        yval = Symbol('yval')
        try:
            ySolution = nsolve(sp.sqrt((D_in-x_in)**2+yval**2)**5*Z_in[1]*(10.0*(x_in**2+yval**2)**2+self.ec[1]**2*(2*x_in**2-yval**2)) + \
                               sp.sqrt(x_in**2+yval**2)**5*Z_in[2]*(10.0*((D_in-x_in)**2+yval**2)**2+self.ec[2]**2*(2*(D_in-x_in)**2-yval**2)) + \
                              -10.0*(sp.sqrt(x_in**2+yval**2)*sp.sqrt((D_in-x_in)**2+yval**2))**5* \
                                    (E_in/self.ke2 - (Z_in[1]*Z_in[2])*(1.0/D_in+(self.ec[1]**2+self.ec[2]**2)/(5.0*D_in**3)))/Z_in[0],
                               yval, sol_guess)
        except ValueError, e:
            #print(str(e))
            ySolution = 0.0
예제 #27
0
args = "x,y,z"

# really sloppy handling, use argparse
if len(sys.argv) > 1:
    try:
        N = int(sys.argv[1])
    except:
        raise Exception("argument must be an integer N (partition size in RK4)")

else:
    N = 4

# just set verbosity based on size of N
v = (N < 5)
x0 = np.array([[1,1,1]]).T

x_sol = cm_rk4(case_one, args, x0, N, verbose=v)

# now just do some data
F, X = parse_symbolic(case_one, args)

# get F value at x*
F1 = F.subs(list(zip(X, x_sol)))

err = F1.norm() # wow, these methods are great
print("||F(x*)|| = ", err)

x_check = nsolve(F, X, (1,1,1))
print("solution according to sympy.solvers.nsolve:")
print(x_check.T)
예제 #28
0
 def getroot(x0):
     root = nsolve((f1, f2, f3), (x, y, z), x0)
     assert mnorm(F(*root), 1) <= 1.0e-8
     return root
예제 #29
0
def exactSol(x,t=0.2,x0=0,ql=[1.,1.,0.],qr=[0.25,0.1,0.],gamma=1.4):
	''' Gives exact solution to Sod shock tube problem in order to check for accuracies and compare with computational solution.
	Exact solution is given at x points.
	Algorith taken from http://www.phys.lsu.edu/~tohline/PHYS7412/sod.html
	Ref. Sod, G. A. 1978, Journal of Computational Physics, 27, 1-31.
	'''
	
	#Import stuff
	from sympy.solvers import nsolve
	from sympy import Symbol
	
	#Initiate stuff
	
	shape=x.shape
	x=x.flatten()
	p1 = Symbol('p1')
	[rol,pl,vl]=ql
	[ror,pr,vr]=qr
	
	#Calculate wave velocities and values
	
	cleft=(gamma*pl/rol)**(0.5)
	cright=(gamma*pr/ror)**(0.5)
	m=((gamma-1)/(gamma+1))**0.5
	eq=((2*(gamma**0.5))/(gamma-1)*(1-(p1**((gamma-1)/2/gamma))))-((p1-pr)*(((1-(m**2))**2)*((ror*(p1+(m*m*pr)))**(-1)))**(0.5))
	ppost=float(nsolve(eq,p1,0.))
	rpostByrright=((ppost/pr)+(m*m))/(1+((ppost/pr)*(m*m)))
	vpost=(2*(gamma**0.5))/(gamma-1)*(1-(ppost**((gamma-1)/2/gamma)))
	romid=((ppost/pl)**(1/gamma))*rol
	vshock=vpost*(rpostByrright)/(rpostByrright-1)
	ropost=rpostByrright*ror
	pmid=ppost
	vmid=vpost

	#Calculate locations
	x1=x0-(cleft*t)
	x3=x0+(vpost*t)
	x4=x0+(vshock*t)
	ro=[]
	p=[]
	v=[]
	for i in x:
		csound=((m*m)*(x0-i)/t)+((1-(m*m))*cleft)
		vinst=(1-(m*m))*(((i-x0)/t)+cleft)
		roinst=rol*((csound/cleft)**(2/(gamma-1)))
		pinst=pl*((roinst/rol)**(gamma))
		if i<x1:
			ro.append(rol)
			p.append(pl)
			v.append(vl)
		elif (i>=x4):
			ro.append(ror)
			p.append(pr)
			v.append(vr)
		elif (i<x4) and (i>=x3):
			ro.append(ropost)
			p.append(ppost)
			v.append(vpost)
		elif (i<x3) and (((roinst>rol) and (roinst<romid)) or ((roinst<rol) and (roinst>romid))):
			ro.append(roinst)
			p.append(pinst)
			v.append(vinst)
		else:
			ro.append(romid)
			p.append(pmid)
			v.append(vmid)
			
	#Reshape solutions
	ro=np.array(ro).reshape(shape)
	v=np.array(v).reshape(shape)
	p=np.array(p).reshape(shape)
	
	#calculate conserved variables
	rou = ro*v
	ener=p/(gamma-1)/ro

	return([ro,v,p,ener])
예제 #30
0
 def _nsolve(self, guess):
     """
     :returns: Numerical solution to tapdole equations
     """
     sol = nsolve(self._sympy_gradient, self.field_names, guess)
     return np.array([float(s) for s in sol])
예제 #31
0
파일: ex3.py 프로젝트: Sergane/Labs
T = 297
gamma = mu*v**2/(c.R*T)
Sg = 2*mu*v/(c.R*T)*Sv

Ck = (7.0-5.0*gamma)/(2*(gamma-1))*c.R
Sck = c.R/(gamma-1)**2*Sg
print "Cк:", Ck
print "Погрешность Cк:", Sck

a = (7.0-5.0*gamma)/(2*(gamma-1))
# Sa = Sg/(gamma-1)**2
print "a:", a
print "a/2:", a/2

y = Symbol('y')
# последнее число это приблизительный хk
# лучше всего посмотреть на картинке приблизительный х,
# которому соответствует Y=a/2
xk = nsolve(2*y**2*exp(-y)/(1-exp(-y))**2-a, 4.5)
print "xk:", xk
Sxk = 0.05

nu = xk*c.k*T/c.h
Snu = c.k*T/c.h*Sxk
print "Частота:", nu
print "Погрешность частоты:", Snu

Th = c.h*nu/c.k
Sth = T*Sxk
print "Характеристическая темп.:", Th
print "Погрешность хар-кой темп.:", Sth
예제 #32
0
# -*- coding: utf-8 -*-
"""
Created on Tue Apr  7 11:19:00 2020

@author: Alejandro
"""

import numpy as np
import sympy as sp
from decimal import getcontext
from decimal import Decimal

from numpy import sign

from scipy.optimize import fsolve
from sympy.solvers import solve, nsolve, solveset

print("a) f(x)=x^7-x^4+2")
coefs = [1, 0, 0, -1, 0, 0, 0, 2]

print(np.roots(coefs))

x = sp.Symbol('x')

print("b) f(x) = x^7 +cosx -3")

print(nsolve(x**7 + sp.cos(x) - 3, x, 1))
예제 #33
0
def test_issue_6408():
    x = Symbol('x')
    assert nsolve(Piecewise((x, x < 1), (x**2, True)), x, 2) == 0.0
예제 #34
0
def test_nsolve_denominator():
    x = symbols('x')
    # Test that nsolve uses the full expression (numerator and denominator).
    ans = nsolve((x**2 + 3*x + 2)/(x + 2), -2.1)
    # The root -2 was divided out, so make sure we don't find it.
    assert ans == -1.0
예제 #35
0
def test_issue_6408_fail():
    x, y = symbols('x y')
    assert nsolve(Integral(x * y, (x, 0, 5)), y, 2) == 0.0
예제 #36
0
파일: optimise.py 프로젝트: puneet24696/BTP
from __future__ import division
from sympy.solvers import nsolve
from sympy import Symbol
import sympy

x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
a = Symbol('a')

eq1 = a - 0.0071 + 0.0071 * sympy.cosh(-14057.73 / y) + 100 * sympy.sinh(
    -140.5773 / y) / y
eq2 = -50 / (z**2) + a
eq3 = -2354400 / (x**2) + a
eq4 = x + y + z - 1138000
print nsolve((eq1, eq2, eq3, eq4), (x, y, z, a),
             (5000.0, 50000.0, 50.0, 100.0))
예제 #37
0
 def getroot(x0):
     root = nsolve(f, (x, y, z), x0)
     assert mnorm(F(*root), 1) <= 1.e-8
     return root
예제 #38
0
def exactSod(x, t=0.2, x0=0, ql=[1., 1., 0.], qr=[0.25, 0.1, 0.], gamma=1.4):
    ''' Gives exact solution to Sod shock tube problem in order to check for accuracies and compare with computational solution.
	Exact solution is given at x points.
	Algorith taken from http://www.phys.lsu.edu/~tohline/PHYS7412/sod.html
	Ref. Sod, G. A. 1978, Journal of Computational Physics, 27, 1-31.
	'''

    #Import stuff
    from sympy.solvers import nsolve
    from sympy import Symbol

    #Initiate stuff

    shape = x.shape
    x = x.flatten()
    p1 = Symbol('p1')
    [rol, pl, vl] = ql
    [ror, pr, vr] = qr

    #Calculate wave velocities and values

    cleft = (gamma * pl / rol)**(0.5)
    cright = (gamma * pr / ror)**(0.5)
    m = ((gamma - 1) / (gamma + 1))**0.5
    eq = ((2 * (gamma**0.5)) / (gamma - 1) *
          (1 - (p1**((gamma - 1) / 2 / gamma)))) - ((p1 - pr) * ((
              (1 - (m**2))**2) * ((ror * (p1 + (m * m * pr)))**(-1)))**(0.5))
    ppost = float(nsolve(eq, p1, 0.))
    rpostByrright = ((ppost / pr) + (m * m)) / (1 + ((ppost / pr) * (m * m)))
    vpost = (2 *
             (gamma**0.5)) / (gamma - 1) * (1 -
                                            (ppost**((gamma - 1) / 2 / gamma)))
    romid = ((ppost / pl)**(1 / gamma)) * rol
    vshock = vpost * (rpostByrright) / (rpostByrright - 1)
    ropost = rpostByrright * ror
    pmid = ppost
    vmid = vpost

    #Calculate locations
    x1 = x0 - (cleft * t)
    x3 = x0 + (vpost * t)
    x4 = x0 + (vshock * t)
    ro = []
    p = []
    v = []
    for i in x:
        csound = ((m * m) * (x0 - i) / t) + ((1 - (m * m)) * cleft)
        vinst = (1 - (m * m)) * (((i - x0) / t) + cleft)
        roinst = rol * ((csound / cleft)**(2 / (gamma - 1)))
        pinst = pl * ((roinst / rol)**(gamma))
        if i < x1:
            ro.append(rol)
            p.append(pl)
            v.append(vl)
        elif (i >= x4):
            ro.append(ror)
            p.append(pr)
            v.append(vr)
        elif (i < x4) and (i >= x3):
            ro.append(ropost)
            p.append(ppost)
            v.append(vpost)
        elif (i < x3) and (((roinst > rol) and (roinst < romid)) or
                           ((roinst < rol) and (roinst > romid))):
            ro.append(roinst)
            p.append(pinst)
            v.append(vinst)
        else:
            ro.append(romid)
            p.append(pmid)
            v.append(vmid)

    #Reshape solutions
    ro = np.array(ro).reshape(shape)
    v = np.array(v).reshape(shape)
    p = np.array(p).reshape(shape)

    #calculate conserved variables
    rou = ro * v
    ener = p / (gamma - 1) / ro

    return ([ro, v, p, rou, ener])
    def compute_coefficients(self, type, lagrange_point_nr):

        mu = self.mu

        gammaL = Symbol('gammaL')

        if lagrange_point_nr == 1:
            gammaL = nsolve(
                gammaL**5 - (3 - mu) * gammaL**4 + (3 - 2 * mu) * gammaL**3 -
                mu * gammaL**2 + 2 * mu * gammaL - mu, gammaL, 1)
            c2 = 1 / gammaL**3 * ((1)**2 * mu + (-1)**2 *
                                  (1 - mu) * gammaL**(2 + 1) /
                                  (1 - gammaL)**(2 + 1))
            c3 = 1 / gammaL**3 * ((1)**3 * mu + (-1)**3 *
                                  (1 - mu) * gammaL**(3 + 1) /
                                  (1 - gammaL)**(3 + 1))
            c4 = 1 / gammaL**3 * ((1)**4 * mu + (-1)**4 *
                                  (1 - mu) * gammaL**(4 + 1) /
                                  (1 - gammaL)**(4 + 1))

        if lagrange_point_nr == 2:
            gammaL = nsolve(
                gammaL**5 + (3 - mu) * gammaL**4 + (3 - 2 * mu) * gammaL**3 -
                mu * gammaL**2 - 2 * mu * gammaL - mu, gammaL, 1)

            c2 = 1 / gammaL**3 * ((-1)**2 * mu + (-1)**2 *
                                  (1 - mu) * gammaL**(2 + 1) /
                                  (1 + gammaL)**(2 + 1))
            c3 = 1 / gammaL**3 * ((-1)**3 * mu + (-1)**3 *
                                  (1 - mu) * gammaL**(3 + 1) /
                                  (1 + gammaL)**(3 + 1))
            c4 = 1 / gammaL**3 * ((-1)**4 * mu + (-1)**4 *
                                  (1 - mu) * gammaL**(4 + 1) /
                                  (1 + gammaL)**(4 + 1))
        print('Gamma L: ' + str(gammaL))
        l = Symbol('l')
        l = nsolve(l**4 + (c2 - 2) * l**2 - (c2 - 1) * (1 + 2 * c2), l, 1)

        print('l: ' + str(l))

        # print(np.sqrt(1-c2/2+1/2*np.sqrt((c2-2)**2+4*(c2-1)*(1+2*c2))))

        k = 2 * l / (l**2 + 1 - c2)
        delta = l**2 - c2

        d1 = 3 * l**2 / k * (k * (6 * l**2 - 1) - 2 * l)
        d2 = 8 * l**2 / k * (k * (11 * l**2 - 1) - 2 * l)

        a21 = 3 * c3 * (k**2 - 2) / (4 * (1 + 2 * c2))
        a22 = 3 * c3 / (4 * (1 + 2 * c2))
        a23 = -3 * c3 * l / (4 * k * d1) * (3 * k**3 * l - 6 * k * (k - l) + 4)
        a24 = -3 * c3 * l / (4 * k * d1) * (2 + 3 * k * l)

        b21 = -3 * c3 * l / (2 * d1) * (3 * k * l - 4)
        b22 = 3 * c3 * l / d1

        d21 = -c3 / (2 * l**2)

        a31 = -9 * l / (4 * d2) * (4 * c3 * (k * a23 - b21) + k * c4 *
                                   (4 + k**2)) + (9 * l**2 + 1 - c2) / (
                                       2 * d2) * (3 * c3 *
                                                  (2 * a23 - k * b21) + c4 *
                                                  (2 + 3 * k**2))
        a32 = -1 / d2 * (9 * l / 4 * (4 * c3 *
                                      (k * a24 - b22) + k * c4) + 3 / 2 *
                         (9 * l**2 + 1 - c2) *
                         (c3 * (k * b22 + d21 - 2 * a24) - c4))

        b31 = 3 / (8 * d2) * (8 * l * (3 * c3 * (k * b21 - 2 * a23) - c4 *
                                       (2 + 3 * k**2)) +
                              (9 * l**2 + 1 + 2 * c2) *
                              (4 * c3 * (k * a23 - b21) + k * c4 * (4 + k**2)))
        b32 = 1 / d2 * (9 * l * (c3 * (k * b22 + d21 - 2 * a24) - c4) + 3 / 8 *
                        (9 * l**2 + 1 + 2 * c2) * (4 * c3 *
                                                   (k * a24 - b22) + k * c4))

        d31 = 3 / (64 * l**2) * (4 * c3 * a24 + c4)
        d32 = 3 / (64 * l**2) * (4 * c3 * (a23 - d21) + c4 * (4 + k**2))

        a1 = -3 / 2 * c3 * (2 * a21 + a23 + 5 * d21) - 3 / 8 * c4 * (12 - k**2)
        a2 = 3 / 2 * c3 * (a24 - 2 * a22) + 9 / 8 * c4

        s1 = 1 / (2 * l *
                  (l * (1 + k**2) - 2 * k)) * (3 / 2 * c3 *
                                               (2 * a21 * (k**2 - 2) - a23 *
                                                (k**2 + 2) - 2 * k * b21) -
                                               3 / 8 * c4 *
                                               (3 * k**4 - 8 * k**2 + 8))
        s2 = 1 / (2 * l * (l * (1 + k**2) - 2 * k)) * (
            3 / 2 * c3 * (2 * a22 * (k**2 - 2) + a24 *
                          (k**2 + 2) + 2 * k * b22 + 5 * d21) + 3 / 8 * c4 *
            (12 - k**2))

        l1 = a1 + 2 * l**2 * s1
        l2 = a2 + 2 * l**2 * s2

        column_name = 'L' + str(lagrange_point_nr) + ' Orbits'

        df = pd.DataFrame(
            {
                column_name: [
                    gammaL, l, k, delta, c2, c3, c4, s1, s2, l1, l2, a1, a2,
                    d1, d2, a21, a22, a23, a24, a31, a32, b21, b22, b31, b32,
                    d21, d31, d32
                ]
            },
            index=[
                'gammaL', 'l', 'k', 'delta', 'c2', 'c3', 'c4', 's1', 's2',
                'l1', 'l2', 'a1', 'a2', 'd1', 'd2', 'a21', 'a22', 'a23', 'a24',
                'a31', 'a32', 'b21', 'b22', 'b31', 'b32', 'd21', 'd31', 'd32'
            ])

        if type == 'horizontal':
            Ax = 1e-3
            # Ax = 1e-4
            Az = 0
            pass
        if type == 'vertical':
            Ax = 0
            # Az = 5e-4
            Az = 2e-1
            # Az = 1e-6
            pass
        if type == 'halo':
            # Az = 1.2e-1
            # Az = 1.6e-1
            Az = 1.1e-1
            Ax = np.sqrt(float((-delta - l2 * Az**2) / l1))
            pass
        print('Ax: ' + str(Ax))
        print('Az: ' + str(Az))
        omega1 = 0
        omega2 = s1 * Ax**2 + s2 * Az**2
        omega = 1 + omega1 + omega2
        print('Omega: ' + str(omega))
        T = 2 * math.pi / (l * omega)
        print('T: ' + str(T) + '\n')

        tau1 = 0
        deltan = 2 - 3

        x = a21 * Ax**2 + a22 * Az**2 - Ax * math.cos(tau1) + (
            a23 * Ax**2 - a24 * Az**2) * math.cos(2 * tau1) + (
                a31 * Ax**3 - a32 * Ax * Az**2) * math.cos(3 * tau1)
        y = k * Ax * math.sin(tau1) + (b21 * Ax**2 - b22 * Az**2) * math.sin(
            2 * tau1) + (b31 * Ax**3 - b32 * Ax * Az**2) * math.sin(3 * tau1)
        z = deltan * Az * math.cos(tau1) + deltan * d21 * Ax * Az * (
            math.cos(2 * tau1) -
            3) + deltan * (d32 * Az * Ax**2 - d31 * Az**3) * math.cos(3 * tau1)
        xdot = l * Ax * math.sin(tau1) - 2 * l * (
            a23 * Ax**2 - a24 * Az**2) * math.sin(2 * tau1) - 3 * l * (
                a31 * Ax**3 - a32 * Ax * Az**2) * math.sin(3 * tau1)
        ydot = l * (k * Ax * math.cos(tau1) + 2 *
                    (b21 * Ax**2 - b22 * Az**2) * math.cos(2 * tau1) + 3 *
                    (b31 * Ax**3 - b32 * Ax * Az**2) * math.cos(3 * tau1))
        zdot = -l * deltan * Az * math.sin(
            tau1) - 2 * l * deltan * d21 * Ax * Az * math.sin(
                2 * tau1) - 3 * l * deltan * (d32 * Az * Ax**2 -
                                              d31 * Az**3) * math.sin(3 * tau1)

        print('x: ' + str(x))
        # print('y: ' + str(y))
        # print('z: ' + str(z))
        # print('xdot: ' + str(xdot))
        # print('ydot: ' + str(ydot))
        # print('zdot: ' + str(zdot) + '\n')

        if lagrange_point_nr == 1:
            print('X: ' + str((x - 1) * gammaL + 1 - mu))
            pass
        if lagrange_point_nr == 2:
            print('X: ' + str((x + 1) * gammaL + 1 - mu))
            pass

        print('Y: ' + str(y * gammaL))
        print('Z: ' + str(z * gammaL))
        print('Xdot: ' + str(xdot * gammaL))
        # print('Ydot: ' + str(ydot * gammaL))
        print('Ydot: ' + str(ydot * gammaL * omega))
        print('Zdot: ' + str(zdot * gammaL) + '\n')

        if lagrange_point_nr == 1:
            print(str((x - 1) * gammaL + 1 - mu))
            pass
        if lagrange_point_nr == 2:
            print(str((x + 1) * gammaL + 1 - mu))
            pass
        print(str(z * gammaL))
        print(str(ydot * gammaL * omega))
        print(T)
        # print('T: ' + str(T / self.n / 86400))

        # print(df)
        # print(self.n)
        # print(omega)
        return x, y, z
예제 #40
0
def leaf_temperature(g,
                     meteo,
                     t_soil,
                     t_sky_eff,
                     t_init=None,
                     form_factors=None,
                     gbh=None,
                     ev=None,
                     ei=None,
                     solo=True,
                     ff_type=True,
                     leaf_lbl_prefix='L',
                     max_iter=100,
                     t_error_crit=0.01,
                     t_step=0.5):
    """Computes the temperature of each individual leaf and soil elements.

    Args:
        g: a multiscale tree graph object
        meteo (DataFrame): forcing meteorological variables
        t_soil (float): [°C] soil surface temperature
        t_sky_eff (float): [°C] effective sky temperature
        t_init(float or dict): [°C] temperature used for initialisation
        form_factors(3-tuple of float or dict): form factors for soil, sky and leaves.
            if None (default) (0.5, 0.5, 0.5) is used for all leaves
        gbh (float or dict): [W m-2 K-1] boundary layer conductance for heat
            if None (default) a default model is called with length=10cm and wind_speed as found in meteo
        ev (float or dict): [mol m-2 s-1] evaporation flux
            if None (default) evaporation is set to zero for all leaves
        ei (float or dict): [umol m-2 s-1] photosynthetically active radition (PAR) incident on leaves
            if None (default) PAR is set to zero for all leaves
        solo (bool):
            if True (default), calculates energy budget for each element assuming the temperatures of surrounding
                leaves as constant (from previous calculation step)
            if False, computes simultaneously all temperatures using `sympy.solvers.nsolve` (**very costly!!!**)
        ff_type (bool): form factor type flag. If true fform factor for a given leaf is expected to be a single value, or a dict of ff otherwxie
        leaf_lbl_prefix (str): the prefix of the leaf label
        max_iter (int): maximum allowed iteration (used only when :arg:`solo` is True)
        t_error_crit (float): [°C] maximum allowed error in leaf temperature (used only when :arg:`solo` is True)
        t_step (float): [°C] maximum temperature step between two consecutive iterations

    Returns:
        (dict): [°C] the tempearture of individual leaves given as the dictionary keys
        (int): [-] the number of iterations (not None only when :arg:`solo` is True)

    """

    leaves = get_leaves(g, leaf_lbl_prefix)
    it = 0

    if t_init is None:
        t_init = meteo.Tac[0]
    if form_factors is None:
        form_factors = 0.5, 0.5, 0.5
    if gbh is None:
        gbh = _gbH(0.1, meteo.u[0])
    if ev is None:
        ev = 0
    if ei is None:
        ei = 0

    k_soil, k_sky, k_leaves = form_factors
    properties = {}
    for what in ('t_init', 'gbh', 'ev', 'ei', 'k_soil', 'k_sky', 'k_leaves'):
        val = eval(what)
        if isinstance(val, dict):
            properties[what] = val
        else:
            properties[what] = {vid: val for vid in leaves}

    # macro-scale climatic data
    temp_sky = utils.celsius_to_kelvin(t_sky_eff)
    temp_air = utils.celsius_to_kelvin(meteo.Tac[0])
    temp_soil = utils.celsius_to_kelvin(t_soil)

    # initialisation
    t_prev = properties['t_init']

    # iterative calculation of leaves temperature
    if solo:
        t_error_trace = []
        it_step = t_step
        for it in range(max_iter):
            t_dict = {}

            for vid in leaves:
                shortwave_inc = properties['ei'][vid] / (0.48 * 4.6
                                                         )  # Ei not Eabs

                ff_sky = properties['k_sky'][vid]
                ff_leaves = properties['k_leaves'][vid]
                ff_soil = properties['k_soil'][vid]

                gb_h = properties['gbh'][vid]
                evap = properties['ev'][vid]
                t_leaf = t_prev[vid]

                if not ff_type:
                    longwave_grain_from_leaves = -sigma * sum([
                        ff_leaves[ivid] *
                        (utils.celsius_to_kelvin(t_prev[ivid]))**4
                        for ivid in ff_leaves
                    ])
                else:
                    longwave_grain_from_leaves = ff_leaves * sigma * (
                        utils.celsius_to_kelvin(t_leaf))**4

                def _VineEnergyX(t_leaf):
                    shortwave_abs = a_glob * shortwave_inc
                    longwave_net = e_leaf * (ff_sky * e_sky * sigma * temp_sky ** 4 +
                                             e_leaf * longwave_grain_from_leaves +
                                             ff_soil * e_soil * sigma * temp_soil ** 4) \
                                   - 2 * e_leaf * sigma * t_leaf ** 4
                    latent_heat_loss = -lambda_ * evap
                    sensible_heat_net = -gb_h * (t_leaf - temp_air)
                    energy_balance = shortwave_abs + longwave_net + latent_heat_loss + sensible_heat_net
                    return energy_balance

                t_leaf0 = utils.kelvin_to_celsius(
                    optimize.newton_krylov(_VineEnergyX,
                                           utils.celsius_to_kelvin(t_leaf)))

                t_dict[vid] = t_leaf0

            t_new = t_dict

            # evaluation of leaf temperature conversion criterion
            error_dict = {vtx: abs(t_prev[vtx] - t_new[vtx]) for vtx in leaves}

            t_error = max(error_dict.values())
            t_error_trace.append(t_error)

            if t_error < t_error_crit:
                break
            else:
                try:
                    if abs(t_error_trace[-1] -
                           t_error_trace[-2]) < t_error_crit:
                        it_step = max(0.01, it_step / 2.)
                except IndexError:
                    pass

                t_next = {}
                for vtx_id in t_new.keys():
                    tx = t_prev[vtx_id] + it_step * (t_new[vtx_id] -
                                                     t_prev[vtx_id])
                    t_next[vtx_id] = tx

                t_prev = t_next

    # matrix iterative calculation of leaves temperature ('not solo' case)
    else:
        it = 1
        t_lst = []
        t_dict = {vid: Symbol('t%d' % vid) for vid in leaves}

        eq_lst = []
        t_leaf_lst = []
        for vid in leaves:
            shortwave_inc = properties['ei'][vid] / (0.48 * 4.6)  # Ei not Eabs
            ff_sky = properties['k_sky'][vid]
            ff_leaves = properties['k_leaves'][vid]

            ff_soil = properties['k_soil'][vid]
            gb_h = properties['gbh'][vid]
            evap = properties['ev'][vid]
            t_leaf = t_prev[vid]

            t_leaf_lst.append(t_leaf)
            t_lst.append(t_dict[vid])

            eq_aux = 0.
            for ivid in ff_leaves:
                if not g.node(ivid).label.startswith('soil'):
                    eq_aux += -ff_leaves[ivid] * ((t_dict[ivid])**4)

            eq = (a_glob * shortwave_inc + e_leaf * sigma *
                  (ff_sky * e_sky *
                   (temp_sky**4) + e_leaf * eq_aux + ff_soil * e_soil *
                   (temp_sky**4) - 2 * (t_dict[vid])**4) - lambda_ * evap -
                  gb_h * Cp * (t_dict[vid] - temp_air))

            eq_lst.append(eq)

        tt = time.time()
        t_leaf0_lst = nsolve(eq_lst, t_lst, t_leaf_lst, verify=False) - 273.15
        print("---%s seconds ---" % (time.time() - tt))

        t_new = {}
        for ivid, vid in enumerate(leaves):
            t_new[vid] = float(t_leaf0_lst[ivid])
            ivid += 1

    return t_new, it
예제 #41
0
def test_issue_14950():
    x = Matrix(symbols('t s'))
    x0 = Matrix([17, 23])
    eqn = x + x0
    assert nsolve(eqn, x, x0) == -x0
    assert nsolve(eqn.T, x.T, x0.T) == -x0
예제 #42
0
def test_issue_6408():
    x = Symbol('x')
    assert nsolve(Piecewise((x, x < 1), (x**2, True)), x, 2) == 0.0
예제 #43
0
def test_nsolve_rational():
    x = symbols('x')
    assert nsolve(x - Rational(1, 3), 0, prec=100) == Rational(1, 3).evalf(100)
예제 #44
0
    def generate(self):
        """
        Generate initial configurations.
        """

        minTol = 0.0001

        dcount = 0
        simTime = time()
        timeStamp = datetime.now().strftime("%Y-%m-%d/%H.%M.%S")

        simulationNumber = 0
        totSims = 0

        dcontact = self._sa.ab[0] + self._sa.ab[4]
        xcontact = self._sa.ab[0] + self._sa.ab[2]
        dsaddle = 1.0 / (np.sqrt(self._sa.Z[1] / self._sa.Z[2]) + 1.0)
        xsaddle = 1.0 / (np.sqrt(self._sa.Z[2] / self._sa.Z[1]) + 1.0)

        Eav = self._sa.Q - np.sum(self._Ekin0) - minTol

        # Solve Dmin
        Dsym = Symbol('Dsym')
        Dmin = np.float(nsolve(Dsym - (self._sa.Z[0]*self._sa.Z[1]/xsaddle + \
                                       self._sa.Z[0]*self._sa.Z[2]/dsaddle + \
                                       self._sa.Z[1]*self._sa.Z[2] \
                                      )*1.43996518/(Eav), Dsym, 18.0))
        Dmax = Dmin + self._Dmax

        # Solve D_tpl_contact and D_tph_contact
        A = ((Eav) / 1.43996518 -
             self._sa.Z[0] * self._sa.Z[2] / dcontact) / self._sa.Z[1]
        D_tpl_contact = np.float(nsolve(Dsym**2*A - \
                                        Dsym*(A*dcontact + self._sa.Z[0] +
                                              self._sa.Z[2]) + \
                                        self._sa.Z[2]*dcontact, Dsym, 26.0))
        A = ((Eav) / 1.43996518 -
             self._sa.Z[0] * self._sa.Z[1] / xcontact) / self._sa.Z[2]
        D_tph_contact = np.float(nsolve(Dsym**2*A - \
                                        Dsym*(A*xcontact + self._sa.Z[0] +
                                              self._sa.Z[1]) + \
                                        self._sa.Z[1]*xcontact, Dsym, 30.0))

        if self._config == 'max':
            ekins = np.linspace(0, self._Ekin0, self._sims)
            D = []
            for i in range(0, self._sims):
                Eav = self._sa.Q - ekins[i] - minTol
                A = ((Eav) / 1.43996518 -
                     self._sa.Z[0] * self._sa.Z[1] / xcontact) / self._sa.Z[2]
                D_tph_contact = np.float(nsolve(Dsym**2*A - \
                                                Dsym*(A*xcontact + self._sa.Z[0] +
                                                      self._sa.Z[1]) + \
                                                self._sa.Z[1]*xcontact, Dsym, 30.0))
                """Dmin = np.float(nsolve(Dsym - (self._sa.Z[0]*self._sa.Z[1]/xsaddle + \
                                               self._sa.Z[0]*self._sa.Z[2]/dsaddle + \
                                               self._sa.Z[1]*self._sa.Z[2] \
                                              )*1.43996518/(Eav), Dsym, 18.0))
                D.append(Dmin)
                xs.append([xsaddle*Dmin])"""
                D.append(D_tph_contact)
            xs = [[xcontact + minTol]] * self._sims
            ys = [0] * self._sims
            print D[0]
            print D[-1]
            ekins2 = np.linspace(0, 192, self._sims)
            import matplotlib.pyplot as plt
            #plt.plot(ekins2, ekins2/(self._sa.mff[0]/self._sa.mff[1] + 1.0))
            #plt.plot(ekins2, ekins2/(self._sa.mff[1]/self._sa.mff[0] + 1.0))
            plt.plot(ekins, D)
            plt.show()
        elif self._config == 'triad':
            D = [Dmin, D_tpl_contact, D_tph_contact]
            xs = [[xsaddle * Dmin], [D[1] - dcontact - minTol],
                  [xcontact + minTol]]
            ys = [0] * 3
            print D
        else:
            D = np.linspace(Dmin, Dmax, self._sims)

            xs = [0] * self._sims
            ys = [0] * self._sims

            xs[0] = [xsaddle * D[0]]

            for i in range(1, len(D)):
                A = ((self._sa.Q - minTol) / 1.43996518 -
                     self._sa.Z[1] * self._sa.Z[2] / D[i]) / self._sa.Z[0]
                p = [
                    A, (self._sa.Z[2] - self._sa.Z[1] - A * D[i]),
                    D[i] * self._sa.Z[1]
                ]
                sols = np.roots(p)
                #print(str(D[i])+'\t'),
                #print(sols),

                # Check 2 sols
                if len(sols) != 2:
                    raise Exception('Wrong amount of solutions: ' +
                                    str(len(sols)))
                # Check reals
                #if np.iscomplex(sols[0]):
                #    raise ValueError('Complex root: '+str(sols[0]))
                #if np.iscomplex(sols[1]):
                #    raise ValueError('Complex root: '+str(sols[1]))

                xmin = max(sols[1], self._sa.ab[0] + self._sa.ab[2] + minTol)
                xmax = min(sols[0],
                           D[i] - (self._sa.ab[0] + self._sa.ab[4] + minTol))
                """
                s1 = '_'
                s2 = '_'
                if xmin == self._sa.ab[0]+self._sa.ab[2]+minTol:
                    s1 = 'o'
                if xmax == D[i]-(self._sa.ab[0]+self._sa.ab[4]+minTol):
                    s2 = 'o'
                print(s1+s2)
                """

                # Check inside neck
                if xmin < (self._sa.ab[0] + self._sa.ab[2]):
                    raise ValueError('Solution overlapping with HF:')
                if xmin > D[i] - (self._sa.ab[0] + self._sa.ab[4]):
                    raise ValueError('Solution overlapping with LF:')
                if xmax < (self._sa.ab[0] + self._sa.ab[2]):
                    raise ValueError('Solution overlapping with HF:')
                if xmax > D[i] - (self._sa.ab[0] + self._sa.ab[4]):
                    raise ValueError('Solution overlapping with LF:')

                xs[i] = np.arange(xmin, xmax, self._dx)

        # Assign y-values
        for i in range(0, len(D)):
            ys[i] = [0] * len(xs[i])
            for j in range(0, len(xs[i])):
                if self._yMax == 0 or self._dy == 0:
                    ys[i][j] = [0]
                else:
                    ys[i][j] = np.arange(0, self._yMax, self._dy)

        # Count total simulations
        for i in range(0, len(D)):
            for j in range(0, len(xs[i])):
                totSims += len(ys[i][j])

        ENi_max = 0
        for i in range(0, len(D)):
            for j in range(0, len(xs[i])):
                for k in range(0, len(ys[i][j])):
                    simulationNumber += 1
                    r = [
                        0.0, ys[i][j][k], -xs[i][j], 0.0, D[i] - xs[i][j], 0.0
                    ]

                    v = [0.0] * 6

                    if self._config == 'max':
                        v[0] = np.sqrt(2 * ekins[i] /
                                       (self._sa.mff[0]**2 / self._sa.mff[1] +
                                        self._sa.mff[0]))
                        v[2] = -np.sqrt(2 * ekins[i] /
                                        (self._sa.mff[1]**2 / self._sa.mff[0] +
                                         self._sa.mff[1]))

                    sim = SimulateTrajectory(sa=self._sa, r_in=r, v_in=v)
                    e, outString, ENi = sim.run(
                        simulationNumber=simulationNumber, timeStamp=timeStamp)
                    if ENi > ENi_max:
                        ENi_max = ENi
                    #sim.plotTrajectories()
                    if e == 0:
                        print("S: " + str(simulationNumber) + "/~" +
                              str(totSims) + "\t" + str(r) + "\t" + outString)
        print("Total simulation time: " + str(time() - simTime) + "sec")
        print("Maximum Nickel Energy: " + str(ENi_max) + " MeV")
예제 #45
0
def test_issue_14950():
    x = Matrix(symbols('t s'))
    x0 = Matrix([17, 23])
    eqn = x + x0
    assert nsolve(eqn, x, x0) == -x0
    assert nsolve(eqn.T, x.T, x0.T) == -x0
예제 #46
0
 def getroot(x0):
     root = nsolve(f, (x, y, z), x0)
     assert mnorm(F(*root), 1) <= 1.e-8
     return root
예제 #47
0
def test_nsolve_denominator():
    x = symbols('x')
    # Test that nsolve uses the full expression (numerator and denominator).
    ans = nsolve((x**2 + 3 * x + 2) / (x + 2), -2.1)
    # The root -2 was divided out, so make sure we don't find it.
    assert ans == -1.0
예제 #48
0
def test_issue_6408_fail():
    x, y = symbols('x y')
    assert nsolve(Integral(x*y, (x, 0, 5)), y, 2) == 0.0
예제 #49
0
def test_nsolve_rational():
    x = symbols('x')
    assert nsolve(x - Rational(1, 3), 0, prec=100) == Rational(1, 3).evalf(100)