How to use bounds method in ATX

Best Python code snippet using ATX

test_util.py

Source:test_util.py Github

copy

Full Screen

1from sympy import (Symbol, S, exp, log, sqrt, oo, E, zoo, pi, tan, sin, cos,2 cot, sec, csc, Abs, symbols, I, re, simplify,3 expint, Rational)4from sympy.calculus.util import (function_range, continuous_domain, not_empty_in,5 periodicity, lcim, AccumBounds, is_convex,6 stationary_points, minimum, maximum)7from sympy.core import Add, Mul, Pow8from sympy.sets.sets import (Interval, FiniteSet, EmptySet, Complement,9 Union)10from sympy.testing.pytest import raises11from sympy.abc import x12a = Symbol('a', real=True)13def test_function_range():14 x, y, a, b = symbols('x y a b')15 assert function_range(sin(x), x, Interval(-pi/2, pi/2)16 ) == Interval(-1, 1)17 assert function_range(sin(x), x, Interval(0, pi)18 ) == Interval(0, 1)19 assert function_range(tan(x), x, Interval(0, pi)20 ) == Interval(-oo, oo)21 assert function_range(tan(x), x, Interval(pi/2, pi)22 ) == Interval(-oo, 0)23 assert function_range((x + 3)/(x - 2), x, Interval(-5, 5)24 ) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo))25 assert function_range(1/(x**2), x, Interval(-1, 1)26 ) == Interval(1, oo)27 assert function_range(exp(x), x, Interval(-1, 1)28 ) == Interval(exp(-1), exp(1))29 assert function_range(log(x) - x, x, S.Reals30 ) == Interval(-oo, -1)31 assert function_range(sqrt(3*x - 1), x, Interval(0, 2)32 ) == Interval(0, sqrt(5))33 assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals34 ) == FiniteSet(0)35 assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals36 ) == FiniteSet(y)37 assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4))38 ) == Union(Interval(-sin(3), 1), FiniteSet(sin(4)))39 assert function_range(cos(x), x, Interval(-oo, -4)40 ) == Interval(-1, 1)41 assert function_range(cos(x), x, S.EmptySet) == S.EmptySet42 raises(NotImplementedError, lambda : function_range(43 exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals))44 raises(NotImplementedError, lambda : function_range(45 sin(x) + x, x, S.Reals)) # issue 1327346 raises(NotImplementedError, lambda : function_range(47 log(x), x, S.Integers))48 raises(NotImplementedError, lambda : function_range(49 sin(x)/2, x, S.Naturals))50def test_continuous_domain():51 x = Symbol('x')52 assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi)53 assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \54 Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True),55 Interval(pi*Rational(3, 2), 2*pi, True, False))56 assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \57 Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True))58 assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \59 Interval(Rational(1, 4), oo, True, True)60 assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True)61 assert continuous_domain(1/x - 2, x, S.Reals) == \62 Union(Interval.open(-oo, 0), Interval.open(0, oo))63 assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \64 Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo))65 domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals)66 assert not domain.contains(3*pi/2)67 assert domain.contains(5)68def test_not_empty_in():69 assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \70 Interval(S.Half, 2, True, False)71 assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \72 Union(Interval(-sqrt(2), -1), Interval(1, 2))73 assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \74 Union(Interval(-sqrt(17)/2 - S.Half, -2),75 Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4))76 assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \77 Complement(S.Reals, FiniteSet(1))78 assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \79 Complement(S.Reals, FiniteSet(1))80 assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \81 Complement(S.Reals, FiniteSet(1))82 assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \83 Interval(-oo, oo)84 assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \85 Interval(S(3)/2, 2)86 assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \87 Complement(S.Reals, FiniteSet(-1, 1))88 assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True),89 Interval(4, 5))), x) == \90 Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True),91 Interval(1, 3, True, True), Interval(4, 5))92 assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet93 assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \94 Union(Interval(-2, -1, True, False), Interval(2, oo))95 raises(ValueError, lambda: not_empty_in(x))96 raises(ValueError, lambda: not_empty_in(Interval(0, 1), x))97 raises(NotImplementedError,98 lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a))99def test_periodicity():100 x = Symbol('x')101 y = Symbol('y')102 z = Symbol('z', real=True)103 assert periodicity(sin(2*x), x) == pi104 assert periodicity((-2)*tan(4*x), x) == pi/4105 assert periodicity(sin(x)**2, x) == 2*pi106 assert periodicity(3**tan(3*x), x) == pi/3107 assert periodicity(tan(x)*cos(x), x) == 2*pi108 assert periodicity(sin(x)**(tan(x)), x) == 2*pi109 assert periodicity(tan(x)*sec(x), x) == 2*pi110 assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2111 assert periodicity(tan(x) + cot(x), x) == pi112 assert periodicity(sin(x) - cos(2*x), x) == 2*pi113 assert periodicity(sin(x) - 1, x) == 2*pi114 assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi115 assert periodicity(exp(sin(x)), x) == 2*pi116 assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi117 assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi118 assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi119 assert periodicity(tan(sin(2*x)), x) == pi120 assert periodicity(2*tan(x)**2, x) == pi121 assert periodicity(sin(x%4), x) == 4122 assert periodicity(sin(x)%4, x) == 2*pi123 assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3)124 assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1)125 assert periodicity((x**2+1) % x, x) is None126 assert periodicity(sin(re(x)), x) == 2*pi127 assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero128 assert periodicity(tan(x), y) is S.Zero129 assert periodicity(sin(x) + I*cos(x), x) == 2*pi130 assert periodicity(x - sin(2*y), y) == pi131 assert periodicity(exp(x), x) is None132 assert periodicity(exp(I*x), x) == 2*pi133 assert periodicity(exp(I*z), z) == 2*pi134 assert periodicity(exp(z), z) is None135 assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi136 assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi137 assert periodicity(exp(sin(z)), z) == 2*pi138 assert periodicity(exp(2*I*z), z) == pi139 assert periodicity(exp(z + I*sin(z)), z) is None140 assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi141 assert periodicity(log(x), x) is None142 assert periodicity(exp(x)**sin(x), x) is None143 assert periodicity(sin(x)**y, y) is None144 assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi145 assert all(periodicity(Abs(f(x)), x) == pi for f in (146 cos, sin, sec, csc, tan, cot))147 assert periodicity(Abs(sin(tan(x))), x) == pi148 assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi149 assert periodicity(sin(x) > S.Half, x) == 2*pi150 assert periodicity(x > 2, x) is None151 assert periodicity(x**3 - x**2 + 1, x) is None152 assert periodicity(Abs(x), x) is None153 assert periodicity(Abs(x**2 - 1), x) is None154 assert periodicity((x**2 + 4)%2, x) is None155 assert periodicity((E**x)%3, x) is None156 assert periodicity(sin(expint(1, x))/expint(1, x), x) is None157def test_periodicity_check():158 x = Symbol('x')159 y = Symbol('y')160 assert periodicity(tan(x), x, check=True) == pi161 assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi162 assert periodicity(sec(x), x) == 2*pi163 assert periodicity(sin(x*y), x) == 2*pi/abs(y)164 assert periodicity(Abs(sec(sec(x))), x) == pi165def test_lcim():166 from sympy import pi167 assert lcim([S.Half, S(2), S(3)]) == 6168 assert lcim([pi/2, pi/4, pi]) == pi169 assert lcim([2*pi, pi/2]) == 2*pi170 assert lcim([S.One, 2*pi]) is None171 assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E172def test_is_convex():173 assert is_convex(1/x, x, domain=Interval(0, oo)) == True174 assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False175 assert is_convex(x**2, x, domain=Interval(0, oo)) == True176 assert is_convex(log(x), x) == False177 raises(NotImplementedError, lambda: is_convex(log(x), x, a))178def test_stationary_points():179 x, y = symbols('x y')180 assert stationary_points(sin(x), x, Interval(-pi/2, pi/2)181 ) == {-pi/2, pi/2}182 assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4)183 ) == EmptySet()184 assert stationary_points(tan(x), x,185 ) == EmptySet()186 assert stationary_points(sin(x)*cos(x), x, Interval(0, pi)187 ) == {pi/4, pi*Rational(3, 4)}188 assert stationary_points(sec(x), x, Interval(0, pi)189 ) == {0, pi}190 assert stationary_points((x+3)*(x-2), x191 ) == FiniteSet(Rational(-1, 2))192 assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5)193 ) == EmptySet()194 assert stationary_points((x**2+3)/(x-2), x195 ) == {2 - sqrt(7), 2 + sqrt(7)}196 assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5)197 ) == {2 + sqrt(7)}198 assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals199 ) == FiniteSet(-2, 0, Rational(5, 4))200 assert stationary_points(exp(x), x201 ) == EmptySet()202 assert stationary_points(log(x) - x, x, S.Reals203 ) == {1}204 assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))205 ) == {0, -pi, pi}206 assert stationary_points(y, x, S.Reals207 ) == S.Reals208 assert stationary_points(y, x, S.EmptySet) == S.EmptySet209def test_maximum():210 x, y = symbols('x y')211 assert maximum(sin(x), x) is S.One212 assert maximum(sin(x), x, Interval(0, 1)) == sin(1)213 assert maximum(tan(x), x) is oo214 assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One215 assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half216 assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))217 ) == sqrt(2)/4218 assert maximum((x+3)*(x-2), x) is oo219 assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14)220 assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7)221 assert simplify(maximum(-x**4-x**3+x**2+10, x)222 ) == 41*sqrt(41)/512 + Rational(5419, 512)223 assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2)224 assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne225 assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))226 ) is S.One227 assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2)228 assert maximum(y, x, S.Reals) == y229 raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet))230 raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet))231 raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet))232 raises(ValueError, lambda : maximum(sin(x), sin(x)))233 raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet))234 raises(ValueError, lambda : maximum(sin(x), S.One))235def test_minimum():236 x, y = symbols('x y')237 assert minimum(sin(x), x) is S.NegativeOne238 assert minimum(sin(x), x, Interval(1, 4)) == sin(4)239 assert minimum(tan(x), x) is -oo240 assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne241 assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2)242 assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))243 ) == -sqrt(2)/4244 assert minimum((x+3)*(x-2), x) == Rational(-25, 4)245 assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2)246 assert minimum(x**4-x**3+x**2+10, x) == S(10)247 assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2)248 assert minimum(log(x) - x, x, S.Reals) is -oo249 assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))250 ) is S.NegativeOne251 assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2)252 assert minimum(y, x, S.Reals) == y253 raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet))254 raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet))255 raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet))256 raises(ValueError, lambda : minimum(sin(x), sin(x)))257 raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet))258 raises(ValueError, lambda : minimum(sin(x), S.One))259def test_AccumBounds():260 assert AccumBounds(1, 2).args == (1, 2)261 assert AccumBounds(1, 2).delta is S.One262 assert AccumBounds(1, 2).mid == Rational(3, 2)263 assert AccumBounds(1, 3).is_real == True264 assert AccumBounds(1, 1) is S.One265 assert AccumBounds(1, 2) + 1 == AccumBounds(2, 3)266 assert 1 + AccumBounds(1, 2) == AccumBounds(2, 3)267 assert AccumBounds(1, 2) + AccumBounds(2, 3) == AccumBounds(3, 5)268 assert -AccumBounds(1, 2) == AccumBounds(-2, -1)269 assert AccumBounds(1, 2) - 1 == AccumBounds(0, 1)270 assert 1 - AccumBounds(1, 2) == AccumBounds(-1, 0)271 assert AccumBounds(2, 3) - AccumBounds(1, 2) == AccumBounds(0, 2)272 assert x + AccumBounds(1, 2) == Add(AccumBounds(1, 2), x)273 assert a + AccumBounds(1, 2) == AccumBounds(1 + a, 2 + a)274 assert AccumBounds(1, 2) - x == Add(AccumBounds(1, 2), -x)275 assert AccumBounds(-oo, 1) + oo == AccumBounds(-oo, oo)276 assert AccumBounds(1, oo) + oo is oo277 assert AccumBounds(1, oo) - oo == AccumBounds(-oo, oo)278 assert (-oo - AccumBounds(-1, oo)) is -oo279 assert AccumBounds(-oo, 1) - oo is -oo280 assert AccumBounds(1, oo) - oo == AccumBounds(-oo, oo)281 assert AccumBounds(-oo, 1) - (-oo) == AccumBounds(-oo, oo)282 assert (oo - AccumBounds(1, oo)) == AccumBounds(-oo, oo)283 assert (-oo - AccumBounds(1, oo)) is -oo284 assert AccumBounds(1, 2)/2 == AccumBounds(S.Half, 1)285 assert 2/AccumBounds(2, 3) == AccumBounds(Rational(2, 3), 1)286 assert 1/AccumBounds(-1, 1) == AccumBounds(-oo, oo)287 assert abs(AccumBounds(1, 2)) == AccumBounds(1, 2)288 assert abs(AccumBounds(-2, -1)) == AccumBounds(1, 2)289 assert abs(AccumBounds(-2, 1)) == AccumBounds(0, 2)290 assert abs(AccumBounds(-1, 2)) == AccumBounds(0, 2)291 c = Symbol('c')292 raises(ValueError, lambda: AccumBounds(0, c))293 raises(ValueError, lambda: AccumBounds(1, -1))294def test_AccumBounds_mul():295 assert AccumBounds(1, 2)*2 == AccumBounds(2, 4)296 assert 2*AccumBounds(1, 2) == AccumBounds(2, 4)297 assert AccumBounds(1, 2)*AccumBounds(2, 3) == AccumBounds(2, 6)298 assert AccumBounds(1, 2)*0 == 0299 assert AccumBounds(1, oo)*0 == AccumBounds(0, oo)300 assert AccumBounds(-oo, 1)*0 == AccumBounds(-oo, 0)301 assert AccumBounds(-oo, oo)*0 == AccumBounds(-oo, oo)302 assert AccumBounds(1, 2)*x == Mul(AccumBounds(1, 2), x, evaluate=False)303 assert AccumBounds(0, 2)*oo == AccumBounds(0, oo)304 assert AccumBounds(-2, 0)*oo == AccumBounds(-oo, 0)305 assert AccumBounds(0, 2)*(-oo) == AccumBounds(-oo, 0)306 assert AccumBounds(-2, 0)*(-oo) == AccumBounds(0, oo)307 assert AccumBounds(-1, 1)*oo == AccumBounds(-oo, oo)308 assert AccumBounds(-1, 1)*(-oo) == AccumBounds(-oo, oo)309 assert AccumBounds(-oo, oo)*oo == AccumBounds(-oo, oo)310def test_AccumBounds_div():311 assert AccumBounds(-1, 3)/AccumBounds(3, 4) == AccumBounds(Rational(-1, 3), 1)312 assert AccumBounds(-2, 4)/AccumBounds(-3, 4) == AccumBounds(-oo, oo)313 assert AccumBounds(-3, -2)/AccumBounds(-4, 0) == AccumBounds(S.Half, oo)314 # these two tests can have a better answer315 # after Union of AccumBounds is improved316 assert AccumBounds(-3, -2)/AccumBounds(-2, 1) == AccumBounds(-oo, oo)317 assert AccumBounds(2, 3)/AccumBounds(-2, 2) == AccumBounds(-oo, oo)318 assert AccumBounds(-3, -2)/AccumBounds(0, 4) == AccumBounds(-oo, Rational(-1, 2))319 assert AccumBounds(2, 4)/AccumBounds(-3, 0) == AccumBounds(-oo, Rational(-2, 3))320 assert AccumBounds(2, 4)/AccumBounds(0, 3) == AccumBounds(Rational(2, 3), oo)321 assert AccumBounds(0, 1)/AccumBounds(0, 1) == AccumBounds(0, oo)322 assert AccumBounds(-1, 0)/AccumBounds(0, 1) == AccumBounds(-oo, 0)323 assert AccumBounds(-1, 2)/AccumBounds(-2, 2) == AccumBounds(-oo, oo)324 assert 1/AccumBounds(-1, 2) == AccumBounds(-oo, oo)325 assert 1/AccumBounds(0, 2) == AccumBounds(S.Half, oo)326 assert (-1)/AccumBounds(0, 2) == AccumBounds(-oo, Rational(-1, 2))327 assert 1/AccumBounds(-oo, 0) == AccumBounds(-oo, 0)328 assert 1/AccumBounds(-1, 0) == AccumBounds(-oo, -1)329 assert (-2)/AccumBounds(-oo, 0) == AccumBounds(0, oo)330 assert 1/AccumBounds(-oo, -1) == AccumBounds(-1, 0)331 assert AccumBounds(1, 2)/a == Mul(AccumBounds(1, 2), 1/a, evaluate=False)332 assert AccumBounds(1, 2)/0 == AccumBounds(1, 2)*zoo333 assert AccumBounds(1, oo)/oo == AccumBounds(0, oo)334 assert AccumBounds(1, oo)/(-oo) == AccumBounds(-oo, 0)335 assert AccumBounds(-oo, -1)/oo == AccumBounds(-oo, 0)336 assert AccumBounds(-oo, -1)/(-oo) == AccumBounds(0, oo)337 assert AccumBounds(-oo, oo)/oo == AccumBounds(-oo, oo)338 assert AccumBounds(-oo, oo)/(-oo) == AccumBounds(-oo, oo)339 assert AccumBounds(-1, oo)/oo == AccumBounds(0, oo)340 assert AccumBounds(-1, oo)/(-oo) == AccumBounds(-oo, 0)341 assert AccumBounds(-oo, 1)/oo == AccumBounds(-oo, 0)342 assert AccumBounds(-oo, 1)/(-oo) == AccumBounds(0, oo)343def test_issue_18795():344 r = Symbol('r', real=True)345 a = AccumBounds(-1,1)346 c = AccumBounds(7, oo)347 b = AccumBounds(-oo, oo)348 assert c - tan(r) == AccumBounds(7-tan(r), oo)349 assert b + tan(r) == AccumBounds(-oo, oo)350 assert (a + r)/a == AccumBounds(-oo, oo)*AccumBounds(r - 1, r + 1)351 assert (b + a)/a == AccumBounds(-oo, oo)352def test_AccumBounds_func():353 assert (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1)) == AccumBounds(-1, 4)354 assert exp(AccumBounds(0, 1)) == AccumBounds(1, E)355 assert exp(AccumBounds(-oo, oo)) == AccumBounds(0, oo)356 assert log(AccumBounds(3, 6)) == AccumBounds(log(3), log(6))357def test_AccumBounds_pow():358 assert AccumBounds(0, 2)**2 == AccumBounds(0, 4)359 assert AccumBounds(-1, 1)**2 == AccumBounds(0, 1)360 assert AccumBounds(1, 2)**2 == AccumBounds(1, 4)361 assert AccumBounds(-1, 2)**3 == AccumBounds(-1, 8)362 assert AccumBounds(-1, 1)**0 == 1363 assert AccumBounds(1, 2)**Rational(5, 2) == AccumBounds(1, 4*sqrt(2))364 assert AccumBounds(-1, 2)**Rational(1, 3) == AccumBounds(-1, 2**Rational(1, 3))365 assert AccumBounds(0, 2)**S.Half == AccumBounds(0, sqrt(2))366 assert AccumBounds(-4, 2)**Rational(2, 3) == AccumBounds(0, 2*2**Rational(1, 3))367 assert AccumBounds(-1, 5)**S.Half == AccumBounds(0, sqrt(5))368 assert AccumBounds(-oo, 2)**S.Half == AccumBounds(0, sqrt(2))369 assert AccumBounds(-2, 3)**Rational(-1, 4) == AccumBounds(0, oo)370 assert AccumBounds(1, 5)**(-2) == AccumBounds(Rational(1, 25), 1)371 assert AccumBounds(-1, 3)**(-2) == AccumBounds(0, oo)372 assert AccumBounds(0, 2)**(-2) == AccumBounds(Rational(1, 4), oo)373 assert AccumBounds(-1, 2)**(-3) == AccumBounds(-oo, oo)374 assert AccumBounds(-3, -2)**(-3) == AccumBounds(Rational(-1, 8), Rational(-1, 27))375 assert AccumBounds(-3, -2)**(-2) == AccumBounds(Rational(1, 9), Rational(1, 4))376 assert AccumBounds(0, oo)**S.Half == AccumBounds(0, oo)377 assert AccumBounds(-oo, -1)**Rational(1, 3) == AccumBounds(-oo, -1)378 assert AccumBounds(-2, 3)**(Rational(-1, 3)) == AccumBounds(-oo, oo)379 assert AccumBounds(-oo, 0)**(-2) == AccumBounds(0, oo)380 assert AccumBounds(-2, 0)**(-2) == AccumBounds(Rational(1, 4), oo)381 assert AccumBounds(Rational(1, 3), S.Half)**oo is S.Zero382 assert AccumBounds(0, S.Half)**oo is S.Zero383 assert AccumBounds(S.Half, 1)**oo == AccumBounds(0, oo)384 assert AccumBounds(0, 1)**oo == AccumBounds(0, oo)385 assert AccumBounds(2, 3)**oo is oo386 assert AccumBounds(1, 2)**oo == AccumBounds(0, oo)387 assert AccumBounds(S.Half, 3)**oo == AccumBounds(0, oo)388 assert AccumBounds(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero389 assert AccumBounds(-1, Rational(-1, 2))**oo == AccumBounds(-oo, oo)390 assert AccumBounds(-3, -2)**oo == FiniteSet(-oo, oo)391 assert AccumBounds(-2, -1)**oo == AccumBounds(-oo, oo)392 assert AccumBounds(-2, Rational(-1, 2))**oo == AccumBounds(-oo, oo)393 assert AccumBounds(Rational(-1, 2), S.Half)**oo is S.Zero394 assert AccumBounds(Rational(-1, 2), 1)**oo == AccumBounds(0, oo)395 assert AccumBounds(Rational(-2, 3), 2)**oo == AccumBounds(0, oo)396 assert AccumBounds(-1, 1)**oo == AccumBounds(-oo, oo)397 assert AccumBounds(-1, S.Half)**oo == AccumBounds(-oo, oo)398 assert AccumBounds(-1, 2)**oo == AccumBounds(-oo, oo)399 assert AccumBounds(-2, S.Half)**oo == AccumBounds(-oo, oo)400 assert AccumBounds(1, 2)**x == Pow(AccumBounds(1, 2), x)401 assert AccumBounds(2, 3)**(-oo) is S.Zero402 assert AccumBounds(0, 2)**(-oo) == AccumBounds(0, oo)403 assert AccumBounds(-1, 2)**(-oo) == AccumBounds(-oo, oo)404 assert (tan(x)**sin(2*x)).subs(x, AccumBounds(0, pi/2)) == \405 Pow(AccumBounds(-oo, oo), AccumBounds(0, 1))406def test_comparison_AccumBounds():407 assert (AccumBounds(1, 3) < 4) == S.true408 assert (AccumBounds(1, 3) < -1) == S.false409 assert (AccumBounds(1, 3) < 2).rel_op == '<'410 assert (AccumBounds(1, 3) <= 2).rel_op == '<='411 assert (AccumBounds(1, 3) > 4) == S.false412 assert (AccumBounds(1, 3) > -1) == S.true413 assert (AccumBounds(1, 3) > 2).rel_op == '>'414 assert (AccumBounds(1, 3) >= 2).rel_op == '>='415 assert (AccumBounds(1, 3) < AccumBounds(4, 6)) == S.true416 assert (AccumBounds(1, 3) < AccumBounds(2, 4)).rel_op == '<'417 assert (AccumBounds(1, 3) < AccumBounds(-2, 0)) == S.false418 assert (AccumBounds(1, 3) <= AccumBounds(4, 6)) == S.true419 assert (AccumBounds(1, 3) <= AccumBounds(-2, 0)) == S.false420 assert (AccumBounds(1, 3) > AccumBounds(4, 6)) == S.false421 assert (AccumBounds(1, 3) > AccumBounds(-2, 0)) == S.true422 assert (AccumBounds(1, 3) >= AccumBounds(4, 6)) == S.false423 assert (AccumBounds(1, 3) >= AccumBounds(-2, 0)) == S.true424 # issue 13499425 assert (cos(x) > 0).subs(x, oo) == (AccumBounds(-1, 1) > 0)426 c = Symbol('c')427 raises(TypeError, lambda: (AccumBounds(0, 1) < c))428 raises(TypeError, lambda: (AccumBounds(0, 1) <= c))429 raises(TypeError, lambda: (AccumBounds(0, 1) > c))430 raises(TypeError, lambda: (AccumBounds(0, 1) >= c))431def test_contains_AccumBounds():432 assert (1 in AccumBounds(1, 2)) == S.true433 raises(TypeError, lambda: a in AccumBounds(1, 2))434 assert 0 in AccumBounds(-1, 0)435 raises(TypeError, lambda:436 (cos(1)**2 + sin(1)**2 - 1) in AccumBounds(-1, 0))437 assert (-oo in AccumBounds(1, oo)) == S.true438 assert (oo in AccumBounds(-oo, 0)) == S.true439 # issue 13159440 assert Mul(0, AccumBounds(-1, 1)) == Mul(AccumBounds(-1, 1), 0) == 0441 import itertools442 for perm in itertools.permutations([0, AccumBounds(-1, 1), x]):443 assert Mul(*perm) == 0444def test_intersection_AccumBounds():445 assert AccumBounds(0, 3).intersection(AccumBounds(1, 2)) == AccumBounds(1, 2)446 assert AccumBounds(0, 3).intersection(AccumBounds(1, 4)) == AccumBounds(1, 3)447 assert AccumBounds(0, 3).intersection(AccumBounds(-1, 2)) == AccumBounds(0, 2)448 assert AccumBounds(0, 3).intersection(AccumBounds(-1, 4)) == AccumBounds(0, 3)449 assert AccumBounds(0, 1).intersection(AccumBounds(2, 3)) == S.EmptySet450 raises(TypeError, lambda: AccumBounds(0, 3).intersection(1))451def test_union_AccumBounds():452 assert AccumBounds(0, 3).union(AccumBounds(1, 2)) == AccumBounds(0, 3)453 assert AccumBounds(0, 3).union(AccumBounds(1, 4)) == AccumBounds(0, 4)454 assert AccumBounds(0, 3).union(AccumBounds(-1, 2)) == AccumBounds(-1, 3)455 assert AccumBounds(0, 3).union(AccumBounds(-1, 4)) == AccumBounds(-1, 4)456 raises(TypeError, lambda: AccumBounds(0, 3).union(1))457def test_issue_16469():458 x = Symbol("x", real=True)459 f = abs(x)460 assert function_range(f, x, S.Reals) == Interval(0, oo, False, True)461def test_issue_18747():...

Full Screen

Full Screen

rtree.py

Source:rtree.py Github

copy

Full Screen

...33 index of node's parent34 """35 return (node - 1) // 236@ngjit37def _distances_from_bounds(bounds, total_bounds, p):38 n = bounds.shape[1] // 239 dim_ranges = [(total_bounds[d], total_bounds[d + n]) for d in range(n)]40 # Avoid degenerate case where there is a single unique rectangle that is a41 # single point. Increase the range by 1.0 to prevent divide by zero error42 for d in range(n):43 if dim_ranges[d][0] == dim_ranges[d][1]:44 dim_ranges[d] = (dim_ranges[d][0], dim_ranges[d][1] + 1)45 # Compute hilbert distance of the middle of each bounding box46 dim_mids = [(bounds[:, d] + bounds[:, d + n]) / 2.0 for d in range(n)]47 side_length = 2 ** p48 coords = np.zeros((bounds.shape[0], n), dtype=np.int64)49 for d in range(n):50 coords[:, d] = _data2coord(dim_mids[d], dim_ranges[d], side_length)51 hilbert_distances = distances_from_coordinates(p, coords)52 return hilbert_distances53class HilbertRtree:54 """55 This class provides a numba implementation of a read-only Hilbert R-tree56 spatial index57 See https://en.wikipedia.org/wiki/Hilbert_R-tree for more info on the Hilbert R-tree58 This implementation stores the R-tree as an array representation of a binary tree.59 See https://en.wikipedia.org/wiki/Binary_tree#Arrays for more info on the array60 representation of a binary tree.61 """62 @staticmethod63 @ngjit64 def _build_hilbert_rtree(bounds, p, page_size):65 """66 numba function to construct a Hilbert Rtree67 See HilbertRtree.__init__ for parameter descriptions68 """69 # Handle empty bounds array70 if bounds.size == 0:71 return bounds, np.zeros(0, dtype=np.int64), bounds72 # Init bounds_tree array for storing the binary tree representation73 input_size = bounds.shape[0]74 n = bounds.shape[1] // 275 num_pages = int(np.ceil(input_size / page_size))76 tree_depth = int(np.ceil(np.log2(num_pages)))77 next_pow2 = 2 ** tree_depth78 tree_length = next_pow2 * 2 - 179 bounds_tree = np.full((tree_length, 2 * n), np.nan)80 leaf_start = tree_length - next_pow281 # Compute Hilbert distances for inputs82 total_bounds = ([bounds[:, d].min() for d in range(n)] +83 [bounds[:, d + n].max() for d in range(n)])84 hilbert_distances = _distances_from_bounds(bounds, total_bounds, p)85 # Calculate indices needed to sort bounds by hilbert distance86 keys = np.argsort(hilbert_distances)87 # Populate leaves of the tree, one leaf per page. This is layer = tree_depth88 sorted_bounds = bounds[keys, :]89 for page in range(num_pages):90 start = page * page_size91 stop = start + page_size92 page_bounds = sorted_bounds[start:stop, :]93 d_mins = [np.min(page_bounds[:, d]) for d in range(n)]94 d_maxes = [np.max(page_bounds[:, d + n]) for d in range(n)]95 d_ranges = d_mins + d_maxes96 bounds_tree[leaf_start + page, :] = d_ranges97 # Populate internal layers of tree98 layer = tree_depth - 199 start = _parent(tree_length - next_pow2)100 stop = _parent(tree_length - 1)101 while layer >= 0:102 for node in range(start, stop + 1):103 left_bounds = bounds_tree[_left_child(node), :]104 left_valid = not np.isnan(left_bounds[0])105 right_bounds = bounds_tree[_right_child(node), :]106 right_valid = not np.isnan(right_bounds[0])107 if left_valid:108 if right_valid:109 d_mins = [min(left_bounds[d], right_bounds[d]) for d in range(n)]110 d_maxes = [max(left_bounds[d + n], right_bounds[d + n]) for d in range(n)]111 d_ranges = d_mins + d_maxes112 bounds_tree[node, :] = d_ranges113 else:114 bounds_tree[node, :] = left_bounds115 elif right_valid:116 bounds_tree[node, :] = right_bounds117 # update layer, start/stop118 start = _parent(start)119 stop = _parent(stop)120 layer -= 1121 return sorted_bounds, keys, bounds_tree122 def __init__(self, bounds, p=10, page_size=512):123 """124 Construct a new HilbertRtree125 Args:126 bounds: A 2-dimensional numpy array representing a collection of127 n-dimensional bounding boxes. One row per bounding box with128 2*n columns containing the coordinates of each bounding box as follows:129 - bounds[:, 0:n] contains the min values of the bounding boxes,130 one column for each of the n dimensions131 - bounds[:, n+1:2n] contains the max values of the bounding boxes,132 one column for each of the n dimensions133 p: The Hilbert curve order parameter that determines the resolution134 of the 2D grid that data points are rounded to before computing135 their Hilbert distance. Points will be discretized into 2 ** p136 bins in both the x and y dimensions.137 page_size: Number of elements per leaf of the tree.138 """139 # Validate/coerce inputs140 if len(bounds.shape) != 2:141 raise ValueError("bounds must be a 2D array")142 if bounds.shape[1] < 2 or bounds.shape[1] % 2 != 0:143 raise ValueError(144 "The second dimension of bounds must be a multiple of 2 and at least 2"145 )146 self._page_size = max(1, page_size) # 1 is smallest valid page size147 self._numba_rtree = None148 self._sorted_bounds, self._keys, self._bounds_tree = \149 HilbertRtree._build_hilbert_rtree(bounds.astype('float64'), p, self._page_size)150 def __getstate__(self):151 # Remove _NumbaRtree instance during serialization since jitclass instances152 # don't support it.153 state = self.__dict__154 state['_numba_rtree'] = None155 return state156 @property157 def numba_rtree(self):158 """159 Returns:160 _NumbaRtree jitclass instance that is suitable for use inside numba161 functions162 """163 if self._numba_rtree is None:164 self._numba_rtree = _NumbaRtree(165 self._sorted_bounds, self._keys, self._page_size, self._bounds_tree166 )167 return self._numba_rtree168 def intersects(self, bounds):169 """170 Compute the indices of the input bounding boxes that intersect with the171 supplied query bounds172 Args:173 bounds: An array of the form [min0, min1, ..., max0, max1, ...]174 representing the bounds to calculate intersections against175 Returns:176 1d numpy array of the indices of all of the rows in the input bounds array177 that intersect with the query bounds178 """179 bounds = tuple(float(b) for b in bounds)180 return self.numba_rtree.intersects(bounds)181 def covers_overlaps(self, bounds):182 """183 Simultaneously compute the indices of the input bounding boxes that are covered184 by the query bounds and those that overlap with the query bounds185 Args:186 bounds: An array of the form [min0, min1, ..., max0, max1, ...]187 representing the bounds to calculate intersections against188 Returns:189 Tuple of two 1d numpy arrays of indices into the input bounds array.190 * The first array contains indices of all bounding boxes that are fully191 covered by the query bounds.192 * The second array contains the indices of all bounding boxes that193 overlap with one or more edges of the query bounds.194 """195 bounds = tuple(float(b) for b in bounds)196 return self.numba_rtree.covers_overlaps(bounds)197 @property198 def empty(self):199 """200 True if the RTree was created with zero bounding boxes201 """202 return self.numba_rtree._bounds_tree.shape[0] == 0203 @property204 def total_bounds(self):205 """206 Tuple of the total bounds of all bounding boxes207 """208 if not self.empty:209 return tuple(self.numba_rtree._bounds_tree[0, :])210 else:211 return tuple((np.nan,) * self.numba_rtree._bounds_tree.shape[1])212_numbartree_spec = [213 ('_bounds', float64[:, :]),214 ('_keys', int64[:]),215 ('_page_size', int64),216 ('_bounds_tree', float64[:, :]),217]218@jitclass(_numbartree_spec)...

Full Screen

Full Screen

arbitrage.py

Source:arbitrage.py Github

copy

Full Screen

...18 bid = linprog(np.array([ 1, 0]), A_ub, b_ub).x19 ask = linprog(np.array([-1, 0]), A_ub, b_ub).x20 coords = [('side', ['ask', 'bid']), ('asset', ['forward', 'bond'])]21 return xr.DataArray([bid, ask], coords)22def compute_no_arb_bounds(parity, time):23 parity_slice = parity.sel(time=time)24 no_arb_bounds = parity_slice.groupby('expiry', restore_coord_dims=True).map(25 lambda e: compute_no_arb_bounds_map(e.bid, e.ask, e.strike))26 return no_arb_bounds.to_dataset(name='bounds')27def plot_parity_bounds(no_arb_bounds, parity, time, n_expiries):28 no_arb_bounds = no_arb_bounds.bounds29 parity = parity.set_index({'option_id': ['expiry', 'strike']})30 expiries = np.unique(parity.expiry)31 parity_slice = parity.sel(time=time)32 strike_max = np.max(parity_slice.strike.values)33 parity_bid = parity_slice.bid.reset_coords(drop=True34 ).to_series().dropna().unstack('expiry')35 parity_ask = parity_slice.ask.reset_coords(drop=True36 ).to_series().dropna().unstack('expiry')37 parity_bid += parity_bid.index.values[:, None]38 parity_ask += parity_ask.index.values[:, None]39 forward_bounds = no_arb_bounds.sel(asset='forward').to_dataset('side'40 ).reset_coords(drop=True).to_dataframe()41 bond_bounds = no_arb_bounds.sel(asset='bond').to_dataset('side'42 ).reset_coords(drop=True).to_dataframe()43 parity_bounds = pd.concat([forward_bounds,44 forward_bounds - (bond_bounds - 1)*strike_max],45 keys=[0, strike_max], names=['strike'])46 colours = cm.coolwarm(np.linspace(0., 1., len(expiries)))47 fig, axes = plt.subplots(2, 1, sharex=True, figsize=(A4_WIDTH, A4_HEIGHT))48 for ax in axes:49 parity_bid.plot(marker='^', linewidth=0, ax=ax, color=colours,50 markersize=3)51 parity_ask.plot(marker='v', linewidth=0, ax=ax, color=colours,52 markersize=3, legend=False)53 ylim = ax.get_ylim()54 for (_, g), c in zip(parity_bounds.groupby('expiry'), colours):55 g = g.droplevel('expiry')56 ax.fill_between(g.index, g.bid, g.ask, color=c, alpha=.2)57 ax.set_ylim(ylim)58 ax.set_ylabel(r'price minus strike')59 axes[0].get_legend().remove()60 axes[0].set_ylim((parity_bid[expiries[n_expiries - 1]].min(), None))61 return fig62def plot_forward_bounds(no_arb_bounds):63 no_arb_bounds = no_arb_bounds.bounds64 forward_bounds = no_arb_bounds.sel(asset='forward').to_dataset('side'65 ).reset_coords(drop=True).to_dataframe()66 fig, ax = plt.subplots(figsize=(A4_WIDTH, A4_HEIGHT/2))67 ax.fill_between(forward_bounds.index, forward_bounds.bid,68 forward_bounds.ask, step='mid')69 ax.set_xlabel('expiry')70 ax.set_xlabel('forward price')71 return fig72def plot_no_arb_yield_curve(no_arb_bounds, parity):73 no_arb_bounds = no_arb_bounds.bounds74 bond_bounds = no_arb_bounds.sel(asset='bond').to_dataset('side'75 ).reset_coords(drop=True).to_dataframe()76 years_to_expiry = parity.years_to_expiry.groupby('expiry').first(...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ATX automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful